Add browser playtest and improve library, media and input
Bundle web bootstrap, icons, local font fallbacks and hosting instructions. Add optimized WebP/MP3 packaging, asset checks and a browser narration regression tool. Support browser audio handoff and ad-free explained hints. Refresh the responsive bookshelf and reduce unnecessary app, narration and paper repaint work. Preserve deliberate page swipes while tolerating small mouse movements during cell and navigation clicks. Validation: all 77 Flutter tests pass; shell, JavaScript and Python scripts parse; locale and web manifests are valid JSON; git diff --check passes.
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Override FLUTTER_BIN when Flutter is not on PATH.
|
||||
flutter_bin="${FLUTTER_BIN:-flutter}"
|
||||
pub_options=()
|
||||
if [[ "${PUB_OFFLINE:-0}" == 1 ]]; then pub_options+=(--offline); fi
|
||||
"$flutter_bin" pub get "${pub_options[@]}"
|
||||
"$flutter_bin" build web --wasm --release --no-pub --no-web-resources-cdn --dart-define=WEB_OPTIMIZED_MEDIA=true "$@"
|
||||
python3 scripts/optimize_web_media.py build/web
|
||||
python3 scripts/check_web_assets.py build/web
|
||||
mkdir -p artifacts
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile, ZIP_DEFLATED
|
||||
|
||||
output = Path('artifacts/lumen-browser-playtest.zip')
|
||||
with ZipFile(output, 'w', ZIP_DEFLATED) as archive:
|
||||
for path in sorted(Path('build/web').rglob('*')):
|
||||
if path.is_file():
|
||||
archive.write(path, path.relative_to('build/web'))
|
||||
archive.write('docs/BROWSER_PLAYTEST.md', 'HOSTING.md')
|
||||
print(f'Browser playtest: {output.resolve()} ({output.stat().st_size / 1024**2:.1f} MiB)')
|
||||
PY
|
||||
@@ -0,0 +1,115 @@
|
||||
// Node 22+, a local preview, and a dedicated Chrome with --remote-debugging-port=9224.
|
||||
// Each run uses a fresh browser context; existing tabs and saved games are untouched.
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const appUrl = process.argv[2] || 'http://127.0.0.1:8080/';
|
||||
const debuggerUrl = process.env.CHROME_DEBUG_URL || 'http://127.0.0.1:9224';
|
||||
const browser = await (await fetch(`${debuggerUrl}/json/version`)).json();
|
||||
const socket = new WebSocket(browser.webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.onopen = resolve;
|
||||
socket.onerror = reject;
|
||||
});
|
||||
let serial = 0;
|
||||
const pending = new Map();
|
||||
socket.onmessage = ({ data }) => {
|
||||
const response = JSON.parse(data);
|
||||
if (!response.id) return;
|
||||
const request = pending.get(response.id);
|
||||
if (!request) return;
|
||||
clearTimeout(request.timer);
|
||||
pending.delete(response.id);
|
||||
if (response.error) request.reject(new Error(JSON.stringify(response.error)));
|
||||
else request.resolve(response.result);
|
||||
};
|
||||
function call(method, params = {}, sessionId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++serial;
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
reject(new Error(`Timed out: ${method}`));
|
||||
}, 15000);
|
||||
pending.set(id, { resolve, reject, timer });
|
||||
socket.send(JSON.stringify({ id, method, params, sessionId }));
|
||||
});
|
||||
}
|
||||
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const { browserContextId } = await call('Target.createBrowserContext');
|
||||
try {
|
||||
const { targetId } = await call('Target.createTarget', { url: 'about:blank', browserContextId });
|
||||
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
|
||||
const page = (method, params) => call(method, params, sessionId);
|
||||
async function evaluate(expression) {
|
||||
const result = await page('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, userGesture: true });
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
return result.result.value;
|
||||
}
|
||||
const controls = async () => (await page('Accessibility.getFullAXTree')).nodes;
|
||||
async function until(check, description, timeout = 15000) {
|
||||
const deadline = Date.now() + timeout;
|
||||
do {
|
||||
if (await check()) return;
|
||||
await wait(100);
|
||||
} while (Date.now() < deadline);
|
||||
throw new Error(`Timed out waiting for ${description}`);
|
||||
}
|
||||
async function click(prefix, role = 'button') {
|
||||
let node;
|
||||
await until(async () => {
|
||||
node = (await controls()).find(n => n.role?.value === role && n.name?.value?.startsWith(prefix));
|
||||
return !!node;
|
||||
}, prefix);
|
||||
const { object } = await page('DOM.resolveNode', { backendNodeId: node.backendDOMNodeId });
|
||||
if (role === 'button') {
|
||||
await page('Runtime.callFunctionOn', { objectId: object.objectId, functionDeclaration: 'function(){this.click()}', userGesture: true });
|
||||
} else {
|
||||
// Book cards currently merge their progress bar into their semantics.
|
||||
const result = await page('Runtime.callFunctionOn', {
|
||||
objectId: object.objectId, returnByValue: true,
|
||||
functionDeclaration: 'function(){const r=this.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}}',
|
||||
});
|
||||
for (const type of ['mousePressed', 'mouseReleased']) {
|
||||
await page('Input.dispatchMouseEvent', { type, ...result.result.value, button: 'left', clickCount: 1 });
|
||||
}
|
||||
}
|
||||
await wait(150);
|
||||
}
|
||||
const audio = () => evaluate(`window.__narrationTestAudio.map(a=>({src:a.src,paused:a.paused,time:a.currentTime}))`);
|
||||
async function expectRecording(filename) {
|
||||
await until(async () => (await audio()).some(a => a.src.endsWith(filename) && !a.paused && a.time > .1), filename, 7000);
|
||||
const voices = (await audio()).filter(a => /narration_|midnight_/.test(a.src) && !/ambience|atmosphere/.test(a.src));
|
||||
assert(voices.filter(a => !a.paused).every(a => a.src.endsWith(filename)), 'An old recording is still playing');
|
||||
console.log(`Playing correct file: ${filename}`);
|
||||
}
|
||||
await page('Page.enable');
|
||||
await page('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
|
||||
await page('Page.addScriptToEvaluateOnNewDocument', { source: `
|
||||
localStorage.setItem('language', JSON.stringify('en'));
|
||||
window.__narrationTestAudio = [];
|
||||
const play = HTMLMediaElement.prototype.play;
|
||||
HTMLMediaElement.prototype.play = function(...args) {
|
||||
if (!window.__narrationTestAudio.includes(this)) window.__narrationTestAudio.push(this);
|
||||
return play.apply(this, args);
|
||||
};
|
||||
` });
|
||||
await page('Page.navigate', { url: appUrl });
|
||||
await until(() => evaluate(`!!document.querySelector('flt-semantics-placeholder')`), 'game startup', 30000);
|
||||
await evaluate(`document.querySelector('flt-semantics-placeholder').click()`);
|
||||
await click('Mara’s notebook', 'progressbar');
|
||||
await click('Open Mara’s notebook');
|
||||
await expectRecording('narration_cottage_dedication.mp3');
|
||||
await click('Next leaf');
|
||||
await expectRecording('narration_cottage_window.mp3');
|
||||
await click('← Previous leaf');
|
||||
await expectRecording('narration_cottage_dedication.mp3');
|
||||
await click('Next leaf');
|
||||
await click('Next leaf');
|
||||
await wait(3500);
|
||||
assert((await audio()).filter(a => a.src.includes('narration_cottage_')).every(a => a.paused), 'A skipped leaf started narrating');
|
||||
await click('← Previous leaf');
|
||||
await expectRecording('narration_cottage_window.mp3');
|
||||
console.log('Next, previous and rapid page turns use the correct narration.');
|
||||
} finally {
|
||||
await call('Target.disposeBrowserContext', { browserContextId });
|
||||
socket.close();
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check all story/art/audio references in a deployable Flutter web bundle."""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(sys.argv[1] if len(sys.argv) > 1 else 'build/web')
|
||||
missing = []
|
||||
references = set()
|
||||
|
||||
|
||||
def visit(value):
|
||||
if isinstance(value, dict):
|
||||
for item in value.values():
|
||||
visit(item)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
visit(item)
|
||||
elif isinstance(value, str) and value.startswith('assets/'):
|
||||
references.add(value)
|
||||
path = root / 'assets' / value
|
||||
if path.suffix in ('.png', '.wav'):
|
||||
path = path.with_suffix('.webp' if path.suffix == '.png' else '.mp3')
|
||||
if not path.is_file():
|
||||
missing.append(value)
|
||||
|
||||
|
||||
for name in ['index.html', 'flutter_bootstrap.js', 'main.dart.js',
|
||||
'manifest.json', 'main.dart.wasm', 'main.dart.mjs', 'assets/AssetManifest.bin.json',
|
||||
'assets/assets/fonts/DancingScript.ttf']:
|
||||
if not (root / name).is_file():
|
||||
missing.append(name)
|
||||
|
||||
font_manifest = root / 'assets/FontManifest.json'
|
||||
if font_manifest.is_file():
|
||||
visit(json.loads(font_manifest.read_text()))
|
||||
|
||||
for path in (root / 'assets/assets').rglob('*.json'):
|
||||
data = json.loads(path.read_text())
|
||||
visit(data)
|
||||
# Mara's original manifest uses filenames instead of asset paths.
|
||||
if path.name == 'narration_manifest.json':
|
||||
for track in data.get('tracks', {}).values():
|
||||
if 'file' in track and 'asset' not in track:
|
||||
visit('assets/audio/' + track['file'])
|
||||
|
||||
if missing:
|
||||
raise SystemExit('Missing bundled files:\n' + '\n'.join(sorted(set(missing))))
|
||||
print(f'Web bundle verified: {len(references)} referenced assets present.')
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Emit web-only WebP/MP3 copies. Original game assets are never changed."""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('build', type=Path, nargs='?', default=Path('build/web'))
|
||||
args = parser.parse_args()
|
||||
assets = args.build / 'assets/assets'
|
||||
sources = sorted([*assets.rglob('*.png'), *assets.rglob('*.wav')])
|
||||
before = sum(p.stat().st_size for p in sources)
|
||||
|
||||
|
||||
def convert(path):
|
||||
if path.suffix == '.png':
|
||||
target = path.with_suffix('.webp')
|
||||
with Image.open(path) as image:
|
||||
# Keep full-size notebook textures; illustrations need fewer pixels.
|
||||
max_size = (1536, 1536) if 'page' in path.name else (1024, 1024)
|
||||
image.thumbnail(max_size, Image.Resampling.LANCZOS)
|
||||
image.save(target, 'WEBP', quality=86, method=6)
|
||||
else:
|
||||
target = path.with_suffix('.mp3')
|
||||
subprocess.run([
|
||||
'ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(path),
|
||||
'-codec:a', 'libmp3lame', '-b:a', '64k', str(target),
|
||||
], check=True)
|
||||
size = target.stat().st_size
|
||||
path.unlink()
|
||||
return size
|
||||
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
after = sum(pool.map(convert, sources))
|
||||
print(f'Web media: {before / 1024**2:.1f} → {after / 1024**2:.1f} MiB '
|
||||
f'({100 * (1 - after / before):.0f}% smaller; {len(sources)} files).')
|
||||
Reference in New Issue
Block a user