Files
sfhorizont/store/make_screenshots.mjs
T
2026-10-27 21:21:33 +01:00

326 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// App Store screenshots for every locale in store/metadata.json.
//
// 1. python3 store/scene.py <work> (synthetic dusk scene + profile)
// 2. render the scene SVGs, camera video (see store/README.md)
// 3. node store/make_screenshots.mjs <appUrl> <work> [locale…]
//
// The app runs in headless Chrome at iPhone 6.9" size (430×932 pt @3x) in its
// app-shell mode (window.flutter_inappwebview stub), with demo sites seeded
// into localStorage / IndexedDB and a fake camera. Each raw screen is then
// framed with a localized headline into a 1290×2796 App Store image.
import { spawn } from 'node:child_process'
import { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const HERE = dirname(fileURLToPath(import.meta.url))
const ROOT = join(HERE, '..')
const CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
const [appUrl, work, ...only] = process.argv.slice(2)
const meta = JSON.parse(readFileSync(join(HERE, 'metadata.json'), 'utf8'))
const locales = Object.keys(meta).filter((k) => !k.startsWith('_') && (!only.length || only.includes(k)))
const profile = JSON.parse(readFileSync(join(work, 'profile.json'), 'utf8'))
const b64 = (f) => readFileSync(join(work, f)).toString('base64')
const STRIP_FULL = b64('strip_full.png')
const STRIP_PARTIAL = b64('strip_partial.png')
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const SHOTS = ['welcome', 'capture', 'nina', 'pano', 'export', 'sites']
// ---------- Chrome / DevTools plumbing ----------
async function launch(lang, port) {
const profileDir = join(work, `chrome-${lang}`)
rmSync(profileDir, { recursive: true, force: true })
const proc = spawn(CHROME, [
'--headless=new', `--remote-debugging-port=${port}`, `--user-data-dir=${profileDir}`,
'--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream',
`--use-file-for-fake-video-capture=${join(work, 'camera.y4m')}`,
'--ignore-certificate-errors', `--lang=${lang}`, `--accept-lang=${lang}`, '--no-first-run',
'--hide-scrollbars', 'about:blank',
], { stdio: 'ignore' })
let ws
for (let i = 0; i < 60 && !ws; i++) {
try {
const page = (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()).find((t) => t.type === 'page')
if (page) { ws = new WebSocket(page.webSocketDebuggerUrl); break }
} catch { /* starting */ }
await sleep(200)
}
if (!ws) throw new Error('Chrome did not start')
if (ws.readyState !== WebSocket.OPEN) await new Promise((r) => ws.addEventListener('open', r))
let id = 0
const pending = new Map()
ws.addEventListener('message', (e) => {
const m = JSON.parse(e.data)
if (m.id && pending.has(m.id)) {
const { resolve, reject } = pending.get(m.id)
pending.delete(m.id)
m.error ? reject(new Error(m.error.message)) : resolve(m.result)
}
})
const send = (method, params = {}) => new Promise((resolve, reject) => {
const i = ++id
pending.set(i, { resolve, reject })
ws.send(JSON.stringify({ id: i, method, params }))
})
const evaluate = async (expression, userGesture = false) => {
const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, userGesture })
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text)
return r.result.value
}
const close = async () => {
ws.close()
const exited = new Promise((r) => proc.once('exit', r))
proc.kill()
await Promise.race([exited, sleep(5000)])
try { rmSync(profileDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }) } catch { /* leftover temp profile */ }
}
return { send, evaluate, close }
}
// ---------- demo data ----------
function demoSites(names) {
const now = Date.now()
const iso = (dt) => new Date(now - dt).toISOString()
return [
{
id: 'demoA', name: names[0], createdAt: iso(9e8), updatedAt: iso(1e5), source: 'survey',
location: { latDeg: 47.4979, lonDeg: 19.0402, elevM: 112, accuracyM: 4 }, status: 'complete',
frames: 24, cells: Array(24).fill(true), profile, coverage: Array(360).fill(1),
marginDeg: 2, northOffsetDeg: 0, edits: [], exported: { nina: true, stellarium: true }, hasStrip: true,
},
{
id: 'demoB', name: names[1], createdAt: iso(3e8), updatedAt: iso(2e5), source: 'survey',
location: { latDeg: 46.9012, lonDeg: 18.0457, elevM: 412, accuracyM: 6 }, status: 'in-progress',
frames: 14, cells: Array.from({ length: 24 }, (_, i) => i < 14), profile,
coverage: Array.from({ length: 360 }, (_, d) => (d < 210 ? 1 : 0)),
marginDeg: 2, northOffsetDeg: 0, edits: [], exported: { nina: false, stellarium: false }, hasStrip: true,
},
]
}
const seedScript = (sites) => `(async () => {
const blob = (b64) => new Blob([Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))], { type: 'image/png' })
const db = await new Promise((res, rej) => {
const r = indexedDB.open('sfzenith', 1)
r.onupgradeneeded = () => r.result.createObjectStore('strips')
r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error)
})
await new Promise((res, rej) => {
const t = db.transaction('strips', 'readwrite')
t.objectStore('strips').put(blob('${STRIP_FULL}'), 'demoA')
t.objectStore('strips').put(blob('${STRIP_PARTIAL}'), 'demoB')
t.oncomplete = res; t.onerror = () => rej(t.error)
})
db.close()
localStorage.setItem('sfz.sites.v1', ${JSON.stringify(JSON.stringify(sites))})
localStorage.setItem('sfz.settings.v1', JSON.stringify({ welcomed: true, autoCapture: true, fovDeg: null, author: '' }))
return true
})()`
// ---------- raw app screens ----------
async function rawScreens(locale, port) {
const m = meta[locale]
const out = join(work, locale)
mkdirSync(out, { recursive: true })
const b = await launch(m.app, port)
const { send, evaluate } = b
const shot = async (name) => {
const r = await send('Page.captureScreenshot', { format: 'png' })
writeFileSync(join(out, `raw-${name}.png`), Buffer.from(r.data, 'base64'))
}
const waitFor = async (expr, ms = 20000) => {
const t0 = Date.now()
while (Date.now() - t0 < ms) {
if (await evaluate(expr).catch(() => false)) return
await sleep(150)
}
throw new Error(`${locale}: timeout waiting for ${expr}`)
}
const click = (sel, i = 0) => evaluate(`(() => { const el = document.querySelectorAll(${JSON.stringify(sel)})[${i}]; if (!el) throw new Error('no ${sel}'); el.click(); return true })()`, true)
try {
await send('Page.enable')
await send('Runtime.enable')
await send('Emulation.setDeviceMetricsOverride', { width: 430, height: 932, deviceScaleFactor: 3, mobile: true })
await send('Emulation.setTouchEmulationEnabled', { enabled: true })
await send('Browser.grantPermissions', { origin: new URL(appUrl).origin, permissions: ['geolocation', 'videoCapture', 'sensors'] })
// App-shell mode: the page sees the Flutter bridge and the system bar insets.
await send('Page.addScriptToEvaluateOnNewDocument', { source: `
window.flutter_inappwebview = { callHandler: () => Promise.resolve(undefined) };
// documentElement does not exist yet at document start.
new MutationObserver((_, obs) => {
if (!document.documentElement) return;
document.documentElement.style.setProperty('--safe-top', '59px');
document.documentElement.style.setProperty('--safe-bottom', '34px');
obs.disconnect();
}).observe(document, { childList: true });` })
await send('Page.navigate', { url: appUrl })
await waitFor(`!!document.querySelector('.btn-primary')`)
await sleep(1500)
await shot('welcome')
await evaluate(seedScript(demoSites(m.sites)))
await send('Page.navigate', { url: appUrl })
await waitFor(`document.querySelectorAll('.site-card').length === 2`)
await sleep(1200)
// Sites with the bottom 83 pt left for the native tab bar drawn in the frame.
await evaluate(`document.documentElement.style.setProperty('--safe-bottom', '83px')`)
await sleep(300)
await shot('sites')
await evaluate(`document.documentElement.style.setProperty('--safe-bottom', '34px')`)
await click('.site-card', 0) // complete site → Review
await waitFor(`!!document.querySelector('.slider')`, 30000)
await sleep(800)
await shot('nina')
await click('.segmented button', 1) // Panorama tab
await waitFor(`!!document.querySelector('.pano-zoom canvas')`)
await sleep(800)
await click('.segmented button', 3) // Paint sky
await sleep(200)
await evaluate(`(() => { const c = document.querySelector('.pano-zoom canvas'); const r = c.getBoundingClientRect();
c.dispatchEvent(new PointerEvent('pointermove', { clientX: r.left + r.width * 0.73, clientY: r.top + r.height * 0.3, bubbles: true })); return true })()`)
await sleep(400)
await shot('pano')
await click('.screen-actions .btn-primary') // Export
await waitFor(`!!document.querySelector('.format-card')`)
await sleep(1200)
await shot('export')
await evaluate(`window.__sfzNav('sites')`)
await waitFor(`document.querySelectorAll('.site-card').length === 2`)
const idx = await evaluate(`[...document.querySelectorAll('.site-card')].findIndex(c => c.querySelector('.badge-amber'))`)
await click('.site-card', idx) // in-progress site → Capture
await waitFor(`!!document.querySelector('.cap-panel') && !document.querySelector('.cap-start')`, 30000)
await sleep(1500)
// Simulated compass (?sim): turn to 204°, the next empty cell is at 217.5°.
await evaluate(`(() => { for (let i = 0; i < 68; i++) window.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); return true })()`)
await sleep(2000)
await shot('capture')
} finally {
await b.close()
}
}
// ---------- App Store frames ----------
async function importLocale(app) {
return (await import(pathToFileURL(join(ROOT, `wasm/frontend/src/i18n/locales/${app}.js`)).href)).default
}
const fontDir = pathToFileURL(join(ROOT, 'wasm/frontend/node_modules/@fontsource/barlow/files')).href
// App Store: 1290×2796 with an iPhone frame. Play: 1440×2560 (9:16; Play rejects
// images longer than 2:1) with a generic phone outline and no Dynamic Island.
const FRAME = {
appstore: { W: 1290, H: 2796, scale: 0.79, bottom: 60, h1Top: 150, h1Size: 92, island: true },
play: { W: 1440, H: 2560, scale: 0.68, bottom: 70, h1Top: 120, h1Size: 84, island: false },
}
function frameHtml({ raw, caption, rtl, tabs, kind = 'appstore' }) {
const { W, H, scale, bottom, h1Top, h1Size, island } = FRAME[kind]
const sw = Math.round(1290 * scale), sh = Math.round(2796 * scale)
const left = Math.round((W - sw) / 2), top = H - sh - bottom
const px = (v) => Math.round(v * 3 * scale) // app points → frame pixels
const r = (v) => Math.round(v * scale / 0.79) // radii tuned for the App Store frame
const tabBar = tabs ? `
<div class="tabbar" style="height:${px(83)}px">
${tabs.map((t, i) => `<div class="tab${i === 0 ? ' on' : ''}">
<div class="pill" style="width:${px(58)}px;height:${px(30)}px;border-radius:${px(15)}px">${t.icon}</div>
<div class="lbl" style="font-size:${px(11)}px;margin-top:${px(3)}px">${t.label}</div></div>`).join('')}
</div>` : ''
return `<!doctype html><html dir="${rtl ? 'rtl' : 'ltr'}"><head><meta charset="utf-8"><style>
@font-face { font-family: Barlow; font-weight: 700; src: url('${fontDir}/barlow-latin-700-normal.woff2') format('woff2'); }
@font-face { font-family: Barlow; font-weight: 700; src: url('${fontDir}/barlow-latin-ext-700-normal.woff2') format('woff2'); unicode-range: U+0100-024F; }
html, body { margin: 0; width: ${W}px; height: ${H}px; overflow: hidden; }
body { background: radial-gradient(120% 70% at 70% 0%, #1B2B4A 0%, #0B1222 45%, #04060B 100%); font-family: Barlow, 'Geeza Pro', system-ui, sans-serif; }
.stars { position: absolute; inset: 0; background-image:
radial-gradient(2px 2px at 120px 160px, #fff8, transparent), radial-gradient(2px 2px at 980px 90px, #fff9, transparent),
radial-gradient(1.5px 1.5px at 400px 320px, #fff6, transparent), radial-gradient(2px 2px at 1180px 420px, #fff7, transparent),
radial-gradient(1.5px 1.5px at 760px 250px, #fff5, transparent), radial-gradient(2.5px 2.5px at 230px 470px, #FFE9C7aa, transparent); }
h1 { position: absolute; left: 90px; right: 90px; top: ${h1Top}px; margin: 0; color: #E8ECF2; font-weight: 700;
font-size: ${h1Size}px; line-height: 1.12; text-align: center; letter-spacing: -0.01em; }
h1 em { color: #F5B544; font-style: normal; }
${kind === 'play' ? `h1 { top: 0; height: ${top - 18}px; display: flex; align-items: center; justify-content: center; }` : ''}
.device { position: absolute; left: ${left - 18}px; top: ${top - 18}px; width: ${sw + 36}px; height: ${sh + 36}px;
border-radius: ${r(120)}px; background: #1A2130; box-shadow: 0 40px 120px #000a, inset 0 0 0 3px #2B3446; }
.screen { position: absolute; left: ${left}px; top: ${top}px; width: ${sw}px; height: ${sh}px; border-radius: ${r(104)}px; overflow: hidden; background: #000; }
.screen img { width: 100%; height: 100%; display: block; }
.status { position: absolute; left: 0; right: 0; top: 0; height: ${px(54)}px; display: flex; align-items: center;
justify-content: space-between; padding: 0 ${px(34)}px; color: #fff; font: 600 ${px(17)}px -apple-system, system-ui, sans-serif; direction: ltr; }
.island { position: absolute; left: 50%; top: ${px(11)}px; width: ${px(125)}px; height: ${px(37)}px; margin-left: -${px(62.5)}px; border-radius: ${px(19)}px; background: #000; }
.home { position: absolute; left: 50%; bottom: ${px(8)}px; width: ${px(140)}px; height: ${px(5)}px; margin-left: -${px(70)}px; border-radius: 9px; background: #fff; opacity: .85; }
.tabbar { position: absolute; left: 0; right: 0; bottom: 0; background: #0A0D13; border-top: 2px solid #1E2634; display: flex; padding-top: ${px(8)}px; box-sizing: border-box; }
.tab { flex: 1; display: flex; flex-direction: column; align-items: center; color: #93A0B4; font-family: system-ui, sans-serif; font-weight: 600; }
.tab .pill { display: flex; align-items: center; justify-content: center; }
.tab.on { color: #F5B544; } .tab.on .pill { background: #2A2312; }
.tab svg { width: ${px(22)}px; height: ${px(22)}px; }
</style></head><body><div class="stars"></div>
<h1>${caption}</h1>
<div class="device"></div>
<div class="screen"><img src="${raw}">
<div class="status"><span>9:41</span><span style="display:flex;gap:${px(6)}px;align-items:center">
<svg width="${px(18)}" height="${px(12)}" viewBox="0 0 18 12"><g fill="#fff"><rect x="0" y="8" width="3" height="4" rx="1"/><rect x="5" y="5.5" width="3" height="6.5" rx="1"/><rect x="10" y="3" width="3" height="9" rx="1"/><rect x="15" y="0" width="3" height="12" rx="1"/></g></svg>
<svg width="${px(16)}" height="${px(12)}" viewBox="0 0 16 12"><path d="M8 11.5 5.6 9a3.4 3.4 0 0 1 4.8 0zM3.4 6.8a6.6 6.6 0 0 1 9.2 0l-1.4 1.4a4.6 4.6 0 0 0-6.4 0zM1 4.4a10 10 0 0 1 14 0l-1.4 1.4a8 8 0 0 0-11.2 0z" fill="#fff"/></svg>
<svg width="${px(27)}" height="${px(13)}" viewBox="0 0 27 13"><rect x=".5" y=".5" width="23" height="12" rx="3.5" fill="none" stroke="#fff" opacity=".45"/><rect x="2" y="2" width="20" height="9" rx="2" fill="#fff"/><rect x="24.5" y="4" width="2" height="5" rx="1" fill="#fff" opacity=".45"/></svg>
</span></div>
${island ? '<div class="island"></div>' : ''}
${tabBar}
<div class="home"></div>
</div></body></html>`
}
// Tab icons approximating the app's CupertinoIcons (square_stack_3d_up, plus_circle, slider_horizontal_3).
const TAB_ICONS = [
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"><path d="M12 3 3 7.5 12 12l9-4.5z"/><path d="M3 12l9 4.5 9-4.5"/><path d="M3 16.5 12 21l9-4.5"/></svg>',
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></svg>',
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M3 6h18M3 12h18M3 18h18"/><circle cx="15" cy="6" r="2" fill="#0A0D13"/><circle cx="8" cy="12" r="2" fill="#0A0D13"/><circle cx="17" cy="18" r="2" fill="#0A0D13"/></svg>',
]
async function frames(locale) {
const m = meta[locale]
const msgs = await importLocale(m.app)
const out = join(work, locale)
const rtl = m.app === 'ar'
for (const [i, name] of SHOTS.entries()) {
const raw = join(out, `raw-${name}.png`)
if (!existsSync(raw)) continue
const tabs = name === 'sites'
? ['sites', 'new', 'settings'].map((k, j) => ({ label: msgs[`tab.${k}`], icon: TAB_ICONS[j] }))
: null
const tabsOrdered = tabs && rtl ? [...tabs] : tabs // dir=rtl on <html> mirrors the flex row
// App Store images in <locale>/, Google Play images in <locale>/play/.
for (const kind of ['appstore', 'play']) {
const dir = kind === 'play' ? join(out, 'play') : out
mkdirSync(dir, { recursive: true })
const html = join(dir, `frame-${name}.html`)
writeFileSync(html, frameHtml({ raw: pathToFileURL(raw).href, caption: m.captions[i], rtl, tabs: tabsOrdered, kind }))
const png = join(dir, `${String(i + 1).padStart(2, '0')}-${name}.png`)
const { W, H } = FRAME[kind]
const render = () => new Promise((res) => {
const p = spawn(CHROME, ['--headless=new', '--hide-scrollbars', '--allow-file-access-from-files',
'--force-device-scale-factor=1', `--window-size=${W},${H}`, `--screenshot=${png}`, pathToFileURL(html).href], { stdio: 'ignore' })
p.on('exit', (c) => res(c === 0))
})
let ok = false
for (let attempt = 0; attempt < 3 && !ok; attempt++) ok = await render() // headless Chrome occasionally exits non-zero
if (!ok) throw new Error(`frame render failed: ${png}`)
}
}
}
// FRAMES_ONLY=1 re-frames existing raw-*.png without re-running the app.
let port = 9400
for (const locale of locales) {
process.stdout.write(`${locale}: screens… `)
if (!process.env.FRAMES_ONLY) await rawScreens(locale, port++)
process.stdout.write('frames… ')
await frames(locale)
console.log('done')
}