From 637129aa4ed03b533a566ac9013eead698a7352c Mon Sep 17 00:00:00 2001 From: Sprite Date: Mon, 23 Nov 2026 01:02:08 +0000 Subject: [PATCH] Add the web runtime (DOM patcher, events, host bridge) and a browser e2e web/ is the js-target MoonBit program: it renders app.view into the DOM with a keyed patcher, turns pointer/touch/key events into app input, runs effects against window.Android or demo stand-ins, and exposes window.launcher.* for the Android shell. tests/e2e.cjs ports the legacy Playwright flows and passes against the build; scripts/build-web.sh assembles dist/web. Co-Authored-By: Claude Sonnet 5.5 --- app/pkg.generated.mbti | 2 + scripts/build-web.sh | 14 ++ tests/e2e.cjs | 217 +++++++++++++++++++ web/ffi.mbt | 361 ++++++++++++++++++++++++++++++++ web/index.html | 18 ++ web/main.mbt | 465 +++++++++++++++++++++++++++++++++++++++++ web/moon.pkg | 13 ++ web/patch.mbt | 188 +++++++++++++++++ web/pkg.generated.mbti | 15 ++ web/style.css | 261 +++++++++++++++++++++++ 10 files changed, 1554 insertions(+) create mode 100755 scripts/build-web.sh create mode 100644 tests/e2e.cjs create mode 100644 web/ffi.mbt create mode 100644 web/index.html create mode 100644 web/main.mbt create mode 100644 web/moon.pkg create mode 100644 web/patch.mbt create mode 100644 web/pkg.generated.mbti create mode 100644 web/style.css diff --git a/app/pkg.generated.mbti b/app/pkg.generated.mbti index d6bdcaa..7cf6c8c 100644 --- a/app/pkg.generated.mbti +++ b/app/pkg.generated.mbti @@ -65,6 +65,7 @@ pub(all) enum Edge { Corner } +#derive(Eq, @debug.Debug) pub(all) enum Effect { Launch(String) AppInfo(String) @@ -156,6 +157,7 @@ pub fn Model::packed(Self) -> @grid.Packed pub fn Model::slot_of_widget(Self, Int32) -> Int32 pub fn Model::widget_matches(Self, Int32) -> Bool +#derive(Eq, @debug.Debug) pub(all) enum Msg { Restore(saved~ : String?, legacy~ : String?) Started(now~ : Int64, last_check~ : Int64, declined~ : Int32, installed~ : Int32) diff --git a/scripts/build-web.sh b/scripts/build-web.sh new file mode 100755 index 0000000..d9078c9 --- /dev/null +++ b/scripts/build-web.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Builds the page: the MoonBit program (web/*.mbt, js backend) plus its static files, +# into dist/web/. With --demo the browser demo's apps.json and widgets.json come too; +# the APK build leaves them out (the shell answers those URLs itself). +set -euo pipefail +cd "$(dirname "$0")/.." +export PATH="$HOME/.moon/bin:$PATH" +moon build --target js --release +out=dist/web +rm -rf "$out" && mkdir -p "$out" +cp _build/js/release/build/web/web.js "$out/launcher.js" +cp web/index.html web/style.css "$out/" +if [ "${1:-}" = "--demo" ]; then cp web/apps.json web/widgets.json "$out/"; fi +echo "built $out ($(wc -c < "$out/launcher.js") bytes of JS)" diff --git a/tests/e2e.cjs b/tests/e2e.cjs new file mode 100644 index 0000000..71f1361 --- /dev/null +++ b/tests/e2e.cjs @@ -0,0 +1,217 @@ +// Browser test of the launcher page built from MoonBit (dist/web, see scripts/build-web.sh), +// against the demo apps.json and widgets.json: the same flows legacy/tests/e2e.cjs drove. +// scripts/build-web.sh --demo && node tests/e2e.cjs +// Serves dist/web itself unless BASE points at a running copy. PLAYWRIGHT names the +// playwright module to load when it is not installed next to the repo; SHOTS=dir saves screenshots. +const assert = require("assert"); +const fs = require("fs"); +const http = require("http"); +const path = require("path"); +const { chromium } = require(process.env.PLAYWRIGHT || "playwright"); + +const serve = () => new Promise((resolve) => { + const root = path.join(__dirname, "..", "dist", "web"); + const types = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" }; + const srv = http.createServer((req, res) => { + const f = path.join(root, req.url.split("?")[0] === "/" ? "index.html" : req.url.split("?")[0]); + fs.readFile(f, (err, data) => { + if (err) { res.writeHead(404); res.end(); return; } + res.writeHead(200, { "content-type": types[path.extname(f)] || "application/octet-stream" }); + res.end(data); + }); + }).listen(0, () => resolve([srv, `http://localhost:${srv.address().port}`])); +}); + +(async () => { + const [srv, served] = process.env.BASE ? [null, process.env.BASE] : await serve(); + const BASE = served; + const shot = async (p, name) => { if (process.env.SHOTS) await p.screenshot({ path: path.join(process.env.SHOTS, name + ".png") }); }; + const b = await chromium.launch(); + const p = await b.newPage({ viewport: { width: 390, height: 780 } }); + p.on("pageerror", (e) => { console.error("page error:", e.message); process.exitCode = 1; }); + + const settle = () => p.waitForTimeout(250); // renders land on the next frame, which can lag here + await p.emulateMedia({ reducedMotion: "reduce" }); // no sliding drawer under the pointer + await p.goto(BASE + "/"); + await p.evaluate(() => localStorage.clear()); + await p.reload(); + await p.waitForSelector(".hint"); + await shot(p, "00-blank-home"); + assert.ok(!(await p.$(".clock")), "home has no built-in clock"); + const longpress = async (sel, fy = 0.5) => { + const r = await p.locator(sel).first().boundingBox(); + await p.mouse.move(r.x + r.width / 2, r.y + r.height * fy); + await p.mouse.down(); await p.waitForTimeout(650); await p.mouse.up(); await settle(); + }; + // the home menu's update check goes to the shell and closes the menu + await longpress(".hint"); + await p.click(".sheet-item >> text=Check for updates"); await settle(); + assert.equal(await p.textContent("#toast"), "Check for updates"); + assert.ok(!(await p.$(".sheet")), "the menu closes"); + const homeApps = () => p.$$eval(".slots .name", (ns) => ns.map((n) => n.textContent)); + // long press on the blank home: add apps through the drawer's pick mode + await longpress(".hint"); + await p.click(".sheet-item >> text=Add apps"); await settle(); + for (const i of [4, 8, 12]) await p.click(`.apps .tile:nth-child(${i})`); + await settle(); + assert.equal(await p.$$eval(".apps .tile.on", (ts) => ts.length), 3); + await p.click(".drawer-head >> text=Done"); await settle(); + assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]); + await shot(p, "01-home-with-apps"); + // add a widget: long press on blank home, below the apps + await longpress(".home", 0.95); + await p.click(".sheet-item >> text=Add widget"); + await p.waitForSelector(".widget-list li"); + // search the picker by widget name and by the app it comes from + const widgetNames = () => p.$$eval(".widget-list .widget-name", (ns) => ns.map((n) => n.firstChild.textContent)); + await p.fill(".widget-search", "cal"); await settle(); + assert.deepEqual(await widgetNames(), ["Calendar"]); + await p.fill(".widget-search", "goo"); await settle(); + assert.deepEqual(await widgetNames(), ["Weather"]); + await p.fill(".widget-search", "zzz"); await settle(); + assert.equal(await p.textContent(".sheet .empty"), "No widgets match."); + await p.fill(".widget-search", ""); await settle(); + await p.click(".widget-list li:first-child"); await settle(); + assert.equal(await p.getAttribute(".widget-slot", "data-wid"), "100"); + await shot(p, "02-widget-placeholder"); + assert.equal(await p.textContent(".widget-label"), "Clock"); + // hold a home app and drag it: reorder + const drag = async (from, to) => { + const a = await p.locator(from).first().boundingBox(), z = await p.locator(to).first().boundingBox(); + await p.mouse.move(a.x + a.width / 2, a.y + a.height / 2); + await p.mouse.down(); await p.waitForTimeout(650); await settle(); + assert.ok(await p.$(".slots > .lifted"), "a long press lifts the slot"); + await p.mouse.move(z.x + z.width / 2, z.y + z.height / 2, { steps: 5 }); await settle(); + await p.mouse.up(); await settle(); + }; + await drag(".slots .tile:nth-child(2)", ".slots .tile:nth-child(1)"); + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]); + assert.ok(!(await p.$(".sheet")), "a drag doesn't open the menu"); + assert.ok(!(await p.$(".slots > .lifted"))); + await drag(".slots .tile:nth-child(1)", ".slots .tile:nth-child(3)"); + assert.deepEqual(await homeApps(), ["Chrome", "Phone", "Gmail"]); + // hold without moving: the menu + await longpress(".slots .tile:nth-child(3)"); + await p.click(".sheet-item >> text=Move earlier"); await settle(); + assert.deepEqual(await homeApps(), ["Chrome", "Gmail", "Phone"]); + await longpress(".slots .tile:nth-child(1)"); + await p.click(".sheet-item >> text=Move later"); await settle(); + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]); + // the grid runs down the screen; an app dropped in an empty cell there stays in it, + // and the rest stay packed + const rows = await p.$eval(".slots", (s) => getComputedStyle(s).gridTemplateRows.split(" ").length); + assert.ok(rows >= 5, `rows fill the screen: ${rows}`); + const tileAt = (n) => p.locator(`.slots .tile:has-text("${n}")`).boundingBox(); + const g0 = await tileAt("Gmail"), c0 = await tileAt("Chrome"), pitch = 64 + 8; + await p.mouse.move(g0.x + g0.width / 2, g0.y + g0.height / 2); + await p.mouse.down(); await p.waitForTimeout(650); await settle(); + await p.mouse.move(g0.x + g0.width / 2 + 10, g0.y + g0.height / 2 + 4 * pitch, { steps: 6 }); await settle(); + await p.mouse.up(); await settle(); + const g1 = await tileAt("Gmail"), c1 = await tileAt("Chrome"); + assert.ok(Math.abs(g1.y - g0.y - 4 * pitch) < 3, `left four rows down: ${g1.y - g0.y}`); + assert.equal(Math.round(c1.x), Math.round(g0.x), "Chrome moves up into the packed first cell"); + await p.reload(); await p.waitForSelector(".slots .tile"); + assert.ok(Math.abs((await tileAt("Gmail")).y - g1.y) < 3, "its cell is saved"); + // dragging it back over an app puts it back in the packed order + const c2 = await tileAt("Chrome"); + await p.mouse.move(g1.x + g1.width / 2, g1.y + g1.height / 2); + await p.mouse.down(); await p.waitForTimeout(650); await settle(); + await p.mouse.move(c2.x + c2.width / 2, c2.y + c2.height / 2, { steps: 6 }); await settle(); + await p.mouse.up(); await settle(); + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone"]); + assert.ok(Math.abs((await tileAt("Gmail")).y - c0.y) < 3, "back in the first row"); + await p.mouse.click(5, 300); await settle(); // a tap on empty home ends the drag gesture + // swipe down opens the drawer (and takes the widget off screen), search, long press adds + const swipe = (y0, y1) => p.evaluate(([y0, y1]) => { + const at = (y) => new Touch({ identifier: 1, target: document.body, clientX: 200, clientY: y }); + document.body.dispatchEvent(new TouchEvent("touchstart", { bubbles: true, touches: [at(y0)], changedTouches: [at(y0)] })); + document.body.dispatchEvent(new TouchEvent("touchend", { bubbles: true, touches: [], changedTouches: [at(y1)] })); + }, [y0, y1]); + await swipe(200, 500); + await p.waitForSelector(".drawer", { timeout: 2000 }); + await shot(p, "03-drawer"); + assert.equal(await p.$$eval("[data-wid]", (ws) => ws.length), 0); + assert.ok(await p.$eval(".drawer input", (i) => i === document.activeElement), "opening the drawer focuses its search"); + await p.fill(".drawer input", "ma"); await settle(); + assert.deepEqual(await p.$$eval(".apps .name", (ns) => ns.map((n) => n.textContent)), ["Gmail", "Maps"]); + await p.press(".drawer input", "Enter"); await settle(); + assert.equal(await p.textContent("#toast"), "Open com.example.gmail/.MainActivity"); + assert.ok(!(await p.$(".drawer")), "launching closes the drawer"); + await swipe(200, 500); + await p.waitForSelector(".drawer .tile", { timeout: 2000 }); + await longpress(".apps .tile:first-child"); + assert.deepEqual(await p.$$eval(".sheet-item", (bs) => bs.map((b) => b.textContent)), ["Add to home", "App info", "Uninstall"]); + await shot(p, "04-drawer-app-menu"); + await p.click(".sheet-item:has-text('Uninstall')"); await settle(); + assert.equal(await p.textContent("#toast"), "Uninstall com.example.calculator/.MainActivity"); + assert.ok(!(await p.$(".sheet")) && (await p.$(".drawer")), "uninstalling closes the menu, not the drawer"); + await p.fill(".drawer input", "phone"); await settle(); + await longpress(".apps .tile:first-child"); + assert.ok(!(await p.$(".sheet-item:has-text('Uninstall')")), "system apps can't be uninstalled"); + await p.click(".sheet-overlay", { position: { x: 10, y: 10 } }); await p.fill(".drawer input", ""); await settle(); + await longpress(".apps .tile:first-child"); + await p.click(".sheet-item:has-text('Add to home')"); await settle(); + assert.equal(await p.textContent(".notice"), "Added to home"); + await swipe(600, 200); + await p.waitForSelector(".drawer", { state: "detached", timeout: 2000 }); // swipe up closes it + assert.deepEqual(await homeApps(), ["Gmail", "Chrome", "Phone", "Calculator"]); + // persisted; tap launches; remove + await p.reload(); await p.waitForSelector(".slots .tile"); + assert.equal(await p.$$eval(".slots > li", (ls) => ls.length), 5); + await p.click(".slots .tile:first-child"); await settle(); + assert.equal(await p.textContent("#toast"), "Open com.example.gmail/.MainActivity"); + // hold a widget without moving: resize handles; drag them to snap it to the grid + await longpress(".widget-slot"); + assert.ok(!(await p.$(".sheet")), "a widget gets handles, not the menu"); + assert.ok(await p.$(".widget-slot.resizing .resize-handle[data-edge=rb]")); + await shot(p, "05-resize-handles"); + const size = () => p.$eval(".widget-slot", (w) => [Math.round(w.getBoundingClientRect().width), Math.round(w.getBoundingClientRect().height)]); + const [w0] = await size(); + const tile = await p.locator(".slots .tile").first().boundingBox(); + const hd = await p.locator(".resize-handle[data-edge=rb]").boundingBox(); + await p.mouse.move(hd.x + hd.width / 2, hd.y + hd.height / 2); + await p.mouse.down(); + const ws = await p.locator(".widget-slot").boundingBox(); + await p.mouse.move(ws.x + tile.width * 2.1, ws.y + 140, { steps: 8 }); await settle(); + await p.mouse.up(); await settle(); + const [w1, h1] = await size(); + assert.ok(w1 < w0 && Math.abs(w1 - (2 * tile.width + 8)) < 3, `two columns wide: ${w1} (tile ${tile.width})`); + assert.equal(h1, 2 * 64 + 8, "snapped to two whole rows of tiles"); + assert.ok(await p.$(".widget-slot.resizing"), "letting go of a handle keeps the handles"); + await p.click(".resize-bar >> text=Done"); await settle(); + assert.ok(!(await p.$(".resize-handle"))); + await p.reload(); await p.waitForSelector(".widget-slot"); + assert.deepEqual(await size(), [w1, h1], "the size is saved"); + // while it shows handles, dragging the widget itself moves it, without another long press + await longpress(".widget-slot"); + const atStart = () => p.$eval(".widget-slot", (w) => { + const r = w.getBoundingClientRect(), s = w.parentElement.getBoundingClientRect(); + return Math.abs(r.left - s.left) < 2 && Math.abs(r.top - s.top) < 2; + }); + assert.ok(!(await atStart())); + const wb = await p.locator(".widget-slot").boundingBox(), first = await p.locator(".slots > li").first().boundingBox(); + await p.mouse.move(wb.x + wb.width / 2, wb.y + wb.height / 2); + await p.mouse.down(); await settle(); + assert.ok(await p.$(".widget-slot.lifted"), "pressing a widget with handles picks it up"); + await p.mouse.move(first.x + first.width / 2, first.y + first.height / 2, { steps: 8 }); await settle(); + await p.mouse.up(); await settle(); + assert.ok(await atStart(), "dragged onto the top row, first cell"); + // the apps flow into the cells beside it: a 2x2 widget in 5 columns leaves room for all four + const beside = await p.$eval(".widget-slot", (w) => { + const r = w.getBoundingClientRect(); + return [...document.querySelectorAll(".slots .tile")].filter((t) => { + const b = t.getBoundingClientRect(); return b.top >= r.top - 1 && b.bottom <= r.bottom + 1; + }).length; + }); + assert.equal(beside, 4, "apps fill the cells beside the widget"); + assert.ok(await p.$(".widget-slot.resizing"), "it keeps its handles after the move"); + assert.ok(!(await p.$(".sheet"))); + await p.click(".resize-bar >> text=Remove"); await settle(); + assert.ok(!(await p.$(".widget-slot"))); + await p.evaluate(() => { window.launcher.reload(); }); await settle(); + assert.equal(await p.$$eval(".slots > li", (ls) => ls.length), 4); + console.log("launcher ok"); + + await b.close(); + if (srv) srv.close(); +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/web/ffi.mbt b/web/ffi.mbt new file mode 100644 index 0000000..649fe1a --- /dev/null +++ b/web/ffi.mbt @@ -0,0 +1,361 @@ +///| +/// The few places MoonBit touches the browser: one-line JavaScript bodies for DOM +/// calls and the host bridge. Everything that decides anything is in the pure packages. + +///| +#external +type Dom + +///| +#external +type Ev + +// ---- DOM ---------------------------------------------------------------------- + +///| +extern "js" fn dom_create(tag : String) -> Dom = + #|(t) => document.createElement(t) + +///| +extern "js" fn dom_text(s : String) -> Dom = + #|(s) => document.createTextNode(s) + +///| +extern "js" fn dom_set_text(d : Dom, s : String) -> Unit = + #|(d, s) => { d.data = s } + +///| +extern "js" fn dom_attr(d : Dom, k : String, v : String) -> Unit = + #|(d, k, v) => d.setAttribute(k, v) + +///| +extern "js" fn dom_rm_attr(d : Dom, k : String) -> Unit = + #|(d, k) => d.removeAttribute(k) + +///| +extern "js" fn dom_prop(d : Dom, k : String, v : String) -> Unit = + #|(d, k, v) => { if (d[k] !== v) d[k] = v } + +///| +extern "js" fn dom_class(d : Dom, v : String) -> Unit = + #|(d, v) => { d.className = v } + +///| +/// Put `d` into `parent` right before `before` (or last when `before` is not a node), +/// unless it is already there. +extern "js" fn dom_place(parent : Dom, d : Dom, before : Dom, has_before : Bool) -> Unit = + #|(p, d, b, has) => { const next = has ? b : null; if (d.parentNode !== p || d.nextSibling !== next) p.insertBefore(d, next); } + +///| +extern "js" fn dom_remove(d : Dom) -> Unit = + #|(d) => d.remove() + +///| +extern "js" fn dom_root() -> Dom = + #|() => document.getElementById("app") + +// ---- events --------------------------------------------------------------------- + +///| +extern "js" fn listen( + target : String, + ty : String, + passive : Bool, + f : (Ev) -> Unit, +) -> Unit = + #|(target, ty, passive, f) => (target === "window" ? window : document).addEventListener(ty, f, { passive, capture: true }) + +///| +extern "js" fn ev_x(e : Ev) -> Double = + #|(e) => e.clientX ?? 0 + +///| +extern "js" fn ev_y(e : Ev) -> Double = + #|(e) => e.clientY ?? 0 + +///| +extern "js" fn ev_key(e : Ev) -> String = + #|(e) => e.key ?? "" + +///| +extern "js" fn ev_composing(e : Ev) -> Bool = + #|(e) => !!e.isComposing + +///| +extern "js" fn ev_primary(e : Ev) -> Bool = + #|(e) => e.isPrimary !== false && (e.button ?? 0) === 0 + +///| +extern "js" fn ev_value(e : Ev) -> String = + #|(e) => e.target && e.target.value != null ? String(e.target.value) : "" + +///| +extern "js" fn ev_prevent(e : Ev) -> Unit = + #|(e) => { if (e.cancelable) e.preventDefault() } + +///| +extern "js" fn ev_touch_x(e : Ev) -> Double = + #|(e) => (e.changedTouches && e.changedTouches[0] ? e.changedTouches[0].clientX : 0) + +///| +extern "js" fn ev_touch_y(e : Ev) -> Double = + #|(e) => (e.changedTouches && e.changedTouches[0] ? e.changedTouches[0].clientY : 0) + +///| +extern "js" fn ev_touches(e : Ev) -> Int = + #|(e) => (e.touches ? e.touches.length : 0) + +///| +/// The handler numbers (`data-n`) from the event's target up, as "3,1,0". +extern "js" fn ev_chain(e : Ev) -> String = + #|(e) => { const out = []; for (let n = e.target; n && n.getAttribute; n = n.parentNode) { const v = n.getAttribute("data-n"); if (v !== null) out.push(v); } return out.join(","); } + +///| +extern "js" fn set_timeout(ms : Int, f : () -> Unit) -> Unit = + #|(ms, f) => { setTimeout(f, ms) } + +///| +extern "js" fn request_frame(f : () -> Unit) -> Unit = + #|(f) => { requestAnimationFrame(() => f()) } + +///| +extern "js" fn now_ms() -> Double = + #|() => Date.now() + +// ---- storage and network ---------------------------------------------------------- + +///| +extern "js" fn storage_get(k : String) -> String = + #|(k) => { try { return localStorage.getItem(k) ?? "" } catch { return "" } } + +///| +extern "js" fn storage_has(k : String) -> Bool = + #|(k) => { try { return localStorage.getItem(k) !== null } catch { return false } } + +///| +extern "js" fn storage_set(k : String, v : String) -> Unit = + #|(k, v) => { try { localStorage.setItem(k, v) } catch {} } + +///| +/// The old WebView build's `ultra.home.*` keys as a JSON object. +extern "js" fn storage_legacy() -> String = + #|() => { const o = {}; try { for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k.startsWith("ultra.home.")) o[k] = localStorage.getItem(k); } } catch {} return JSON.stringify(o); } + +///| +extern "js" fn fetch_text(url : String, f : (Bool, String) -> Unit) -> Unit = + #|(url, f) => { fetch(url, { cache: "no-store" }).then((r) => r.ok ? r.text().then((t) => f(true, t)) : f(false, "HTTP " + r.status)).catch((e) => f(false, String(e))) } + +// ---- page measurements (after each render) ------------------------------------------ + +///| +/// Measure the viewport and the home grid (into `window.__m`); false without a grid. +extern "js" fn measure() -> Bool = + #|() => { const s = document.querySelector(".slots"), h = document.querySelector(".home"); if (!s || !h) return false; const r = s.getBoundingClientRect(); window.__m = [innerWidth, innerHeight, r.left, r.top, r.width, parseFloat(getComputedStyle(h).paddingBottom) || 0]; return true; } + +///| +/// Measurement i: viewport width, height, grid left, top, width, the home's bottom padding. +extern "js" fn measured(i : Int) -> Double = + #|(i) => window.__m[i] + +///| +/// The live widget slots, as the shell wants them: [[id, x, y, w, h, editing]...]. +extern "js" fn widget_slots() -> String = + #|() => JSON.stringify([...document.querySelectorAll(".widget-slot[data-wid]")].map((s) => { const r = s.getBoundingClientRect(); return [+s.dataset.wid, Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height), s.classList.contains("resizing") ? 1 : 0]; })) + +///| +extern "js" fn resize_handles() -> String = + #|() => JSON.stringify([...document.querySelectorAll(".resize-handle")].map((h) => { const r = h.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)]; })) + +///| +/// The drawer covers the page down to this y (px); -1 once it covers the screen, 0 when +/// there is no drawer. `last` is the previous bottom edge, so the answer can run ahead of it. +extern "js" fn drawer_cover(last : Double) -> Double = + #|(last) => { const d = document.querySelector(".drawer"); if (!d) return 0; const b = d.getBoundingClientRect().bottom; if (b >= innerHeight - 1) return -1; return Math.min(innerHeight - 1, Math.max(0, Math.ceil(b + 2 * Math.max(0, b - last)))); } + +///| +extern "js" fn drawer_bottom() -> Double = + #|() => { const d = document.querySelector(".drawer"); return d ? d.getBoundingClientRect().bottom : 0 } + +///| +/// A drawer or sheet over the home screen's widgets (the shell has them step aside). +extern "js" fn has_drawer() -> Bool = + #|() => !!document.querySelector(".drawer") && !document.querySelector(".sheet-overlay") + +///| +extern "js" fn focus_search() -> Unit = + #|() => { const i = document.querySelector(".drawer:not(.picking) .drawer-head input"); if (i) i.focus({ preventScroll: true }) } + +///| +extern "js" fn blur_active() -> Unit = + #|() => { document.activeElement && document.activeElement.blur && document.activeElement.blur() } + +///| +extern "js" fn scroll_top() -> Unit = + #|() => window.scrollTo({ top: 0, behavior: "smooth" }) + +///| +extern "js" fn home_at_top() -> Bool = + #|() => window.scrollY <= 0 + +///| +/// The drawer's list is at its end (or does not scroll); false without a drawer. +extern "js" fn list_at_end() -> Bool = + #|() => { const l = document.querySelector(".drawer .apps"); return !!l && l.scrollTop + l.clientHeight >= l.scrollHeight - 2 } + +///| +/// The sheet is covering the page (a swipe must not act under it). +extern "js" fn toast(s : String) -> Unit = + #|(s) => { const t = document.getElementById("toast"); if (!t) return; t.textContent = s; t.classList.add("show"); clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("show"), 1600); } + +// ---- icons --------------------------------------------------------------------------- + +///| +/// Snapshot the page's icon images; returns how many. +extern "js" fn icons_scan() -> Int = + #|() => { window.__imgs = [...document.querySelectorAll("img.icon[data-icon]")]; return window.__imgs.length; } + +///| +extern "js" fn icon_key(i : Int) -> String = + #|(i) => window.__imgs[i].dataset.icon + +///| +/// Whether image i already shows the icon for its key. +extern "js" fn icon_done(i : Int) -> Bool = + #|(i) => window.__imgs[i].__icon === window.__imgs[i].dataset.icon + +///| +extern "js" fn icon_set(i : Int, src : String) -> Unit = + #|(i, src) => { const img = window.__imgs[i]; img.__icon = img.dataset.icon; if (src) { img.src = src; img.classList.remove("missing"); } else img.classList.add("missing"); } + +///| +/// Forget what images show, so they are filled again. +extern "js" fn icons_reset() -> Unit = + #|() => { for (const img of document.querySelectorAll("img.icon")) img.__icon = undefined; } + +// ---- the host (Android's window.Android, or stand-ins in a desktop browser) ------------- + +///| +extern "js" fn is_android() -> Bool = + #|() => !!window.Android + +///| +extern "js" fn h_launch(c : String) -> Unit = + #|(c) => window.Android.launch(c) + +///| +extern "js" fn h_app_info(c : String) -> Unit = + #|(c) => window.Android.appInfo(c) + +///| +extern "js" fn h_uninstall(c : String) -> Unit = + #|(c) => window.Android.uninstall(c) + +///| +extern "js" fn h_add_widget(p : String) -> Unit = + #|(p) => window.Android.addWidget(p) + +///| +extern "js" fn h_remove_widget(id : Int) -> Unit = + #|(id) => window.Android.removeWidget(id) + +///| +extern "js" fn h_place_widgets(json : String) -> Unit = + #|(j) => window.Android.placeWidgets(j) + +///| +extern "js" fn h_cover_widgets(y : Int) -> Unit = + #|(y) => window.Android.coverWidgets(y) + +///| +extern "js" fn h_exclude_gestures(json : String) -> Unit = + #|(j) => window.Android.excludeGestures && window.Android.excludeGestures(j) + +///| +extern "js" fn h_widget_limits(id : Int) -> String = + #|(id) => window.Android.widgetLimits(id) + +///| +extern "js" fn h_load_icons(json : String) -> Unit = + #|(j) => window.Android.loadIcons(j) + +///| +extern "js" fn h_has_load_icons() -> Bool = + #|() => !!(window.Android && window.Android.loadIcons) + +///| +extern "js" fn h_haptic() -> Unit = + #|() => { if (window.Android) window.Android.haptic(); else navigator.vibrate && navigator.vibrate(10) } + +///| +extern "js" fn h_show_keyboard() -> Unit = + #|() => window.Android && window.Android.showKeyboard() + +///| +extern "js" fn h_hide_keyboard() -> Unit = + #|() => window.Android && window.Android.hideKeyboard() + +///| +extern "js" fn h_open_settings() -> Unit = + #|() => window.Android.openSettings() + +///| +extern "js" fn h_pick_wallpaper() -> Unit = + #|() => window.Android.pickWallpaper() + +///| +extern "js" fn h_open_recents() -> Unit = + #|() => window.Android.openRecents() + +///| +extern "js" fn h_http_get(url : String, tag : Int) -> Unit = + #|(url, tag) => window.Android.httpGet(url, tag) + +///| +extern "js" fn h_install_apk(url : String, version : Int) -> Unit = + #|(url, v) => window.Android.installApk(url, v) + +///| +extern "js" fn h_installed_version() -> Int = + #|() => window.Android.installedVersion() + +// ---- what the shell calls on the page ----------------------------------------------- + +///| +extern "js" fn expose_init() -> Unit = + #|() => { window.launcher = window.launcher || {}; } + +///| +extern "js" fn expose0(name : String, f : () -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +extern "js" fn expose1(name : String, f : (Int) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +extern "js" fn expose_b(name : String, f : (Bool) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +extern "js" fn expose_dd(name : String, f : (Double, Double) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +/// `f(tag, ok, text)`: a finished `httpGet`. +extern "js" fn expose_result(name : String, f : (Int, Bool, String) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = f } + +///| +/// `f(json)`: a batch of icons `{key: dataUri}`. +extern "js" fn expose_json(name : String, f : (String) -> Unit) -> Unit = + #|(n, f) => { window.launcher[n] = (batch) => f(JSON.stringify(batch)) } + +///| +/// Run `f` for each `key\nsrc` pair of a JSON object (flattened, so no arrays cross). +extern "js" fn json_entries(json : String, f : (String, String) -> Unit) -> Unit = + #|(j, f) => { const o = JSON.parse(j); for (const k in o) f(k, o[k] ?? "") } + +///| +/// Mark the page as running outside the shell (a desktop browser): the stylesheet gives it a backdrop. +extern "js" fn mark_demo() -> Unit = + #|() => document.documentElement.classList.add("demo") diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..2960795 --- /dev/null +++ b/web/index.html @@ -0,0 +1,18 @@ + + + + + + ultra · Launcher + + + + +
+
+ + + diff --git a/web/main.mbt b/web/main.mbt new file mode 100644 index 0000000..5198bc1 --- /dev/null +++ b/web/main.mbt @@ -0,0 +1,465 @@ +///| +/// The page runtime: renders `@app.view` into the DOM, turns pointer, touch and key +/// events into `@app` input, runs the effects it returns against the host (Android's +/// `window.Android`, or stand-ins that show toasts in a desktop browser), and exposes +/// `window.launcher.*` for the Android shell to call. + +///| +let model : @app.Model = @app.Model::new() + +///| +let state : Ref[PageState] = Ref::new(PageState::new()) + +///| +priv struct PageState { + mut tree : Array[@vdom.Node[@app.Msg]] + mut table : Array[@vdom.Handlers[@app.Msg]] + mut rendered : Array[RNode] + mut render_pending : Bool + mut focus_pending : Bool + mut placed : String + mut excluded : String + mut cover_y : Int + mut cover_last : Double + mut cover_loop : Bool + mut measured : String + mut touch : (Double, Double, Double)? + mut demo_widget : Int + mut http_tag : Int + http : Map[Int, (Bool, String) -> Unit] + icon_src : Map[String, String] + icon_asked : Map[String, Bool] + icon_tries : Map[String, Int] +} + +///| +fn PageState::new() -> PageState { + { + tree: [], + table: [], + rendered: [], + render_pending: false, + focus_pending: false, + placed: "", + excluded: "[]", + cover_y: 0, + cover_last: 0.0, + cover_loop: false, + measured: "", + touch: None, + demo_widget: 100, + http_tag: 0, + http: {}, + icon_src: {}, + icon_asked: {}, + icon_tries: {}, + } +} + +///| +fn dispatch(msg : @app.Msg) -> Unit { + run(@app.update(model, msg)) +} + +///| +fn feed(inp : @gesture.Input) -> Unit { + run(@app.input(model, state.val.table, inp)) +} + +///| +fn run(fx : Array[@app.Effect]) -> Unit { + for e in fx { + exec(e) + } + schedule_render() +} + +///| +fn schedule_render() -> Unit { + if state.val.render_pending { + return + } + state.val.render_pending = true + request_frame(render) +} + +///| +fn http_get(url : String, f : (Bool, String) -> Unit) -> Unit { + if is_android() { + let tag = state.val.http_tag + 1 + state.val.http_tag = tag + state.val.http[tag] = f + h_http_get(url, tag) + } else { + fetch_text(url, f) + } +} + +///| +fn exec(e : @app.Effect) -> Unit { + let android = is_android() + match e { + Launch(c) => if android { h_launch(c) } else { toast("Open " + c) } + AppInfo(c) => if android { h_app_info(c) } else { toast("App info for " + c) } + Uninstall(c) => if android { h_uninstall(c) } else { toast("Uninstall " + c) } + AddWidget(p) => + if android { + h_add_widget(p) + } else { + let id = state.val.demo_widget + state.val.demo_widget = id + 1 + set_timeout(0, fn() { dispatch(WidgetAdded(id)) }) + } + RemoveWidget(id) => if android { h_remove_widget(id) } + OpenSettings => if android { h_open_settings() } else { toast("Open system settings") } + PickWallpaper => if android { h_pick_wallpaper() } else { toast("Pick a wallpaper") } + OpenRecents => if android { h_open_recents() } else { toast("Show open windows") } + Haptic => h_haptic() + LoadApps => + fetch_text("apps.json", fn(ok, text) { + dispatch(AppsLoaded(if ok { Some(text) } else { None })) + }) + LoadWidgets => + fetch_text("widgets.json", fn(ok, text) { + dispatch(WidgetsLoaded(if ok { Some(text) } else { None })) + }) + QueryLimits(id) => { + let json = if android { + h_widget_limits(id) + } else { + "{\"minW\":120,\"minH\":80,\"maxW\":0,\"maxH\":0,\"h\":true,\"v\":true}" + } + dispatch(LimitsKnown(id, Some(json))) + } + SaveHome(json) => storage_set("launcher.home", json) + SaveLastCheck(t) => storage_set("launcher.update.lastCheck", t.to_string()) + SaveDeclined(n) => storage_set("launcher.update.declined", n.to_string()) + Delay(ms, msg) => set_timeout(ms, fn() { dispatch(msg) }) + HoldTimer(ms, token) => set_timeout(ms, fn() { feed(Hold(token)) }) + FetchRelease(url) => + if android { + http_get(url, fn(ok, text) { + dispatch(ReleaseFetched(if ok { Some(text) } else { None })) + }) + } else { + toast("Check for updates") + set_timeout(0, fn() { dispatch(ReleaseFetched(None)) }) + } + FetchVersion(url) => + http_get(url, fn(ok, text) { + dispatch(VersionFetched(if ok { Some(text) } else { None })) + }) + InstallApk(url, n) => + if android { h_install_apk(url, n) } else { toast("Install update \{n}") } + FocusSearch => state.val.focus_pending = true + HideKeyboard => { + blur_active() + h_hide_keyboard() + } + ScrollTop => scroll_top() + } +} + +// ---- rendering --------------------------------------------------------------------- + +///| +fn render() -> Unit { + let st = state.val + st.render_pending = false + st.tree = @app.view(model) + st.table = @app.handler_table(st.tree) + st.rendered = patch_root(dom_root(), st.rendered, st.tree) + after_render() +} + +///| +fn after_render() -> Unit { + let st = state.val + fill_icons() + if measure() { + let key = "\{measured(0)},\{measured(1)},\{measured(2)},\{measured(3)},\{measured(4)},\{measured(5)}" + if key != st.measured { + st.measured = key + dispatch( + Measured( + vw=measured(0).to_int(), + vh=measured(1).to_int(), + grid_left=measured(2), + grid_top=measured(3), + grid_w=measured(4), + bottom_pad=measured(5), + ), + ) + } + } + if is_android() { + place() + cover() + } + if st.focus_pending { + st.focus_pending = false + focus_search() + h_show_keyboard() + } +} + +///| +/// Tell the shell where the live widget slots are, and keep its edge swipes off the +/// resize handles. +fn place() -> Unit { + let st = state.val + let json = widget_slots() + // The drawer unmarks the slots, but the home under it doesn't move, so the widgets + // stay where they were and `cover` hides them as the drawer slides over them. + if json != st.placed && !has_drawer() { + st.placed = json + h_place_widgets(json) + } + let handles = resize_handles() + if handles != st.excluded { + st.excluded = handles + h_exclude_gestures(handles) + } +} + +///| +/// Native widgets sit above the page, so the drawer can't cover them by itself. While +/// it slides down the shell hides them above its bottom edge each frame, a little ahead +/// of it (by its speed), since the shell trails a frame. +fn cover() -> Unit { + let st = state.val + let y = drawer_cover(st.cover_last).to_int() + st.cover_last = drawer_bottom() + if y != st.cover_y { + st.cover_y = y + h_cover_widgets(y) + } + if y != 0 && y != -1 && !st.cover_loop { + st.cover_loop = true + request_frame(fn() { + state.val.cover_loop = false + cover() + }) + } +} + +// ---- icons ------------------------------------------------------------------------- + +///| +/// Each `` gets its src from here. On a phone the shell +/// draws icons on its own thread and hands them back as data: URIs in batches, so the +/// WebView never loads icons through request interception; in a desktop browser the key +/// already is a URL. +fn fill_icons() -> Unit { + let st = state.val + let n = icons_scan() + let want : Array[Json] = [] + let loader = h_has_load_icons() + for i in 0.. 0 { + h_load_icons(Json::array(want).stringify()) + } +} + +///| +/// A batch from the shell: `{key: dataUri}`. A key it couldn't draw ("") is asked for +/// again, up to 3 times, with backoff; until then, and after, it shows as a blank disc. +fn got_icons(json : String) -> Unit { + let st = state.val + let mut retry = 0 + json_entries(json, fn(k, src) { + st.icon_src[k] = src + st.icon_asked.remove(k) + let tries = st.icon_tries.get(k).unwrap_or(0) + if src == "" && tries < 3 { + st.icon_tries[k] = tries + 1 + retry = tries + 1 + } + }) + fill_icons() + if retry > 0 { + set_timeout(800 * retry, fn() { + let keys : Array[String] = [] + for kv in st.icon_src { + if kv.1 == "" { + keys.push(kv.0) + } + } + for k in keys { + st.icon_src.remove(k) + } + icons_reset() + fill_icons() + }) + } +} + +// ---- input ------------------------------------------------------------------------- + +///| +fn parse_chain(s : String) -> Array[Int] { + if s == "" { + return [] + } + let out : Array[Int] = [] + for part in s.split(",") { + out.push( + try @string.parse_int(part) catch { + _ => -1 + }, + ) + } + out +} + +///| +fn is_dragging() -> Bool { + model.lifted >= 0 || model.resize is Some(_) +} + +///| +fn wire_events() -> Unit { + listen("document", "pointerdown", true, fn(e) { + if ev_primary(e) { + feed(Down(x=ev_x(e), y=ev_y(e), chain=parse_chain(ev_chain(e)))) + } + }) + listen("document", "pointermove", true, fn(e) { + feed(Move(x=ev_x(e), y=ev_y(e))) + }) + listen("document", "pointerup", true, fn(e) { feed(Up(x=ev_x(e), y=ev_y(e))) }) + listen("document", "pointercancel", true, fn(_) { feed(Cancel) }) + // keep the page from scrolling under a lifted slot or a handle being dragged + listen("document", "touchmove", false, fn(e) { if is_dragging() { ev_prevent(e) } }) + listen("document", "contextmenu", false, fn(e) { ev_prevent(e) }) + listen("document", "input", true, fn(e) { + run(@app.typed(model, state.val.table, parse_chain(ev_chain(e)), ev_value(e))) + }) + listen("document", "keydown", true, fn(e) { + if ev_composing(e) { + return + } + let k = ev_key(e) + if k == "Enter" { + run(@app.key(model, state.val.table, parse_chain(ev_chain(e)), Enter)) + } else if k == "Escape" { + run(@app.key(model, state.val.table, parse_chain(ev_chain(e)), Escape)) + } + }) + // Swipes: down on the home opens the drawer, up closes it once its list is at the end. + listen("document", "touchstart", true, fn(e) { + state.val.touch = if ev_touches(e) == 1 { + Some((ev_touch_x(e), ev_touch_y(e), now_ms())) + } else { + None + } + }) + listen("document", "touchend", true, fn(e) { + match state.val.touch { + Some((x0, y0, t0)) => { + state.val.touch = None + dispatch( + Touch( + dx=ev_touch_x(e) - x0, + dy=ev_touch_y(e) - y0, + ms=(now_ms() - t0).to_int(), + home_top=home_at_top(), + list_end=list_at_end(), + ), + ) + } + None => () + } + }) + listen("window", "resize", true, fn(_) { schedule_render() }) + listen("window", "scroll", true, fn(_) { + if is_android() { + request_frame(place) + } + }) +} + +///| +/// What the Android shell calls: `window.launcher.*`. +fn expose_api() -> Unit { + expose_init() + expose0("reload", fn() { + state.val.icon_src.clear() + state.val.icon_asked.clear() + state.val.icon_tries.clear() + icons_reset() + dispatch(Reload) + }) + expose0("home", fn() { dispatch(GoHome) }) + expose0("back", fn() { dispatch(Back) }) + expose1("widgetAdded", fn(id) { dispatch(WidgetAdded(id)) }) + expose1("widgetMenu", fn(id) { dispatch(WidgetMenu(id)) }) + expose1("widgetGrab", fn(id) { dispatch(WidgetGrab(id)) }) + expose_dd("widgetDrag", fn(x, y) { dispatch(NativeDrag(x, y)) }) + expose_b("widgetDrop", fn(moved) { dispatch(NativeDrop(moved)) }) + expose0("place", fn() { + state.val.placed = "" + place() + }) + expose1("updateDeclined", fn(n) { dispatch(UpdateDeclined(n)) }) + expose_json("icons", got_icons) + expose_result("httpResult", fn(tag, ok, text) { + if state.val.http.get(tag) is Some(f) { + state.val.http.remove(tag) + f(ok, text) + } + }) +} + +///| +fn num(key : String) -> Int64 { + let s = storage_get(key) + if s == "" { + 0L + } else { + try @string.parse_int64(s) catch { + _ => 0L + } + } +} + +///| +fn main { + if !is_android() { + mark_demo() + } + expose_api() + wire_events() + let saved = if storage_has("launcher.home") { Some(storage_get("launcher.home")) } else { None } + let legacy = if saved is None { Some(storage_legacy()) } else { None } + dispatch(Restore(saved~, legacy~)) + if is_android() { + let declined = if storage_has("launcher.update.declined") { + num("launcher.update.declined").to_int() + } else { + -1 + } + dispatch( + Started( + now=now_ms().to_int64(), + last_check=num("launcher.update.lastCheck"), + declined~, + installed=h_installed_version(), + ), + ) + } + render() +} diff --git a/web/moon.pkg b/web/moon.pkg new file mode 100644 index 0000000..ed7bad3 --- /dev/null +++ b/web/moon.pkg @@ -0,0 +1,13 @@ +import { + "experiments/launcher/app", + "experiments/launcher/vdom", + "experiments/launcher/gesture", + "moonbitlang/core/json", + "moonbitlang/core/string", +} + +options( + is_main: true, +) + +supported_targets = "js" diff --git a/web/patch.mbt b/web/patch.mbt new file mode 100644 index 0000000..5153f3b --- /dev/null +++ b/web/patch.mbt @@ -0,0 +1,188 @@ +///| +/// Turns `vdom` trees into DOM and patches the DOM to match the next tree: keyed +/// children are reused (and moved) so a reordered tile keeps its element, and the CSS +/// transitions on it. Elements with handlers get `data-n`, their number in document +/// order, which pointer events report back (see `@app.handler_table`). + +///| +priv struct RNode { + dom : Dom + is_text : Bool + tag : String + key : Int + mut text : String + mut n : Int + mut classes : String + mut attrs : Map[String, String] + mut props : Map[String, String] + mut style : String + mut children : Array[RNode] +} + +///| +fn new_rnode(n : @vdom.Node[@app.Msg]) -> RNode { + match n { + Text(s) => + { + dom: dom_text(s), + is_text: true, + tag: "", + key: 0, + text: s, + n: -1, + classes: "", + attrs: {}, + props: {}, + style: "", + children: [], + } + El(e) => + { + dom: dom_create(e.tag), + is_text: false, + tag: e.tag, + key: e.key, + text: "", + n: -1, + classes: "", + attrs: {}, + props: {}, + style: "", + children: [], + } + } +} + +///| +fn update_rnode(r : RNode, n : @vdom.Node[@app.Msg], counter : Ref[Int]) -> Unit { + match n { + Text(s) => + if s != r.text { + r.text = s + dom_set_text(r.dom, s) + } + El(e) => { + // numbered first: children come after their parent in document order + let id = if e.handlers.is_empty() { + -1 + } else { + let id = counter.val + counter.val = id + 1 + id + } + if id != r.n { + r.n = id + if id < 0 { + dom_rm_attr(r.dom, "data-n") + } else { + dom_attr(r.dom, "data-n", id.to_string()) + } + } + let classes = e.classes.filter(fn(c) { c != "" }).join(" ") + if classes != r.classes { + r.classes = classes + dom_class(r.dom, classes) + } + let attrs : Map[String, String] = {} + for kv in e.attrs { + attrs[kv.0] = kv.1 + } + for kv in attrs { + if r.attrs.get(kv.0) != Some(kv.1) { + dom_attr(r.dom, kv.0, kv.1) + } + } + for kv in r.attrs { + if !attrs.contains(kv.0) { + dom_rm_attr(r.dom, kv.0) + } + } + r.attrs = attrs + for kv in e.props { + dom_prop(r.dom, kv.0, kv.1) + } + if e.style != r.style { + r.style = e.style + if e.style == "" { + dom_rm_attr(r.dom, "style") + } else { + dom_attr(r.dom, "style", e.style) + } + } + r.children = patch_children(r.dom, r.children, e.children, counter) + } + } +} + +///| +fn compatible(r : RNode, n : @vdom.Node[@app.Msg]) -> Bool { + match n { + Text(_) => r.is_text + El(e) => !r.is_text && r.tag == e.tag && r.key == e.key + } +} + +///| +fn patch_children( + parent : Dom, + old : Array[RNode], + new : Array[@vdom.Node[@app.Msg]], + counter : Ref[Int], +) -> Array[RNode] { + let used : Array[Bool] = Array::make(old.length(), false) + let by_key : Map[Int, Int] = {} + for i in 0.. + if by_key.get(e.key) is Some(i) && !used[i] && compatible(old[i], n) { + found = i + } + _ => + for i in 0..= 0 { + used[found] = true + old[found] + } else { + new_rnode(n) + } + update_rnode(r, n, counter) + out.push(r) + } + for i in 0..= 0; j = j - 1 { + if j == out.length() - 1 { + dom_place(parent, out[j].dom, out[j].dom, false) + } else { + dom_place(parent, out[j].dom, out[j + 1].dom, true) + } + } + out +} + +///| +/// Patch the children of `root` to `tree`; returns the new state to pass next time. +fn patch_root( + root : Dom, + old : Array[RNode], + tree : Array[@vdom.Node[@app.Msg]], +) -> Array[RNode] { + patch_children(root, old, tree, Ref::new(0)) +} diff --git a/web/pkg.generated.mbti b/web/pkg.generated.mbti new file mode 100644 index 0000000..103a470 --- /dev/null +++ b/web/pkg.generated.mbti @@ -0,0 +1,15 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/launcher/web" + +// Values + +// Errors + +// Types and methods +type Dom + +type Ev + +// Type aliases + +// Traits diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..4a6c4e4 --- /dev/null +++ b/web/style.css @@ -0,0 +1,261 @@ +/* ultra launcher: shadcn-neutral tokens and the few components the views use (from legacy/web/ui.css), then the home screen layout. */ + +:root { + color-scheme: light dark; + --radius: .625rem; + --background: light-dark(oklch(1 0 0), oklch(.145 0 0)); + --foreground: light-dark(oklch(.145 0 0), oklch(.985 0 0)); + --card: light-dark(oklch(1 0 0), oklch(.205 0 0)); + --card-foreground: var(--foreground); + --popover: var(--card); + --popover-foreground: var(--foreground); + --primary: light-dark(oklch(.205 0 0), oklch(.922 0 0)); + --primary-foreground: light-dark(oklch(.985 0 0), oklch(.205 0 0)); + --secondary: light-dark(oklch(.97 0 0), oklch(.269 0 0)); + --secondary-foreground: light-dark(oklch(.205 0 0), oklch(.985 0 0)); + --muted: var(--secondary); + --muted-foreground: light-dark(oklch(.556 0 0), oklch(.708 0 0)); + --accent: var(--secondary); + --accent-foreground: var(--secondary-foreground); + --destructive: light-dark(oklch(.577 .245 27.325), oklch(.704 .191 22.216)); + --border: light-dark(oklch(.922 0 0), oklch(1 0 0 / 10%)); + --input: light-dark(oklch(.922 0 0), oklch(1 0 0 / 15%)); + --input-bg: light-dark(transparent, oklch(1 0 0 / 4.5%)); + --ring: light-dark(oklch(.708 0 0), oklch(.556 0 0)); + --shadow-xs: 0 1px 2px 0 rgb(0 0 0 / .05); + --shadow-sm: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1); + --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1); + --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} +.light { color-scheme: light; } +.dark { color-scheme: dark; } + +/* ---------------------------------------------------------------- base */ +*, ::before, ::after { box-sizing: border-box; } +body { + margin: 0; background: var(--background); color: var(--foreground); + font: 14px/1.5 var(--font-sans); -webkit-font-smoothing: antialiased; +} +.light, .dark { background: var(--background); color: var(--foreground); } +button, input { font: inherit; color: inherit; margin: 0; } +button { border: 0; background: none; padding: 0; } +:focus-visible { outline: none; } +.muted { color: var(--muted-foreground); } +.mono { font-family: var(--font-mono); } +.stack { display: grid; gap: 1rem; } +.row { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; } +.grow { flex: 1; } + +/* ---------------------------------------------------------------- button */ +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: .5rem; + height: 2.25rem; padding: .5rem 1rem; border-radius: calc(var(--radius) - 2px); + border: 1px solid transparent; cursor: pointer; user-select: none; + background: var(--primary); color: var(--primary-foreground); box-shadow: var(--shadow-xs); + transition: background-color .15s, color .15s, box-shadow .15s, opacity .15s; +} +.btn:hover { background: color-mix(in oklab, var(--primary) 90%, transparent); } +.btn:disabled { opacity: .5; pointer-events: none; } +.btn:focus-visible, .input:focus-visible, .checkbox:focus-visible, .switch:focus-visible, +.tab:focus-visible, .toggle:focus-visible { + border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent); +} +.btn.secondary { background: var(--secondary); color: var(--secondary-foreground); } +.btn.secondary:hover { background: color-mix(in oklab, var(--secondary) 80%, transparent); } +.btn.outline { + background: light-dark(var(--background), var(--input-bg)); color: var(--foreground); + border-color: light-dark(var(--border), var(--input)); +} +.btn.outline:hover, .btn.ghost:hover { background: var(--accent); color: var(--accent-foreground); } +.btn.ghost { background: transparent; color: var(--foreground); box-shadow: none; } +.btn.destructive { background: light-dark(var(--destructive), color-mix(in oklab, var(--destructive) 60%, transparent)); color: #fff; } +.btn.destructive:hover { background: color-mix(in oklab, var(--destructive) 90%, transparent); } +.btn.link { background: none; color: var(--primary); box-shadow: none; text-underline-offset: 4px; } +.btn.link:hover { text-decoration: underline; } +.btn.sm { height: 2rem; padding: 0 .75rem; gap: .375rem; } +.btn.lg { height: 2.5rem; padding: 0 1.5rem; } +.btn.icon { width: 2.25rem; padding: 0; } +.btn.icon.sm { width: 2rem; } +.input { + display: flex; width: 100%; min-width: 0; height: 2.25rem; padding: .25rem .75rem; + border: 1px solid var(--input); border-radius: calc(var(--radius) - 2px); + background: var(--input-bg); box-shadow: var(--shadow-xs); font-size: .875rem; + transition: box-shadow .15s, border-color .15s; +} +.input::placeholder { color: var(--muted-foreground); } +@keyframes ui-fade { from { opacity: 0; } } +.alert { + display: grid; gap: .125rem; width: 100%; padding: .75rem 1rem; font-size: .875rem; + border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); color: var(--card-foreground); +} +.alert-title { font-weight: 500; } +.alert-description { color: var(--muted-foreground); } +.alert.destructive { color: var(--destructive); } +.alert.destructive .alert-description { color: color-mix(in oklab, var(--destructive) 90%, transparent); } + +/* Home screen layout; the components come from ui.css. The page is transparent so the + system wallpaper shows through the WebView. MainActivity sets --inset-top and + --inset-bottom to the status and navigation bar (and keyboard) heights. */ +:root { + --top: var(--inset-top, env(safe-area-inset-top, 0px)); + --bottom: var(--inset-bottom, env(safe-area-inset-bottom, 0px)); + --shadow-text: 0 1px 4px rgb(0 0 0 / .6); +} +html, body { background: transparent; } +html.demo { background: linear-gradient(160deg, #1e293b, #4c1d95 55%, #0f172a) fixed; } +body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: transparent; + user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; + overscroll-behavior: none; } +#app { max-width: 560px; margin: 0 auto; } + +/* ---- home */ +.home { min-height: 100vh; box-sizing: border-box; + padding: calc(var(--top) + 1rem) 16px calc(var(--bottom) + 1.5rem); } + +.panel { display: flex; gap: .5rem; margin: 0 auto 1rem; padding: .4rem; max-width: 22rem; + border-radius: 1.25rem; background: rgb(255 255 255 / .12); border: 1px solid rgb(255 255 255 / .16); + backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); } +.panel-btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: .6rem; + min-height: 2.5rem; padding: .4rem 1rem; border: 0; border-radius: .9rem; + background: rgb(255 255 255 / .1); color: #fff; font: inherit; font-weight: 500; + cursor: pointer; text-shadow: 0 1px 4px rgb(0 0 0 / .35); } +.panel-btn:hover, .panel-btn:active { background: rgb(255 255 255 / .22); } +.windows-glyph { position: relative; width: 1.1rem; height: 1.1rem; } +.windows-glyph::before, .windows-glyph::after { content: ""; position: absolute; border: 2px solid currentColor; + border-radius: .25rem; box-sizing: border-box; } +.windows-glyph::before { inset: 0 .3rem .3rem 0; opacity: .6; } +.windows-glyph::after { inset: .3rem 0 0 .3rem; background: rgb(255 255 255 / .15); } +.slots, .apps { list-style: none; margin: 0; padding: 0; display: grid; gap: 1.25rem .5rem; + grid-template-columns: repeat(4, minmax(0, 1fr)); } +/* The home grid is placed explicitly by the model (app/view.mbt sets its columns, rows and + every slot's cell inline); the gaps and the 64px row height must match grid/grid.mbt. */ +.slots { gap: 8px; } +@media (min-width: 480px) { .apps { grid-template-columns: repeat(5, minmax(0, 1fr)); } } +.tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: .4rem; + padding: .35rem .15rem; border-radius: calc(var(--radius) + 4px); cursor: pointer; } +.tile:active { background: rgb(255 255 255 / .12); } +.icon { width: 3.25rem; height: 3.25rem; object-fit: contain; pointer-events: none; + filter: drop-shadow(0 2px 4px rgb(0 0 0 / .3)); } +.icon.missing { border-radius: 999px; background: rgb(255 255 255 / .18); object-position: -999px 0; } +.name { max-width: 100%; font-size: .75rem; line-height: 1.2; text-align: center; + text-shadow: var(--shadow-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.slots .tile { gap: .25rem; padding: .2rem .1rem; } +.slots .icon { width: 2.5rem; height: 2.5rem; } +.slots .name { font-size: .68rem; } + +/* A widget takes whole rows. On a phone the native widget view covers the slot; + the label only shows while the slot is not live (or in a desktop browser). */ +.widget-slot { display: grid; place-items: center; box-sizing: border-box; + border-radius: 1.25rem; background: rgb(255 255 255 / .1); + border: 1px dashed rgb(255 255 255 / .3); } +.widget-label { font-size: .875rem; opacity: .75; text-shadow: var(--shadow-text); + max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +/* The native view can be narrower than the slot, so the label would peek out at its sides. */ +.widget-slot[data-wid] .widget-label { visibility: hidden; } +/* A live widget sits bare on the wallpaper; the frame only comes back while it is picked + up or resized (or while its native view is away, e.g. another widget is being resized). */ +.widget-slot[data-wid]:not(.lifted):not(.resizing) { background: none; border-color: transparent; } + +/* A widget being resized: handles sit just outside its right and bottom edges, where the + native widget view doesn't cover them; the bottom one sits in the gap below the row. */ +.widget-slot { position: relative; } +.widget-slot.resizing { z-index: 2; outline: 2px solid rgb(255 255 255 / .85); + outline-offset: 3px; transition: none; } +.resize-handle { position: absolute; z-index: 2; touch-action: none; cursor: nwse-resize; } +.resize-handle::after { content: ""; position: absolute; border-radius: 999px; background: #fff; + box-shadow: 0 1px 6px rgb(0 0 0 / .45); } +.resize-handle[data-edge="r"] { top: 0; bottom: 0; right: -16px; width: 16px; cursor: ew-resize; } +.resize-handle[data-edge="r"]::after { top: 50%; left: 6px; width: 6px; height: 2.5rem; transform: translateY(-50%); } +.resize-handle[data-edge="b"] { left: 0; right: 0; bottom: -1rem; height: 1rem; cursor: ns-resize; } +.resize-handle[data-edge="b"]::after { left: 50%; top: 5px; width: 2.5rem; height: 6px; transform: translateX(-50%); } +.resize-handle[data-edge="rb"] { right: -16px; bottom: -1rem; width: 2.75rem; height: 1rem; } +.resize-handle[data-edge="rb"]::after { right: 4px; top: 1px; width: 14px; height: 14px; border-radius: 4px; } +.resize-bar { position: fixed; left: 50%; bottom: calc(var(--bottom) + 1rem); z-index: 15; transform: translateX(-50%); + display: flex; align-items: center; gap: .5rem; padding: .4rem .4rem .4rem 1rem; border-radius: 999px; + background: rgb(0 0 0 / .8); color: #fff; font-size: .875rem; white-space: nowrap; + animation: ui-fade .15s; } +.resize-bar { max-width: calc(100vw - 1rem); } +.resize-hint { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.resize-bar .btn { flex: none; } +.resize-bar .btn.ghost { color: #fff; } +.resize-bar .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; } + +/* A slot picked up by a long press, while it is dragged (index.html moves it). */ +.slots > li { transition: transform .15s ease-out; } +.slots > .lifted { z-index: 1; transform: scale(1.12); background: rgb(255 255 255 / .16); + box-shadow: 0 8px 24px rgb(0 0 0 / .35); } +.slots.dragging > li:not(.lifted) { opacity: .8; } +.slots.dragging .tile:active { background: none; } + +.hint, .empty { text-align: center; opacity: .85; text-shadow: var(--shadow-text); } +.hint { margin-top: 30vh; padding: 0 2rem; font-size: .9rem; line-height: 1.5; } + +/* The search pill under the panel: a tap opens the drawer. */ +.search-pill { display: flex; align-items: center; gap: .75rem; width: 100%; max-width: 22rem; height: 2.75rem; + margin: -.25rem auto 1rem; padding: 0 1.1rem; border-radius: 999px; cursor: pointer; + background: rgb(255 255 255 / .1); border: 1px solid rgb(255 255 255 / .15); + color: rgb(255 255 255 / .6); font-size: 1rem; text-align: left; } +.search-pill:active { background: rgb(255 255 255 / .18); } +.magnifier { position: relative; flex: none; width: 1rem; height: 1rem; } +.magnifier::before { content: ""; position: absolute; inset: 0 .3rem .3rem 0; border: 2px solid rgb(255 255 255 / .75); + border-radius: 999px; } +.magnifier::after { content: ""; position: absolute; right: 0; bottom: .05rem; width: .45rem; height: 2px; + background: rgb(255 255 255 / .75); border-radius: 1px; transform: rotate(45deg); } +button { cursor: pointer; } + +/* ---- drawer: slides down over the home screen */ +.drawer { position: fixed; inset: 0; z-index: 10; display: flex; flex-direction: column; + padding: calc(var(--top) + 1rem) 16px 0; background: rgb(10 10 14 / .72); + backdrop-filter: blur(24px); -webkit-backdrop-filter: blur(24px); + animation: drop .22s cubic-bezier(.2, .8, .2, 1); } +@keyframes drop { from { transform: translateY(-100%); } to { transform: none; } } +.drawer-head { display: flex; gap: .5rem; align-items: center; margin-bottom: 1rem; } +.drawer-head .input { flex: 1; height: 2.75rem; border-radius: 999px; padding: 0 1.25rem; font-size: 1rem; + background: rgb(255 255 255 / .1); border-color: rgb(255 255 255 / .15); color: #fff; } +.drawer-head .input::placeholder { color: rgb(255 255 255 / .6); } +.drawer-head .input::-webkit-search-cancel-button { filter: invert(1); } +.drawer-head .btn.ghost { color: #fff; } +.drawer-head .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; } +.drawer-note { margin: 0 0 1rem; font-size: .875rem; opacity: .8; text-align: center; } +.drawer .apps { flex: 1; overflow-y: auto; align-content: start; + padding-bottom: calc(var(--bottom) + 1.5rem); overscroll-behavior: contain; } +.drawer .empty { flex: 1; } +.picking .tile::after { content: ""; position: absolute; top: .1rem; right: .6rem; width: 1.25rem; height: 1.25rem; + border-radius: 999px; border: 2px solid #fff; box-sizing: border-box; + background: rgb(0 0 0 / .35); } +.picking .tile.on::after { content: "✓"; display: grid; place-items: center; font-size: .75rem; font-weight: 700; + background: #fff; color: #111; } + +/* ---- sheets (long-press menus, widget picker) */ +.sheet-overlay { position: fixed; inset: 0; z-index: 20; background: rgb(0 0 0 / .45); animation: ui-fade .15s; } +.sheet { position: fixed; left: 0; right: 0; bottom: 0; z-index: 21; max-width: 560px; margin: 0 auto; + max-height: 70vh; overflow-y: auto; box-sizing: border-box; + padding: .75rem 1rem calc(var(--bottom) + 1rem); border-radius: 1.25rem 1.25rem 0 0; + background: var(--popover); color: var(--popover-foreground); + animation: rise .2s cubic-bezier(.2, .8, .2, 1); } +.sheet::before { content: ""; display: block; width: 2.25rem; height: .3rem; margin: 0 auto .75rem; + border-radius: 999px; background: var(--border); } +@keyframes rise { from { transform: translateY(100%); } to { transform: none; } } +.sheet-title { margin: 0 .5rem .5rem; font-size: 1rem; font-weight: 600; } +.sheet-item { display: block; width: 100%; padding: .85rem .5rem; border: 0; border-radius: var(--radius); + background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; } +.sheet-item:hover, .sheet-item:active { background: var(--accent); } +.sheet .empty { text-shadow: none; color: var(--muted-foreground); } +.widget-list { list-style: none; margin: 0; padding: 0; display: grid; } +.widget-list li { display: flex; align-items: center; gap: .75rem; padding: .5rem; border-radius: var(--radius); + cursor: pointer; } +.widget-list li:hover, .widget-list li:active { background: var(--accent); } +.widget-list .icon { width: 2.5rem; height: 2.5rem; filter: none; } +.widget-name { display: grid; } +.widget-name small { color: var(--muted-foreground); font-size: .8rem; } +.widget-search { width: 100%; margin-bottom: .5rem; } + +.notice, #toast { position: fixed; left: 50%; bottom: calc(var(--bottom) + 2rem); z-index: 30; + transform: translateX(-50%); padding: .5rem 1rem; border-radius: 999px; + background: rgb(0 0 0 / .8); color: #fff; font-size: .875rem; white-space: nowrap; + pointer-events: none; animation: ui-fade .15s; } +#toast { opacity: 0; transition: opacity .2s; animation: none; } +#toast.show { opacity: 1; } + +@media (prefers-reduced-motion: reduce) { .drawer, .sheet { animation: none; } }