From 733e35b8082f60879da85a184cb9c2c9e3a8fd92 Mon Sep 17 00:00:00 2001 From: Waozi Date: Fri, 20 Nov 2026 13:40:36 -0300 Subject: [PATCH] Fix desktop web scale and deploy exact source builds --- .gitea/workflows/pages.yml | 67 ++++++++++++++++++++++- CHANGELOG.md | 4 ++ locales/changelog/cs.md | 4 ++ locales/changelog/de.md | 4 ++ locales/changelog/es.md | 4 ++ locales/changelog/fr.md | 4 ++ locales/changelog/ja.md | 4 ++ locales/changelog/ko.md | 4 ++ locales/changelog/pt.md | 4 ++ locales/changelog/ru.md | 4 ++ locales/changelog/zh.md | 4 ++ mk/tests-web.mk | 1 + scripts/web-smoke-test.mjs | 103 ++++++++++++++++++++++++++++++++++- site/build-production.sh | 25 +++++---- site/production.mk | 2 +- site/verify-deployment.sh | 12 ++++ site/web-build-key.sh | 16 ++++++ site/web-build-receipt.sh | 41 ++++++++++++++ src/app/dpi_state.zi | 21 ++++++- src/app/web_actions.zi | 3 +- src/web_host.js | 8 +++ tests/site_web_build_test.sh | 36 ++++++++++++ 22 files changed, 357 insertions(+), 18 deletions(-) create mode 100644 site/web-build-key.sh create mode 100644 site/web-build-receipt.sh create mode 100644 tests/site_web_build_test.sh diff --git a/.gitea/workflows/pages.yml b/.gitea/workflows/pages.yml index 45dd35c6e..66487f2b8 100644 --- a/.gitea/workflows/pages.yml +++ b/.gitea/workflows/pages.yml @@ -35,9 +35,71 @@ jobs: with: node-version: 22 + - name: Identify exact web build inputs + id: web-inputs + run: | + key=$(sh site/web-build-key.sh) + printf 'key=%s\n' "$key" >> "$GITHUB_OUTPUT" + + - name: Restore the source-built web app + id: web-restore + uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 + continue-on-error: true + with: + path: build/dist/web + key: breeze-web-${{ runner.os }}-${{ runner.arch }}-${{ steps.web-inputs.outputs.key }} + + - name: Check the cached web build + id: web-cache + env: + WEB_INPUT_KEY: ${{ steps.web-inputs.outputs.key }} + run: | + if sh site/web-build-receipt.sh verify build/dist/web "$WEB_INPUT_KEY" 2>/dev/null; then + echo 'Reusing the verified web build for these inputs' + echo 'ready=true' >> "$GITHUB_OUTPUT" + else + echo 'Building the web app for these inputs' + echo 'ready=false' >> "$GITHUB_OUTPUT" + fi + - name: Install site build dependencies run: USER="$(id -un)" .github/scripts/install-apt-packages.sh .github/apt/empty-packages.txt apt-utils gnupg ripgrep unzip zip zstd + - name: Install web build dependencies + if: steps.web-cache.outputs.ready != 'true' + run: USER="$(id -un)" .github/scripts/install-apt-packages.sh .github/apt/web-packages.txt python3-pil + + - name: Fetch locked Ziran packages + if: steps.web-cache.outputs.ready != 'true' + uses: ./.github/actions/ziran-packages + + - name: Set up the pinned Emscripten SDK + if: steps.web-cache.outputs.ready != 'true' + uses: ./.github/actions/emscripten + + - name: Build the web app from this revision + if: steps.web-cache.outputs.ready != 'true' + env: + WEB_INPUT_KEY: ${{ steps.web-inputs.outputs.key }} + run: | + set -eu + rm -f build/dist/web/index.html build/dist/web/index.js build/dist/web/index.wasm + make -j2 PACKAGE_FLAGS=--locked WEB_CACHE_BUSTER="$WEB_INPUT_KEY" build/dist/web/index.html + sh site/web-build-receipt.sh write build/dist/web "$WEB_INPUT_KEY" + + - name: Verify the exact web app artifact + env: + WEB_INPUT_KEY: ${{ steps.web-inputs.outputs.key }} + run: sh site/web-build-receipt.sh verify build/dist/web "$WEB_INPUT_KEY" + + - name: Save the verified web build for the next deployment + if: gitea.event_name != 'pull_request' && steps.web-cache.outputs.ready != 'true' && steps.web-restore.outputs.cache-hit != 'true' + uses: https://github.com/actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 + continue-on-error: true + with: + path: build/dist/web + key: breeze-web-${{ runner.os }}-${{ runner.arch }}-${{ steps.web-inputs.outputs.key }} + - name: Fetch the pinned site icons from Gitea run: | set -eu @@ -56,14 +118,15 @@ jobs: fi printf 'SITE_APP_HOST=%s\n' "$host" >> "$GITHUB_ENV" - - name: Build site with the published web app and signed download repository + - name: Build site with the source-built web app and signed download repository env: APT_SIGNING_KEY: ${{ gitea.event_name != 'pull_request' && secrets.APT_SIGNING_KEY || '' }} - run: sh site/build-production.sh + run: SITE_WEB_DIR="$PWD/build/dist/web" sh site/build-production.sh - name: Test website routes, assets and Telegram bridge run: | node tests/site_assets_test.mjs + sh tests/site_web_build_test.sh # The APT fixture is designed to check package discovery without root. if [ "$(id -u)" -eq 0 ]; then runuser -u nobody -- sh tests/apt_repo_test.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 67c550f3b..3e11a8855 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ - Reset break timers after time away, match coins and timers to the theme, and claim daily coins in Habits. - See the animated Inner Breeze homepage with a simpler footer and reduced-motion support. +### Web app + +- Open the desktop browser app at a normal scale and keep your Appearance setting. + ## [2.1.63] - 2026-11-05 - Correct text in lists and Lumi without cursor jumps. diff --git a/locales/changelog/cs.md b/locales/changelog/cs.md index d88f6e3fe..56d955bef 100644 --- a/locales/changelog/cs.md +++ b/locales/changelog/cs.md @@ -6,6 +6,10 @@ - Cvičení startují čistě a plynule se přepínají. Pokračujte v relacích, sledujte stahování i obraz v obraze na Androidu. - Časovače se po nečinnosti vynulují, mince i časovače ladí s motivem a v Návycích získáte denní mince. +### Webová aplikace + +- Aplikace se v prohlížeči na počítači otevře v běžné velikosti a zachová nastavení vzhledu. + ## [2.1.63] - 2026-11-05 - Opravujte text v seznamech a Lumi bez přeskakování kurzoru. diff --git a/locales/changelog/de.md b/locales/changelog/de.md index 70aa2ed5d..2763c5707 100644 --- a/locales/changelog/de.md +++ b/locales/changelog/de.md @@ -6,6 +6,10 @@ - Starte Übungen sauber, wechsle flüssig und setze sie fort. Sieh Downloads und nutze Android-Bild-in-Bild. - Pausentimer starten nach Abwesenheit neu. Münzen und Timer folgen dem Design. Hole täglich Münzen in Gewohnheiten. +### Web-App + +- Die App öffnet sich im Desktop-Browser in normaler Größe und behält die Anzeigeeinstellung. + ## [2.1.63] - 2026-11-05 - Korrigiere Text in Listen und Lumi ohne springenden Cursor. diff --git a/locales/changelog/es.md b/locales/changelog/es.md index 29fcebf69..f8c45c877 100644 --- a/locales/changelog/es.md +++ b/locales/changelog/es.md @@ -6,6 +6,10 @@ - Inicia prácticas sin restos, cambia y retoma sesiones. Ve las descargas y usa imagen dentro de imagen en Android. - Los temporizadores se reinician tras una pausa y siguen el tema, al igual que las monedas diarias de Hábitos. +### Aplicación web + +- La aplicación abre con un tamaño normal en el navegador de escritorio y conserva tu ajuste de apariencia. + ## [2.1.63] - 2026-11-05 - Corrige texto en listas y Lumi sin saltos del cursor. diff --git a/locales/changelog/fr.md b/locales/changelog/fr.md index 414e380bc..983ef8872 100644 --- a/locales/changelog/fr.md +++ b/locales/changelog/fr.md @@ -6,6 +6,10 @@ - Lancez les pratiques sans traces, reprenez vos séances et suivez les téléchargements et l’incrustation Android. - Les minuteurs de pause se réinitialisent après une absence. Minuteurs et pièces quotidiennes suivent le thème. +### Application web + +- Dans un navigateur sur ordinateur, l’application s’ouvre à taille normale et conserve votre réglage d’apparence. + ## [2.1.63] - 2026-11-05 - Corrigez le texte des listes et de Lumi sans que le curseur saute. diff --git a/locales/changelog/ja.md b/locales/changelog/ja.md index 45345cec5..818c02efb 100644 --- a/locales/changelog/ja.md +++ b/locales/changelog/ja.md @@ -6,6 +6,10 @@ - 練習開始時の表示の残りを解消しました。練習を滑らかに切り替え、中断したセッションを再開できます。ダウンロードの進捗とAndroidのピクチャーインピクチャーにも対応します。 - アプリをしばらく使わないと休憩タイマーがリセットされ、タイマーとコインはテーマに合った表示になります。習慣で毎日コインを受け取れます。 +### ウェブアプリ + +- デスクトップのブラウザーで通常の大きさで開き、表示設定を保持します。 + ## [2.1.63] - 2026-11-05 - リストとLumiでカーソルが飛ぶことなくテキストを修正できます。 diff --git a/locales/changelog/ko.md b/locales/changelog/ko.md index 1241de954..c6f7e1199 100644 --- a/locales/changelog/ko.md +++ b/locales/changelog/ko.md @@ -6,6 +6,10 @@ - 연습 시작 시 남는 화면을 없앴습니다. 연습을 매끄럽게 전환하고 세션을 재개하세요. 다운로드 진행 상황을 보고 Android 화면 속 화면을 사용하세요. - 자리를 비우면 휴식 타이머가 초기화됩니다. 타이머와 코인은 테마에 맞춰 표시되며 습관에서 매일 코인을 받을 수 있습니다. +### 브라우저 앱 + +- 컴퓨터 브라우저에서 기본 크기로 열고 화면 크기 설정을 유지합니다. + ## [2.1.63] - 2026-11-05 - 목록과 Lumi에서 커서가 튀지 않고 텍스트를 수정할 수 있습니다. diff --git a/locales/changelog/pt.md b/locales/changelog/pt.md index 9dfac5771..d89027f62 100644 --- a/locales/changelog/pt.md +++ b/locales/changelog/pt.md @@ -6,6 +6,10 @@ - Inicie práticas sem resíduos, alterne e retome sessões. Veja downloads e use picture-in-picture no Android. - Os timers de pausa reiniciam após uma ausência. Timers e moedas seguem o tema. Resgate moedas diárias em Hábitos. +### Aplicativo web + +- O aplicativo abre no navegador do computador em tamanho normal e mantém o ajuste de aparência. + ## [2.1.63] - 2026-11-05 - Corrija textos nas listas e no Lumi sem saltos do cursor. diff --git a/locales/changelog/ru.md b/locales/changelog/ru.md index 088802728..ed022b658 100644 --- a/locales/changelog/ru.md +++ b/locales/changelog/ru.md @@ -6,6 +6,10 @@ - Запускайте практики без следов, плавно меняйте и продолжайте сеансы. Видны загрузки и «картинка в картинке» Android. - Таймеры сбрасываются после отсутствия. Таймеры и монеты подходят к теме, а в Привычках есть ежедневные монеты. +### Веб-приложение + +- В браузере на компьютере приложение открывается в обычном масштабе и сохраняет настройку оформления. + ## [2.1.63] - 2026-11-05 - Исправляйте текст в списках и Lumi без скачков курсора. diff --git a/locales/changelog/zh.md b/locales/changelog/zh.md index a2820d25d..f86f27635 100644 --- a/locales/changelog/zh.md +++ b/locales/changelog/zh.md @@ -6,6 +6,10 @@ - 消除练习启动时的残影,平滑切换练习并继续未完成的会话。清楚显示下载进度,并支持 Android 画中画。 - 离开一段时间后,休息计时器会重置。金币与计时器随主题变化,还可在习惯中领取每日金币。 +### 网页应用 + +- 在电脑上以正常大小打开应用,并保留外观中的缩放设置。 + ## [2.1.63] - 2026-11-05 - 在列表和Lumi中修改文字时,光标不再跳动。 diff --git a/mk/tests-web.mk b/mk/tests-web.mk index 08c2c5f84..95c9f7d86 100644 --- a/mk/tests-web.mk +++ b/mk/tests-web.mk @@ -32,6 +32,7 @@ web-window-zi-test: $(ZI2C_BIN) .PHONY: site-assets-test site-assets-test: $(JS_RUNTIME) tests/site_assets_test.mjs + sh tests/site_web_build_test.sh .PHONY: apt-repo-test apt-repo-test: diff --git a/scripts/web-smoke-test.mjs b/scripts/web-smoke-test.mjs index d7077d0a5..a72b84861 100755 --- a/scripts/web-smoke-test.mjs +++ b/scripts/web-smoke-test.mjs @@ -712,6 +712,85 @@ async function verifyAppSettingsReloadPersistence(client) { throw new Error('app settings did not persist across reload'); } +async function verifyBrowserStartupScale(client, url) { + const desktop = { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false }; + const desktopAgent = await pageJson(client, 'navigator.userAgent'); + await client.send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { + window.startupPaintScales = new Map(); + const contexts = [CanvasRenderingContext2D]; + if (typeof OffscreenCanvasRenderingContext2D !== 'undefined') + contexts.push(OffscreenCanvasRenderingContext2D); + for (const { prototype } of contexts) { + const fillText = prototype.fillText; + prototype.fillText = function(text, ...args) { + const canvas = window.Module?.canvas; + if (canvas && this.canvas.width === canvas.width && this.canvas.height === canvas.height) + window.startupPaintScales.set(text, this.getTransform().a / devicePixelRatio); + return fillText.call(this, text, ...args); + }; + } + })()` }); + + let launch = 0; + async function check(metrics, expected) { + const startupUrl = new URL(url); + startupUrl.searchParams.set('startupScaleCase', String(++launch)); + await client.send('Emulation.setDeviceMetricsOverride', metrics); + await client.send('Page.navigate', { url: startupUrl.href }); + await waitForHealthyPage(client); + const state = await pageJson(client, `(() => { + const canvas = Module.canvas; + const rect = canvas.getBoundingClientRect(); + return { width: rect.width, height: rect.height, ratio: devicePixelRatio, + backingWidth: canvas.width, backingHeight: canvas.height, + scales: [...window.startupPaintScales.values()] }; + })()`); + const { width, height, deviceScaleFactor } = metrics; + const atExpectedScale = state.scales.filter(scale => Math.abs(scale - expected) < 0.01); + if (state.width !== width || state.height !== height || state.ratio !== deviceScaleFactor || + state.backingWidth !== Math.round(width * deviceScaleFactor) || + state.backingHeight !== Math.round(height * deviceScaleFactor) || atExpectedScale.length < 4) { + throw new Error(`web startup expected scale ${expected}, metrics ${JSON.stringify(metrics)}: ${JSON.stringify(state)}`); + } + } + + await check(desktop, 1); + await check({ ...desktop, deviceScaleFactor: 2 }, 1); + await check({ ...desktop, width: 1600, height: 1000 }, 1); + + await client.send('Emulation.setUserAgentOverride', { + userAgent: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/131.0.0.0 Mobile Safari/537.36' + }); + await check({ width: 390, height: 844, deviceScaleFactor: 3, mobile: true }, 844 / 560); + await client.send('Emulation.setUserAgentOverride', { userAgent: desktopAgent }); + + const telegram = await client.send('Page.addScriptToEvaluateOnNewDocument', { + source: 'globalThis.InbeTelegramBridge = Object.freeze({});' + }); + await check(desktop, 800 / 560); + await client.send('Page.removeScriptToEvaluateOnNewDocument', telegram); + + await check(desktop, 1); + await pageJson(client, `(async () => { + ${wasmHookEvalHelper()} + await callWasmHook('app_web_test_show_appearance'); + })()`, true); + await waitRouteTransition(client); + await waitAnimationFrames(client, 3); + const slider = await pageJson(client, `({ + x: Module._app_web_test_control_x(140), y: Module._app_web_test_control_y(140), + width: Module._app_web_test_control_width(140), height: Module._app_web_test_control_height(140) + })`); + if (slider.width <= 0 || slider.height <= 0) throw new Error('Appearance UI scale slider is missing'); + // The middle of the 50–250% slider selects 150%. + await dispatchCanvasClick(client, slider.x + slider.width / 2, slider.y + slider.height / 2); + await waitForStorageIdle(client); + const flushed = await pageJson(client, 'Module.__inbeFlushStorageSync(true)', true); + if (!flushed) throw new Error('Could not persist the Appearance UI scale'); + await check({ ...desktop, deviceScaleFactor: 2 }, 1.5); + console.log('web startup scale: desktop 100% at DPR 1 and 2, mobile and Telegram fit, saved 150% restored'); +} + async function verifySetupRouteDoesNotOverrideSavedOnboarding(client, port) { await waitForStorageIdle(client); await client.send('Page.navigate', { url: `http://127.0.0.1:${port}/index.html#/audio_setup` }); @@ -1925,7 +2004,27 @@ try { }); const devtoolsPort = await waitForDevtools(chrome, chromeStderr); - const pages = await jsonRequest(`http://127.0.0.1:${devtoolsPort}/json/new?about:blank`, { + const devtools = `http://127.0.0.1:${devtoolsPort}`; + const url = `http://127.0.0.1:${port}/index.html`; + const browserTarget = await jsonRequest(`${devtools}/json/version`); + const browserClient = await connect(browserTarget.webSocketDebuggerUrl); + try { + // The saved zoom belongs to a disposable context with its own IndexedDB. + const { browserContextId } = await browserClient.send('Target.createBrowserContext', { disposeOnDetach: true }); + const { targetId } = await browserClient.send('Target.createTarget', { url: 'about:blank', browserContextId }); + const targets = await jsonRequest(`${devtools}/json/list`); + const target = targets.find(page => page.id === targetId); + if (!target?.webSocketDebuggerUrl) throw new Error('Chromium scale test could not attach to its page'); + client = await connect(target.webSocketDebuggerUrl); + await client.send('Runtime.enable'); + await client.send('Page.enable'); + await verifyBrowserStartupScale(client, url); + } finally { + browserClient.close(); + } + client.close(); + + const pages = await jsonRequest(`${devtools}/json/new?about:blank`, { method: 'PUT' }); client = await connect(pages.webSocketDebuggerUrl); @@ -1948,7 +2047,7 @@ try { await client.send('Emulation.setCPUThrottlingRate', { rate: Number(process.env.WEB_SMOKE_CPU_THROTTLE) }); - await client.send('Page.navigate', { url: `http://127.0.0.1:${port}/index.html` }); + await client.send('Page.navigate', { url }); await waitForHealthyPage(client); await musicChecks(client); if (process.env.WEB_SMOKE_CPU_THROTTLE) diff --git a/site/build-production.sh b/site/build-production.sh index 14c09d376..506f7b0da 100644 --- a/site/build-production.sh +++ b/site/build-production.sh @@ -1,12 +1,12 @@ #!/bin/sh -# Package current website source with the public, phone-verified app release. +# Package the website with the supplied web artifact and published downloads. set -eu cd "$(dirname "$0")/.." release_dir=build/released-web mkdir -p "$release_dir" curl -fsSL --retry 3 https://api.github.com/repos/waozixyz/breeze/releases/latest -o "$release_dir/release.json" -python3 - "$release_dir/release.json" > "$release_dir/release.env" <<'PY' +python3 - "$release_dir/release.json" "${SITE_WEB_DIR:-}" > "$release_dir/release.env" <<'PY' import json import re import sys @@ -19,21 +19,26 @@ if not match: version = match[1] assets = {asset["name"] for asset in release["assets"]} android = next((name for name in (f"inbe-{version}-arm64-v8a.apk", f"inbe-{version}.apk") if name in assets), None) -if not android or "inbe-web.zip" not in assets: - raise SystemExit("Published release is missing an Android APK or the web bundle") +if not android: + raise SystemExit("Published release is missing an Android APK") +if not sys.argv[2] and "inbe-web.zip" not in assets: + raise SystemExit("Published release is missing the web bundle") print(f"export SITE_RELEASE_VERSION={version}") print(f"export SITE_ANDROID_APK_ASSET={android}") PY . "./$release_dir/release.env" release_url="https://github.com/waozixyz/breeze/releases/download/v$SITE_RELEASE_VERSION" -curl -fsSL --retry 3 "$release_url/inbe-web.zip" -o "$release_dir/inbe-web.zip" -rm -rf "$release_dir/app" -mkdir -p "$release_dir/app" -unzip -q "$release_dir/inbe-web.zip" -d "$release_dir/app" -test -s "$release_dir/app/index.wasm" +if [ -z "${SITE_WEB_DIR:-}" ]; then + curl -fsSL --retry 3 "$release_url/inbe-web.zip" -o "$release_dir/inbe-web.zip" + rm -rf "$release_dir/app" + mkdir -p "$release_dir/app" + unzip -q "$release_dir/inbe-web.zip" -d "$release_dir/app" + SITE_WEB_DIR="$PWD/$release_dir/app" +fi +test -s "$SITE_WEB_DIR/index.wasm" make -f site/production.mk package-unpackaged-assets -SITE_WEB_DIR="$PWD/$release_dir/app" sh site/build.sh +SITE_WEB_DIR="$SITE_WEB_DIR" sh site/build.sh # Gitea's job token is only valid on Gitea. Downloads still follow the public release. env -u GITHUB_TOKEN -u GH_TOKEN make -f site/production.mk site-release-assets-check diff --git a/site/production.mk b/site/production.mk index e697f78cb..c3a044512 100644 --- a/site/production.mk +++ b/site/production.mk @@ -1,4 +1,4 @@ -# Pages uses the released web app and builds only the website's downloads. +# Package the website's downloads independently of the web app toolchain. UNPACKAGED_AUDIO_DIR := unpackaged_assets/audio UNPACKAGED_AUDIO_FILES := $(shell git ls-files -- $(UNPACKAGED_AUDIO_DIR)) MEDITATION_AUDIO_TRACKS := $(patsubst $(UNPACKAGED_AUDIO_DIR)/%,%,$(filter %.ogg,$(UNPACKAGED_AUDIO_FILES))) diff --git a/site/verify-deployment.sh b/site/verify-deployment.sh index da1a38305..2b38d0b2c 100644 --- a/site/verify-deployment.sh +++ b/site/verify-deployment.sh @@ -25,6 +25,18 @@ verify_asset /robots.txt build/site/robots.txt verify_asset /sitemap.xml build/site/sitemap.xml verify_asset /build/web/ build/site/build/web/index.html "$app_host" verify_asset /build/telegram/ build/site/build/telegram/index.html "$app_host" +if [ -f build/site/build/web/source-build.txt ]; then + verify_asset /build/web/source-build.txt build/site/build/web/source-build.txt "$app_host" + verify_asset /build/web/source-build.sha256 build/site/build/web/source-build.sha256 "$app_host" + verify_asset /build/web/index.js build/site/build/web/index.js "$app_host" + IFS= read -r web_key < build/site/build/web/source-build.txt + expected_wasm=$(awk '$2 == "index.wasm" { print $1 }' build/site/build/web/source-build.sha256) + test -n "$expected_wasm" + actual_wasm=$(curl -fsS --compressed --max-time 120 \ + "https://$app_host/build/web/index.wasm?v=$web_key" | sha256sum | cut -d ' ' -f 1) + test "$actual_wasm" = "$expected_wasm" + printf 'Verified the source-built web WASM\n' +fi verify_asset /delete-account build/site/delete-account.html "$app_host" verify_asset /apt/dists/stable/InRelease build/site/apt/dists/stable/InRelease missing_status=$(curl -sS --max-time 20 -o /dev/null -w '%{http_code}' "https://innerbreeze.org/website-missing-route?revision=$revision") diff --git a/site/web-build-key.sh b/site/web-build-key.sh new file mode 100644 index 000000000..fa8049e63 --- /dev/null +++ b/site/web-build-key.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." + +revision=$(git rev-parse --verify "${1:-HEAD}^{commit}") +# The native web producer reads these paths. Site templates and unreleased +# homepage notes do not affect the artifact. +{ + git ls-tree -r "$revision" -- Makefile mk src apps assets design locales scripts \ + manifest.json ziran.toml ziran.lock web-assets site-icons unpackaged_assets \ + .gitattributes .github/emscripten-version .github/apt/web-packages.txt \ + .github/scripts/install-apt-packages.sh \ + .github/actions/emscripten .github/actions/ziran-packages \ + site/web-build-key.sh site/web-build-receipt.sh + git show "$revision:CHANGELOG.md" | sed -n '/^## \[[0-9]/,$p' +} | sha256sum | cut -d ' ' -f 1 diff --git a/site/web-build-receipt.sh b/site/web-build-receipt.sh new file mode 100644 index 000000000..45d2ca14b --- /dev/null +++ b/site/web-build-receipt.sh @@ -0,0 +1,41 @@ +#!/bin/sh +set -eu + +mode=${1:?Specify write or verify} +directory=${2:?Specify the web build directory} +key=${3:?Specify the web build input key} +printf '%s\n' "$key" | grep -qEx '[0-9a-f]{64}' +if [ "$mode" = write ]; then + revision=$(git rev-parse HEAD) +fi +cd "$directory" + +for file in index.html index_boot.js index.js index.wasm webmanifest.json; do + test -s "$file" +done + +artifact_hashes() { + find . -type f ! -path './source-build.txt' ! -path './source-build.sha256' -printf '%P\0' | + LC_ALL=C sort -z | xargs -0 sha256sum -- +} + +case "$mode" in + write) + artifact_hashes > source-build.sha256 + printf '%s\n%s\n' "$key" "$revision" > source-build.txt + ;; + verify) + { + IFS= read -r built_key + IFS= read -r revision + } < source-build.txt + test "$built_key" = "$key" + printf '%s\n' "$revision" | grep -qEx '[0-9a-f]{40}' + printf '%s\n%s\n' "$key" "$revision" | cmp -s - source-build.txt + artifact_hashes | cmp -s - source-build.sha256 + ;; + *) + printf 'Unknown web build receipt mode: %s\n' "$mode" >&2 + exit 2 + ;; +esac diff --git a/src/app/dpi_state.zi b/src/app/dpi_state.zi index ce0428b39..d8a853e29 100644 --- a/src/app/dpi_state.zi +++ b/src/app/dpi_state.zi @@ -12,10 +12,19 @@ dpi_state: DPIState; dpi_user_zoom: float32 = 1.0; last_density: float32; +#if #defined(PLATFORM_WEB) { + browser :: #system_library "browser"; + BrowserUsesViewportScale :: () -> s32 #foreign browser "browser_uses_viewport_scale"; + browser_viewport_scaled: bool; +} + #program_export InitDPI :: () { dpi_state = InitialDPI() last_density = 0.0 + #if #defined(PLATFORM_WEB) { + browser_viewport_scaled = BrowserUsesViewportScale() != 0 + } } #program_export @@ -31,10 +40,18 @@ CurrentDPIPlatform :: () -> DPIPlatform { #program_export UpdateDPI :: (view_width: s32, view_height: s32) { + if dpi_state.base_height == 0 { + InitDPI() + } platform: DPIPlatform = CurrentDPIPlatform() density := device_density() - if dpi_state.base_height == 0 { - dpi_state = InitialDPI() + #if #defined(PLATFORM_WEB) { + // Desktop browser viewports are already in CSS pixels. Use a + // fixed base scale while the canvas handles backing pixel density. + if !browser_viewport_scaled { + platform = cast(DPIPlatform)DPIPlatformDesktop + density = 1.0 + } } if density != last_density { dpi_state = InvalidateDPI(dpi_state) diff --git a/src/app/web_actions.zi b/src/app/web_actions.zi index 8cbbb0e1a..a773e4f4f 100644 --- a/src/app/web_actions.zi +++ b/src/app/web_actions.zi @@ -878,7 +878,8 @@ using AppThemeSource; index: s32 = 0 while index < TreeCount(app.ui.session) { node := TreeNodeAt(app.ui.session, index) - if node.kind == WidgetKindDropdown && node.focus_id == focus_id { + if (node.kind == WidgetKindDropdown || node.kind == WidgetKindSlider) && + node.focus_id == focus_id { top := WorldToScreen(Vector2.{node.bounds.x, node.bounds.y}, app.camera) bottom := WorldToScreen(Vector2.{node.bounds.x + node.bounds.width, node.bounds.y + node.bounds.height}, app.camera) diff --git a/src/web_host.js b/src/web_host.js index 8b6ccb3ac..d3be8f6e2 100644 --- a/src/web_host.js +++ b/src/web_host.js @@ -1,5 +1,13 @@ // Browser effects imported by the Ziran app through Emscripten. addToLibrary({ + browser_uses_viewport_scale: () => { + const mobile = navigator.userAgentData?.mobile || + /Android|iPhone|iPad|iPod/i.test(navigator.userAgent) || + // iPad Safari normally identifies itself as desktop Safari. + (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1); + return mobile || globalThis.InbeTelegramBridge ? 1 : 0; + }, + browser_radio: (action, address, volume) => { let radio = Module.__inbeRadio; if (!radio) { diff --git a/tests/site_web_build_test.sh b/tests/site_web_build_test.sh new file mode 100644 index 000000000..83d21ba46 --- /dev/null +++ b/tests/site_web_build_test.sh @@ -0,0 +1,36 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." + +mkdir -p build/scratch +artifact=$(mktemp -d build/scratch/site-web-build.XXXXXX) +trap 'rm -rf "$artifact"' EXIT +key=$(sh site/web-build-key.sh) +receipt=site/web-build-receipt.sh + +reject() { + if sh "$receipt" verify "$artifact" "$1" 2>/dev/null; then + printf 'Accepted %s\n' "$2" >&2 + exit 1 + fi +} + +reject "$key" 'a cache miss' +for file in index.html index_boot.js index.js index.wasm webmanifest.json; do + printf '%s\n' "$file" > "$artifact/$file" +done +mkdir "$artifact/web-assets" +printf 'asset\n' > "$artifact/web-assets/test asset.txt" +sh "$receipt" write "$artifact" "$key" +sh "$receipt" verify "$artifact" "$key" + +other_key=$(printf '%s\n' "$key" | sha256sum | cut -d ' ' -f 1) +reject "$other_key" 'an artifact for a different source key' +printf '%s\ninvalid-revision\n' "$key" > "$artifact/source-build.txt" +reject "$key" 'an invalid build revision' +sh "$receipt" write "$artifact" "$key" +printf 'modified\n' >> "$artifact/web-assets/test asset.txt" +reject "$key" 'a modified app asset' +rm "$artifact/index.wasm" +reject "$key" 'a missing WASM binary' +printf 'Verified web build receipt and cache miss, stale and corrupt cases\n'