Rewrite the launcher in MoonBit (old code moves to legacy/) (#1)
Launcher / test (push) Successful in 1m20s
Launcher / apk (push) Successful in 37s

This commit was merged in pull request #1.
This commit is contained in:
nandi committed 2026-11-23 01:57:10 +00:00
1 parent 7d2bf5996f
commit 2fa7bd745b
150 files changed
+8319 -462

No files matched your search

-1074
View File
File diff suppressed because it is too large. Load diff
BIN
View File
Binary file not shown.
+376
View File
@@ -0,0 +1,376 @@
///|
/// 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) -> Int32 =
#|(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 : Int32, 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 : Int32) -> 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() -> Int32 =
#|() => { window.__imgs = [...document.querySelectorAll("img.icon[data-icon]")]; return window.__imgs.length; }
///|
extern "js" fn icon_key(i : Int32) -> String =
#|(i) => window.__imgs[i].dataset.icon
///|
/// Whether image i already shows the icon for its key.
extern "js" fn icon_done(i : Int32) -> Bool =
#|(i) => window.__imgs[i].__icon === window.__imgs[i].dataset.icon
///|
extern "js" fn icon_set(i : Int32, 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 : Int32) -> 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 : Int32) -> 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 : Int32) -> 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 : Int32) -> Unit =
#|(url, tag) => window.Android.httpGet(url, tag)
///|
extern "js" fn h_install_apk(url : String, version : Int32) -> Unit =
#|(url, v) => window.Android.installApk(url, v)
///|
extern "js" fn h_declined_version() -> Int32 =
#|() => window.Android.declinedVersion()
///|
extern "js" fn h_installed_version() -> Int32 =
#|() => 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 : (Int32) -> 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 : (Int32, 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")
+5 -347
View File
@@ -4,357 +4,15 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>ultra · Launcher</title>
<link rel="stylesheet" href="ui.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- The page is the MoonBit program (launcher.js, built from web/*.mbt): it renders into
#app. On a phone the Java shell serves this folder from the APK's assets, answers
apps.json / widgets.json and provides window.Android; in a desktop browser the demo
JSON files next to this page are used and a toast stands in for each launch. -->
<main id="app"></main>
<div id="toast" role="status"></div>
<script type="module">
import { mount } from "./ultra.js";
// On a phone, MainActivity.java adds window.Android, serves apps.json and
// widgets.json, and draws widgets over the slots reported by place().
// In a desktop browser the demo JSON files are served and these stand-ins run.
const toast = (s) => {
const t = document.getElementById("toast");
t.textContent = s; t.classList.add("show");
clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("show"), 1600);
};
let demoWidget = 100;
const host = window.Android || {
launch: (c) => toast("Open " + c),
appInfo: (c) => toast("App info for " + c),
uninstall: (c) => toast("Uninstall " + c),
addWidget: () => setTimeout(() => window.ultraHome.widgetAdded(demoWidget++), 0),
removeWidget: () => {},
placeWidgets: () => {},
widgetLimits: () => JSON.stringify({ minW: 120, minH: 80, maxW: 0, maxH: 0, h: true, v: true }),
openSettings: () => toast("Open system settings"),
pickWallpaper: () => toast("Pick a wallpaper"),
openRecents: () => toast("Show open windows"),
checkUpdates: () => toast("Check for updates"),
showKeyboard: () => {},
hideKeyboard: () => {},
haptic: () => navigator.vibrate?.(10),
};
if (!window.Android) document.documentElement.classList.add("demo");
// Tell the shell where the live widget slots are (CSS px, viewport-relative).
let placed = "";
const place = () => {
const slots = [...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]; // its body moves it instead of taking touches
});
const j = JSON.stringify(slots);
// The drawer unmarks the slots, but the home screen under it doesn't move, so the
// widgets stay where they were and cover() hides them as it slides over them.
const underDrawer = document.querySelector(".drawer") && !document.querySelector(".sheet-overlay");
if (j !== placed && !underDrawer) { placed = j; host.placeWidgets(j); }
// Keep the system's edge swipes (back) off the resize handles.
const handles = 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)];
}));
if (handles !== excluded) { excluded = handles; host.excludeGestures?.(handles); }
};
let excluded = "[]";
// 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 (coverWidgets(y),
// CSS px; -1 once it covers the screen), so they stay until the drawer reaches them.
// The edge is reported a little ahead (by its speed), since the shell trails a frame.
let coverY = 0, coverLast = 0, coverLoop = false;
const cover = () => {
const d = document.querySelector(".drawer");
let y = 0;
if (d) {
const b = d.getBoundingClientRect().bottom;
y = b >= innerHeight - 1 ? -1 : Math.max(0, Math.ceil(b + 2 * Math.max(0, b - coverLast)));
coverLast = b;
if (y >= innerHeight) y = innerHeight - 1;
} else coverLast = 0;
if (y !== coverY) { coverY = y; host.coverWidgets?.(y); }
if (d && y !== -1 && !coverLoop) {
coverLoop = true;
requestAnimationFrame(() => { coverLoop = false; cover(); });
}
};
// Opening the drawer puts the cursor in its search box and raises the keyboard
// (a WebView won't show it for a focus() the user didn't tap, so the shell does).
// Picking apps to add is for scrolling, so that stays keyboard-free.
let drawerOpen = false;
const watchDrawer = () => {
const d = document.querySelector(".drawer");
if (!!d === drawerOpen) return;
drawerOpen = !!d;
if (d) {
if (d.classList.contains("picking")) return;
d.querySelector(".drawer-head input")?.focus({ preventScroll: true });
host.showKeyboard?.();
} else {
document.activeElement?.blur?.();
host.hideKeyboard?.();
}
};
// Icons: each <img class="icon" data-icon=KEY> 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
// (ultraIcons), so the WebView never loads icons through request interception.
// In a desktop browser the key is already a URL.
const iconSrc = new Map(), asked = new Set();
const setIcon = (img, src) => {
if (src) { img.src = src; img.classList.remove("missing"); } else img.classList.add("missing");
};
const fillIcons = () => {
const want = [];
for (const img of document.querySelectorAll("img.icon[data-icon]")) {
const k = img.dataset.icon;
if (img.__icon === k) continue;
if (iconSrc.has(k)) { img.__icon = k; setIcon(img, iconSrc.get(k)); }
else if (!asked.has(k)) { asked.add(k); want.push(k); }
}
if (!want.length) return;
if (host.loadIcons) host.loadIcons(JSON.stringify(want));
else gotIcons(Object.fromEntries(want.map((k) => [k, k])));
};
// An icon the shell couldn't draw ("") is asked for again, up to 3 times, with backoff;
// until then, and after, it shows as a blank disc.
const tries = new Map();
const gotIcons = (batch) => {
const again = [];
for (const k in batch) {
iconSrc.set(k, batch[k]); asked.delete(k);
const n = tries.get(k) || 0;
if (!batch[k] && n < 3) { tries.set(k, n + 1); again.push(k); }
}
fillIcons();
if (again.length) setTimeout(() => {
for (const k of again) iconSrc.delete(k);
for (const img of document.querySelectorAll("img.icon[data-icon]"))
if (again.includes(img.dataset.icon)) img.__icon = undefined;
fillIcons();
}, 800 * (tries.get(again[0]) || 1));
};
window.ultraIcons = gotIcons; // the shell calls this before ultraHome exists, too
let ready = false; // the grid code below exists and app is mounted
const app = await mount("#app", "./app.wasm", {
onRender: () => { fillIcons(); place(); cover(); watchDrawer(); if (ready) measureGrid(); },
imports: ({ strs }) => ({
launch: (h) => host.launch(strs[h]),
app_info: (h) => host.appInfo(strs[h]),
uninstall: (h) => host.uninstall(strs[h]),
add_widget: (h) => host.addWidget(strs[h]),
remove_widget: (id) => host.removeWidget(id),
open_settings: () => host.openSettings(),
pick_wallpaper: () => host.pickWallpaper(),
open_recents: () => host.openRecents(),
check_updates: () => host.checkUpdates(),
haptic: () => host.haptic(),
}),
});
ready = true;
// Messages the shell and the gestures below send (keep in sync with app.py).
const RELOAD = 2, HOME = 3, BACK = 4, SWIPE_DOWN = 5, SWIPE_UP = 6,
WIDGET_ADDED = 7, WIDGET_MENU = 8, DRAG_TO = 35, DROP = 36, RESIZE = 40, GRAB = 42, WIDGET_COLS = 44,
GRID = 45, MOVE_CELL = 47;
// The home grid: its columns, and as many rows as fit down to the bottom of the
// screen (app.py lays those out, so the empty cells there are real cells).
const grid = () => {
const slots = document.querySelector(".slots");
if (!slots) return null;
const cs = getComputedStyle(slots), r = slots.getBoundingClientRect();
const colW = parseFloat(cs.gridTemplateColumns), gap = parseFloat(cs.columnGap) || 0;
return { left: r.left, top: r.top, cols: cs.gridTemplateColumns.split(" ").length,
colW, gap, cell: parseFloat(cs.gridAutoRows) || 64, rgap: parseFloat(cs.rowGap) || 0,
rows: cs.gridTemplateRows.split(" ").length };
};
let gridSent = -1;
const measureGrid = () => {
const g = grid(), home = document.querySelector(".home");
if (!g || !home) return;
const bottom = innerHeight - parseFloat(getComputedStyle(home).paddingBottom); // of the first screen
const rows = Math.max(1, Math.floor((bottom - (g.top + scrollY) + g.rgap) / (g.cell + g.rgap)));
const v = g.cols * 4096 + rows;
if (v !== gridSent) { gridSent = v; app.dispatch(GRID, v); }
};
const cellAt = (g, x, y) => [Math.max(0, Math.round((x - g.left) / (g.colW + g.gap))),
Math.max(0, Math.round((y - g.top) / (g.cell + g.rgap)))];
// Dragging a home slot. A long press lifts it (app.py marks it .lifted). Moving the
// finger over another slot moves it there in the order (the grid stays packed);
// over an empty cell it is left in that cell (top left by where it was held), and
// letting go drops it; whatever it then covers moves on to free cells.
// Letting go without moving opens its menu instead. A widget showing resize handles
// needs no long press: pressing its body picks it up right away (GRAB), and it keeps
// its handles when let go. Native widget views take their own touches, so the shell
// reports those through widgetGrab/widgetDrag/widgetDrop.
let drag = null, dragged = false; // drag: { x, y, moved } from pointerdown
let carry = null; // { dx, dy, cell }: where the lifted slot was held, the cell sent last
const inside = (r, x, y) => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;
const slotAt = (x, y) => {
for (const li of document.querySelectorAll(".slots > li[data-slot]:not(.lifted)"))
if (inside(li.getBoundingClientRect(), x, y)) return +li.dataset.slot;
return -1;
};
const dragTo = (x, y, x0 = x, y0 = y) => { // x0, y0: where the finger went down
const lifted = document.querySelector(".slots > .lifted"), g = grid();
if (!lifted || !g) return;
if (!carry) {
const r = lifted.getBoundingClientRect();
carry = { dx: x0 - r.left, dy: y0 - r.top, cell: -1 };
}
// A widget goes to the cell under it wherever that is (apps flow around it), so it
// can sit on any row; an app over another app takes its place in the order.
const widget = lifted.classList.contains("widget-slot");
if (!widget && inside(lifted.getBoundingClientRect(), x, y)) return;
// the cell under the finger: a slot there takes the lifted one's place in the order
const [fc, fr] = cellAt(g, x - g.colW / 2, y - g.cell / 2);
const to = slotAt(x, y) >= 0 ? slotAt(x, y)
: slotAt(g.left + fc * (g.colW + g.gap) + g.colW / 2, g.top + fr * (g.cell + g.rgap) + g.cell / 2);
if (to >= 0 && !widget) { carry.cell = -1; app.dispatch(DRAG_TO, to); return; }
if (y > g.top + g.rows * (g.cell + g.rgap)) return; // below the grid
const [col, row] = cellAt(g, x - carry.dx, y - carry.dy);
const cell = row * 64 + Math.min(col, 63);
if (cell !== carry.cell) { carry.cell = cell; app.dispatch(MOVE_CELL, cell); }
};
const drop = (moved) => {
carry = null;
if (document.querySelector(".slots > .lifted")) app.dispatch(DROP, moved ? 1 : 0);
};
let grabbed = false;
const grab = (li) => { grabbed = true; app.dispatch(GRAB, +li.dataset.slot); };
addEventListener("pointerdown", (e) => {
const li = e.isPrimary && !e.target.closest?.(".resize-handle") && e.target.closest?.(".slots > li.resizing");
if (li) grab(li);
}, true);
addEventListener("pointerdown", (e) => {
drag = e.isPrimary && e.target.closest?.(".slots > li") ? { x: e.clientX, y: e.clientY, moved: false } : null;
dragged = false;
});
addEventListener("pointermove", (e) => {
if (!drag || !document.querySelector(".slots > .lifted")) return;
if (!drag.moved && Math.hypot(e.clientX - drag.x, e.clientY - drag.y) < 10) return;
drag.moved = dragged = true;
dragTo(e.clientX, e.clientY, drag.x, drag.y);
});
addEventListener("pointerup", () => { if (drag) drop(drag.moved); drag = null; });
addEventListener("pointercancel", () => { if (drag) drop(drag.moved); drag = null; });
// Keep the page from scrolling under a lifted slot.
addEventListener("touchmove", (e) => {
if (drag && document.querySelector(".slots > .lifted") && e.cancelable) e.preventDefault();
}, { passive: false });
// Resizing a widget. Holding a widget and letting go without moving shows handles on
// its right edge, bottom edge and corner (app.py). Dragging one snaps the widget to
// whole grid columns and rows, within the shell's limits for that widget
// (widgetLimits, CSS px: min/max size, 0 = no max, and whether it resizes h and v).
let rs = null, swallowClick = false;
const span = (k, size, gap) => k * size + (k - 1) * gap;
const fit = (want, lo, hi, size, gap, min, max) => {
// the step nearest to want, kept within [min, max] px where it can be
let k = Math.round((want + gap) / (size + gap));
while (k < hi && span(k, size, gap) < min - 8) k++;
while (k > lo && max > 0 && span(k, size, gap) > max + 8) k--;
return Math.max(lo, Math.min(hi, k));
};
addEventListener("pointerdown", (e) => {
const h = e.target.closest?.(".resize-handle");
if (!h || !e.isPrimary) return;
e.stopPropagation(); e.preventDefault(); // not a long press on the slot under it
const li = h.closest("li"), slots = li.parentElement, cs = getComputedStyle(slots);
const cols = cs.gridTemplateColumns.split(" ").map(parseFloat);
const wid = +li.dataset.wid || 0;
let lim = {};
try { lim = JSON.parse(host.widgetLimits?.(wid) || "{}"); } catch {}
const r = li.getBoundingClientRect();
rs = { li, edge: h.dataset.edge, left: r.left, top: r.top, lim, n: cols.length, colW: cols[0],
gap: parseFloat(cs.columnGap) || 0, rgap: parseFloat(cs.rowGap) || 0,
cell: parseFloat(cs.gridAutoRows) || 88, // a row of app tiles
cols: Math.round((r.width + (parseFloat(cs.columnGap) || 0)) / (cols[0] + (parseFloat(cs.columnGap) || 0))),
h: Math.round(r.height) };
dragged = true;
h.setPointerCapture?.(e.pointerId);
}, true);
addEventListener("pointermove", (e) => {
if (!rs) return;
const { lim, n, colW, gap, rgap, cell } = rs;
let cols = rs.cols, h = rs.h;
if (rs.edge !== "b" && lim.h !== false)
cols = fit(e.clientX - rs.left, 1, n, colW, gap, lim.minW || 0, lim.maxW || 0);
if (rs.edge !== "r" && lim.v !== false) {
const k = fit(e.clientY - rs.top, 1, 20, cell, rgap, lim.minH || 0, lim.maxH || 0);
h = Math.round(span(k, cell, rgap));
}
if (cols === rs.cols && h === rs.h) return;
rs.cols = cols; rs.h = h;
host.haptic();
app.dispatch(RESIZE, (cols >= n ? 0 : cols) * 4096 + h);
}, true);
const endResize = () => { if (rs || grabbed) { rs = null; grabbed = false; swallowClick = true; setTimeout(() => swallowClick = false, 0); } };
addEventListener("pointerup", endResize, true);
addEventListener("pointercancel", endResize, true);
addEventListener("click", (e) => { // the click that ends a handle drag or a move isn't a tap beside the widget
if (swallowClick || e.target.closest?.(".resize-handle")) { swallowClick = false; e.stopPropagation(); e.preventDefault(); }
}, true);
addEventListener("touchmove", (e) => { if (rs && e.cancelable) e.preventDefault(); }, { passive: false });
// A new widget starts as many columns wide as its natural width needs (widgetLimits
// "w", CSS px), like its height starts at whole rows; 0 is the whole row.
const widgetCols = (id) => {
let lim = {};
try { lim = JSON.parse(host.widgetLimits?.(id) || "{}"); } catch {}
const slots = document.querySelector(".slots");
if (!lim.w || !slots) return 0;
const cs = getComputedStyle(slots), cols = cs.gridTemplateColumns.split(" ").map(parseFloat);
const gap = parseFloat(cs.columnGap) || 0;
const k = Math.max(1, Math.ceil((lim.w + gap - 8) / (cols[0] + gap)));
return k >= cols.length ? 0 : k;
};
window.ultraHome = {
reload: () => app.dispatch(RELOAD, 0),
home: () => { app.dispatch(HOME, 0); window.scrollTo({ top: 0, behavior: "smooth" }); },
back: () => app.dispatch(BACK, 0),
widgetAdded: (id) => { app.dispatch(WIDGET_ADDED, id); app.dispatch(WIDGET_COLS, widgetCols(id)); },
widgetMenu: (id) => app.dispatch(WIDGET_MENU, id),
widgetGrab: (id) => { const li = document.querySelector(`.widget-slot.resizing[data-wid="${id}"]`);
if (li) app.dispatch(GRAB, +li.dataset.slot); },
widgetDrag: (x, y) => { dragged = true; dragTo(x, y); },
widgetDrop: (moved) => drop(moved),
place: () => { placed = ""; place(); },
resetIcons: () => { iconSrc.clear(); asked.clear(); tries.clear();
for (const img of document.querySelectorAll("img.icon")) img.__icon = undefined; },
};
addEventListener("scroll", () => requestAnimationFrame(place), { passive: true });
addEventListener("resize", () => requestAnimationFrame(() => { place(); measureGrid(); }));
measureGrid();
// Swipe down on the home screen opens the drawer; swipe up closes it once its
// list is scrolled to the end (or doesn't scroll).
let start = null;
addEventListener("touchstart", (e) => {
const t = e.touches[0];
start = e.touches.length === 1 ? { x: t.clientX, y: t.clientY, at: Date.now() } : null;
}, { passive: true });
addEventListener("touchend", (e) => {
if (!start || dragged || document.querySelector(".slots > .lifted")) { start = null; return; }
const t = e.changedTouches[0], dx = t.clientX - start.x, dy = t.clientY - start.y;
const quick = Date.now() - start.at < 700;
start = null;
if (!quick || Math.abs(dy) < 60 || Math.abs(dx) > Math.abs(dy)) return;
if (document.querySelector(".sheet")) return;
const list = document.querySelector(".drawer .apps");
if (dy > 0 && !list && window.scrollY <= 0) app.dispatch(SWIPE_DOWN, 0);
else if (dy < 0 && list && list.scrollTop + list.clientHeight >= list.scrollHeight - 2) app.dispatch(SWIPE_UP, 0);
}, { passive: true });
</script>
<script type="module" src="launcher.js"></script>
</body>
</html>
+495
View File
@@ -0,0 +1,495 @@
///|
/// 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(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 : Int32
mut cover_last : Double
mut cover_loop : Bool
mut measured : String
mut touch : (Double, Double, Double)?
mut demo_widget : Int32
mut http_tag : Int32
http : Map[Int32, (Bool, String) -> Unit]
icon_src : Map[String, String]
icon_asked : Map[String, Bool]
icon_tries : Map[String, Int32]
}
///|
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())
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 `<img class="icon" data-icon=KEY>` 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..<n {
if icon_done(i) {
continue
}
let k = icon_key(i)
if !loader {
icon_set(i, k)
} else if st.icon_src.get(k) is Some(src) {
icon_set(i, src)
} else if !st.icon_asked.contains(k) {
st.icon_asked[k] = true
want.push(Json::string(k))
}
}
if want.length() > 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[Int32] {
if s == "" {
return []
}
let out : Array[Int32] = []
for part in s.split(",") {
out.push(@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()
})
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 {
@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() {
// the shell keeps the build whose install the user cancelled (-1: none)
let declined = h_declined_version()
dispatch(
Started(
now=now_ms().to_int64(),
last_check=num("launcher.update.lastCheck"),
declined~,
installed=h_installed_version(),
),
)
}
render()
}
+10
View File
@@ -0,0 +1,10 @@
import {
"experiments/launcher/app",
"experiments/launcher/vdom",
"experiments/launcher/gesture",
"moonbitlang/core/string",
}
pkgtype(kind: "executable")
supported_targets = "js"
+189
View File
@@ -0,0 +1,189 @@
///|
/// 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 : Int32
mut text : String
mut n : Int32
mut classes : String
mut attrs : 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: {},
style: "",
children: [],
}
El(e) =>
{
dom: dom_create(e.tag),
is_text: false,
tag: e.tag,
key: e.key,
text: "",
n: -1,
classes: "",
attrs: {},
style: "",
children: [],
}
}
}
///|
fn update_rnode(
r : RNode,
n : @vdom.Node[@app.Msg],
counter : Ref[Int32],
) -> 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] = Map([])
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[Int32],
) -> Array[RNode] {
let used : Array[Bool] = Array::make(old.length(), false)
let by_key : Map[Int32, Int32] = Map([])
for i in 0..<old.length() {
if old[i].key != 0 {
by_key[old[i].key] = i
}
}
let out : Array[RNode] = []
for n in new {
let mut found = -1
match n {
El(e) if e.key != 0 =>
if by_key.get(e.key) is Some(i) && !used[i] && compatible(old[i], n) {
found = i
}
_ =>
for i in 0..<old.length() {
if !used[i] && old[i].key == 0 && compatible(old[i], n) {
found = i
break
}
}
}
let r = if found >= 0 {
used[found] = true
old[found]
} else {
new_rnode(n)
}
update_rnode(r, n, counter)
out.push(r)
}
for i in 0..<old.length() {
if !used[i] {
dom_remove(old[i].dom)
}
}
// put the elements in order, last to first, each before the one after it
for j = out.length() - 1; j >= 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(0))
}
+15
View File
@@ -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
+117 -9
View File
@@ -1,3 +1,99 @@
/* 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. */
@@ -32,14 +128,10 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t
.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 denser than the drawer: an extra column, smaller tiles. Its rows are
all one height, so a widget spans whole rows of app tiles, and apps fill the cells
beside a widget rather than leaving holes (dense packing). Keep the row height and
row gap in sync with widget_rows in app.py. */
.slots { grid-template-columns: repeat(5, minmax(0, 1fr)); grid-auto-rows: 4rem; row-gap: .5rem;
grid-auto-flow: row dense; }
@media (min-width: 480px) { .apps { grid-template-columns: repeat(5, minmax(0, 1fr)); }
.slots { grid-template-columns: repeat(6, 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); }
@@ -54,7 +146,7 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t
/* 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 { grid-column: 1 / -1; display: grid; place-items: center; box-sizing: border-box;
.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);
@@ -83,6 +175,9 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t
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; }
@@ -96,6 +191,19 @@ body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: t
.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);
-224
View File
@@ -1,224 +0,0 @@
/* ultra/ui.css: shadcn/ui's look as plain CSS, for the helpers in ui.py.
*
* The tokens are shadcn's "neutral" theme (https://ui.shadcn.com/docs/theming)
* and the component rules follow its Tailwind classes. Override any token on
* :root to retheme. Dark mode follows the OS, or force it with class="dark"
* (or "light") on any element; this needs CSS light-dark() (2024+ browsers).
* `build` copies this file next to app.wasm.
*/
/* Each token is light-dark(light, dark), so it follows color-scheme. */
: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);
font-size: .875rem; font-weight: 500; line-height: 1; white-space: nowrap;
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; }
/* ---------------------------------------------------------------- card */
.card {
display: flex; flex-direction: column; gap: 1.5rem; padding: 1.5rem 0;
background: var(--card); color: var(--card-foreground);
border: 1px solid var(--border); border-radius: calc(var(--radius) + 4px); box-shadow: var(--shadow-sm);
}
.card-header { display: grid; gap: .375rem; padding: 0 1.5rem; }
.card-title { margin: 0; font-size: 1rem; font-weight: 600; line-height: 1; }
.card-description { margin: 0; font-size: .875rem; color: var(--muted-foreground); }
.card-content { padding: 0 1.5rem; }
.card-footer { display: flex; align-items: center; gap: .5rem; padding: 0 1.5rem; }
/* ---------------------------------------------------------------- input, label */
.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); }
.label { display: flex; align-items: center; gap: .5rem; font-size: .875rem; font-weight: 500; line-height: 1; user-select: none; }
.field { display: inline-flex; align-items: center; gap: .5rem; cursor: pointer; }
/* ---------------------------------------------------------------- badge */
.badge {
display: inline-flex; align-items: center; justify-content: center; gap: .25rem; width: fit-content;
padding: .125rem .5rem; border: 1px solid transparent; border-radius: calc(var(--radius) - 2px);
font-size: .75rem; font-weight: 500; white-space: nowrap;
background: var(--primary); color: var(--primary-foreground);
}
.badge.secondary { background: var(--secondary); color: var(--secondary-foreground); }
.badge.destructive { background: light-dark(var(--destructive), color-mix(in oklab, var(--destructive) 60%, transparent)); color: #fff; }
.badge.outline { background: none; color: var(--foreground); border-color: var(--border); }
/* ---------------------------------------------------------------- checkbox, switch */
.checkbox {
position: relative; flex: none; width: 1rem; height: 1rem; padding: 0; cursor: pointer;
border: 1px solid var(--input); border-radius: 4px; background: var(--input-bg); box-shadow: var(--shadow-xs);
transition: box-shadow .15s;
}
.checkbox[aria-checked="true"] { background: var(--primary); border-color: var(--primary); }
.checkbox[aria-checked="true"]::after {
content: ""; position: absolute; left: 4.5px; top: 1.5px; width: 4px; height: 8px;
border: solid var(--primary-foreground); border-width: 0 2px 2px 0; transform: rotate(45deg);
}
.switch {
display: inline-flex; flex: none; align-items: center; width: 2rem; height: 1.15rem; padding: 0;
border: 1px solid transparent; border-radius: 999px; background: var(--input); cursor: pointer;
box-shadow: var(--shadow-xs); transition: background-color .15s;
}
.switch::after {
content: ""; width: 1rem; height: 1rem; border-radius: 999px; background: var(--background);
transition: transform .15s;
}
.switch:not([aria-checked="true"])::after { background: light-dark(var(--background), var(--foreground)); }
.switch[aria-checked="true"] { background: var(--primary); }
.switch[aria-checked="true"]::after { transform: translateX(calc(100% - 2px)); }
/* ---------------------------------------------------------------- tabs, toggle group */
.tabs-list {
display: inline-flex; align-items: center; height: 2.25rem; width: fit-content; padding: 3px;
border-radius: var(--radius); background: var(--muted); color: var(--muted-foreground);
}
.tab {
display: inline-flex; flex: 1; align-items: center; justify-content: center; height: 100%;
padding: .25rem .5rem; border: 1px solid transparent; border-radius: calc(var(--radius) - 2px);
background: none; font-size: .875rem; font-weight: 500; white-space: nowrap; cursor: pointer;
color: light-dark(var(--foreground), var(--muted-foreground)); transition: color .15s, box-shadow .15s;
}
.tab[aria-selected="true"] {
background: light-dark(var(--background), var(--input-bg)); border-color: light-dark(transparent, var(--input));
color: var(--foreground); box-shadow: var(--shadow-sm);
}
.toggle-group { display: inline-flex; width: fit-content; border-radius: calc(var(--radius) - 2px); box-shadow: var(--shadow-xs); }
.toggle {
display: inline-flex; align-items: center; justify-content: center; height: 2.25rem; min-width: 2.25rem;
padding: 0 .75rem; border: 1px solid var(--input); background: none; font-size: .875rem; font-weight: 500;
cursor: pointer; transition: background-color .15s;
}
.toggle:hover { background: var(--muted); color: var(--muted-foreground); }
.toggle[aria-pressed="true"] { background: var(--accent); color: var(--accent-foreground); }
.toggle-group .toggle { border-radius: 0; }
.toggle-group .toggle + .toggle { border-left: 0; }
.toggle-group .toggle:first-child { border-radius: calc(var(--radius) - 2px) 0 0 calc(var(--radius) - 2px); }
.toggle-group .toggle:last-child { border-radius: 0 calc(var(--radius) - 2px) calc(var(--radius) - 2px) 0; }
/* ---------------------------------------------------------------- dialog */
.dialog-overlay { position: fixed; inset: 0; z-index: 50; background: rgb(0 0 0 / .5); animation: ui-fade .15s; }
.dialog {
position: fixed; z-index: 50; top: 50%; left: 50%; transform: translate(-50%, -50%);
display: grid; gap: 1rem; width: calc(100% - 2rem); max-width: 32rem; padding: 1.5rem;
border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-lg);
background: var(--background); color: var(--foreground); animation: ui-zoom .15s;
}
.dialog-header { display: grid; gap: .5rem; }
.dialog-title { margin: 0; font-size: 1.125rem; font-weight: 600; line-height: 1; }
.dialog-description { margin: 0; font-size: .875rem; color: var(--muted-foreground); }
.dialog-footer { display: flex; flex-wrap: wrap-reverse; justify-content: flex-end; gap: .5rem; }
.dialog-close {
position: absolute; top: 1rem; right: 1rem; width: 1.25rem; height: 1.25rem; padding: 0;
border-radius: 4px; background: none; font-size: 1.125rem; line-height: 1; opacity: .7; cursor: pointer;
}
.dialog-close:hover { opacity: 1; }
@keyframes ui-fade { from { opacity: 0; } }
@keyframes ui-zoom { from { opacity: 0; transform: translate(-50%, -50%) scale(.95); } }
/* ---------------------------------------------------------------- alert, separator, progress, kbd */
.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); }
.separator { flex: none; height: 1px; width: 100%; margin: 0; border: 0; background: var(--border); }
.progress {
display: block; width: 100%; height: .5rem; overflow: hidden; border: 0; border-radius: 999px;
appearance: none; background: color-mix(in oklab, var(--primary) 20%, transparent);
}
.progress::-webkit-progress-bar { background: transparent; }
.progress::-webkit-progress-value { background: var(--primary); transition: width .2s; }
.progress::-moz-progress-bar { background: var(--primary); }
.kbd {
display: inline-flex; align-items: center; justify-content: center; height: 1.25rem; min-width: 1.25rem;
padding: 0 .25rem; border-radius: 4px; background: var(--muted); color: var(--muted-foreground);
font: 500 .75rem var(--font-sans);
}
/* ---------------------------------------------------------------- table */
.table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.table th { height: 2.5rem; padding: 0 .5rem; text-align: left; font-weight: 500; white-space: nowrap; }
.table td { padding: .5rem; }
.table tr { border-bottom: 1px solid var(--border); }
.table tbody tr:hover { background: color-mix(in oklab, var(--muted) 50%, transparent); }
.table tr[aria-selected="true"] { background: var(--muted); }
-410
View File
@@ -1,410 +0,0 @@
// ultra.js: the DOM glue for ultra apps written in LPython.
//
// The wasm module calls into the "js" imports below while view() runs; those
// calls build a lightweight vnode tree. After view() returns we diff the new
// tree against the last one and patch the DOM. Events are delegated from the
// mount point and turned into update(msg, arg) calls.
const EVENT = 0;
export async function mount(root, url, opts = {}) {
if (typeof root === "string") root = document.querySelector(root);
let mem, ex;
const td = new TextDecoder();
const cache = new Map();
// LPython strings are a pointer to { data: i32, len: i32 }.
// Literals live in static data, so decoding is cached by (data, len).
let dv = null;
const str = (p) => {
if (dv === null || dv.buffer !== mem.buffer) dv = new DataView(mem.buffer);
const a = dv.getInt32(p, true), l = dv.getInt32(p + 4, true);
const k = a * 4096 + l;
let s = cache.get(k);
if (s === undefined) {
s = td.decode(new Uint8Array(mem.buffer, a, l));
if (l < 4096) cache.set(k, s);
}
return s;
};
const K = (k) => (typeof k === "object" ? k.k : str(k)); // storage key
// ------------------------------------------------------------ string store
const strs = [""];
const free = [];
const sNew = (v = "") => {
if (free.length) { const h = free.pop(); strs[h] = v; return h; }
strs.push(v); return strs.length - 1;
};
// ------------------------------------------------------------ vnode builder
// vnode: { t, k, a, cls, p, ev, c, n } text: { t: "#", s, n }
let stack, cur;
const node = (t) => ({ t, k: null, a: null, cls: "", p: null, ev: null, c: [], n: null });
let nodes = 0;
const push = (v) => { nodes++; cur.c.push(v); };
const txt = (s) => push({ t: "#", k: null, s: String(s), n: null });
const setA = (k, v) => ((cur.a ||= {})[k] = v);
const setP = (k, v) => ((cur.p ||= {})[k] = v);
const setEv = (k, v) => ((cur.ev ||= {})[k] = v);
// ------------------------------------------------------------ scheduling
// Messages are applied immediately; the re-render is batched onto the next
// animation frame. frame(msg, arg) messages are held until that frame and
// applied just before view(), so an animation steps once per rendered frame.
let queued = false;
let frameQ = [];
let since = 0, tUpdate = 0; // first dispatch since the last render, time in update()
const schedule = () => {
if (queued) return;
queued = true;
if (!since) since = performance.now();
requestAnimationFrame(render);
};
const dispatch = (msg, arg) => {
const t = performance.now();
if (!since) since = t;
ex.update(msg, arg);
tUpdate += performance.now() - t;
schedule();
};
// ------------------------------------------------------------ json store
// Decoded JSON values live here too; LPython holds i32 handles and reads
// fields by dotted path ("repos.3.did"). Handle 0 is "nothing".
const vals = [undefined];
const vfree = [];
const vNew = (v) => {
if (v === undefined) return 0;
if (vfree.length) { const h = vfree.pop(); vals[h] = v; return h; }
vals.push(v); return vals.length - 1;
};
const walk = (h, p) => {
let v = vals[h];
const path = str(p);
if (path) for (const k of path.split(".")) { if (v == null) return undefined; v = v[k]; }
return v;
};
const asText = (v) => (typeof v === "string" ? v : JSON.stringify(v, null, 2));
const httpGet = (url, msg) => {
const h = vNew(null);
fetch(url, { headers: { accept: "application/json" } })
.then(async (r) => {
const body = await r.json().catch(() => null);
vals[h] = r.ok ? body
: { __error: (body && (body.message || body.error)) || "HTTP " + r.status };
})
.catch((e) => { vals[h] = { __error: String(e.message || e) }; })
.then(() => dispatch(msg, h));
return h;
};
const js = {
el: (p) => { const v = node(str(p)); push(v); stack.push(cur); cur = v; },
end: () => { cur = stack.pop(); },
text: (p) => txt(str(p)),
num: (x) => txt(x),
fnum: (x, d) => txt(x.toFixed(d)),
text_ref: (h) => txt(strs[h] ?? ""),
attr: (k, v) => setA(str(k), str(v)),
attr_num: (k, v) => setA(str(k), String(v)),
attr_ref: (k, h) => setA(str(k), strs[h] ?? ""),
cls: (p) => { const c = str(p); if (c) cur.cls = cur.cls ? cur.cls + " " + c : c; },
cls_if: (p, on) => { if (on) js.cls(p); },
key: (k) => { cur.k = k; },
value_ref: (h) => setP("value", strs[h] ?? ""),
checked: (on) => setP("checked", !!on),
autofocus: () => setP("__focus", true),
on_click: (m, a) => setEv("click", [m, a]),
on_dblclick: (m, a) => setEv("dblclick", [m, a]),
on_input: (m) => setEv("input", [m, EVENT]),
on_enter: (m, a) => setEv("enter", [m, a]),
on_escape: (m, a) => setEv("escape", [m, a]),
on_longpress: (m, a) => setEv("longpress", [m, a]),
after: (ms, m, a) => setTimeout(() => dispatch(m, a), ms),
frame: (m, a) => { frameQ.push(m, a); schedule(); },
now_ms: () => performance.now(),
log: (x) => console.log("[ultra]", x),
s_new: () => sNew(),
s_dup: (h) => sNew(strs[h]),
s_copy: (d, s) => { strs[d] = strs[s]; },
s_clear: (h) => { strs[h] = ""; },
s_free: (h) => { if (h > 0) { strs[h] = ""; free.push(h); } },
s_len: (h) => (strs[h] ?? "").trim().length,
s_set: (h, p) => { strs[h] = str(p); },
s_add: (h, p) => { strs[h] += str(p); },
s_add_ref: (h, s) => { strs[h] += strs[s] ?? ""; },
s_add_num: (h, x) => { strs[h] += String(x); },
s_eq: (a, b) => (strs[a] === strs[b] ? 1 : 0),
s_has: (h, n) => ((strs[h] ?? "").toLowerCase().includes((strs[n] ?? "").trim().toLowerCase()) ? 1 : 0),
s_save: (k, h) => { try { localStorage.setItem(K(k), strs[h]); } catch {} },
s_load: (k, h) => {
let v = null;
try { v = localStorage.getItem(K(k)); } catch {}
if (v === null) return 0;
strs[h] = v; return 1;
},
store_i32: (k, v) => { try { localStorage.setItem(K(k), String(v)); } catch {} },
load_i32: (k, d) => {
let v = null;
try { v = localStorage.getItem(K(k)); } catch {}
return v === null ? d : v | 0;
},
http_get: (p, m) => httpGet(str(p), m),
http_get_ref: (h, m) => httpGet(strs[h], m),
j_ok: (h) => (vals[h] != null && !(typeof vals[h] === "object" && "__error" in vals[h]) ? 1 : 0),
j_err: (h, d) => { const v = vals[h]; strs[d] = v && v.__error ? v.__error : v == null ? "no response" : ""; },
j_at: (h, p) => vNew(walk(h, p)),
j_idx: (h, i) => vNew((vals[h] ?? [])[i]),
j_has: (h, p) => (walk(h, p) != null ? 1 : 0),
j_len: (h, p) => {
const v = walk(h, p);
return Array.isArray(v) || typeof v === "string" ? v.length : v && typeof v === "object" ? Object.keys(v).length : 0;
},
j_int: (h, p) => { const v = walk(h, p); return typeof v === "boolean" ? +v : Number(v) | 0; },
j_str: (h, p, d) => { const v = walk(h, p); strs[d] = v == null ? "" : asText(v); return v == null ? 0 : 1; },
j_key: (h, i, d) => { strs[d] = Object.keys(vals[h] ?? {})[i] ?? ""; },
j_free: (h) => { if (h > 0) { vals[h] = undefined; vfree.push(h); } },
};
// Apps can declare their own @jscall imports and supply them here.
if (opts.imports) Object.assign(js, opts.imports({ str, strs, vals, sNew, dispatch, text: txt }));
for (const f of ["s_save", "s_load", "store_i32", "load_i32"]) {
const base = js[f];
js[f + "_at"] = (k, i, x) => base({ k: str(k) + "." + i }, x);
}
// Minimal WASI so print() works and _start-style exits don't crash.
const wasi = {
proc_exit: () => {},
fd_write: (fd, iovs, n, out) => {
const dv = new DataView(mem.buffer);
let s = "", total = 0;
for (let i = 0; i < n; i++) {
const p = dv.getInt32(iovs + i * 8, true), l = dv.getInt32(iovs + i * 8 + 4, true);
s += td.decode(new Uint8Array(mem.buffer, p, l)); total += l;
}
(fd === 2 ? console.error : console.log)(s.replace(/\n$/, ""));
dv.setInt32(out, total, true);
return 0;
},
};
const imports = { js, wasi_snapshot_preview1: wasi };
let instance;
if (typeof url === "string") {
const res = await fetch(url);
// Streaming compile needs the application/wasm MIME type; fall back if absent.
({ instance } = (res.headers.get("content-type") || "").startsWith("application/wasm")
? await WebAssembly.instantiateStreaming(res, imports)
: await WebAssembly.instantiate(await res.arrayBuffer(), imports));
} else {
({ instance } = await WebAssembly.instantiate(url, imports));
}
ex = instance.exports;
mem = ex.memory;
// ------------------------------------------------------------ diff / patch
const create = (v) => {
if (v.t === "#") return (v.n = document.createTextNode(v.s));
const n = (v.n = document.createElement(v.t));
if (v.cls) n.className = v.cls;
if (v.a) for (const k in v.a) n.setAttribute(k, v.a[k]);
if (v.p) setProps(n, null, v.p);
n.__ev = v.ev;
for (const c of v.c) n.appendChild(create(c));
return n;
};
const setProps = (n, o, p) => {
for (const k in p) {
if (k === "__focus") { if (!o || !o.__focus) queueMicrotask(() => n.focus()); continue; }
if (n[k] !== p[k]) n[k] = p[k];
}
};
const patch = (o, v) => {
if (o.t !== v.t || o.k !== v.k) {
const n = create(v);
o.n.replaceWith(n);
return;
}
const n = (v.n = o.n);
if (v.t === "#") { if (o.s !== v.s) n.data = v.s; return; }
if (o.cls !== v.cls) n.className = v.cls;
if (o.a !== v.a) {
const oa = o.a || {}, va = v.a || {};
for (const k in oa) if (!(k in va)) n.removeAttribute(k);
for (const k in va) if (oa[k] !== va[k]) n.setAttribute(k, va[k]);
}
if (v.p) setProps(n, o.p, v.p);
n.__ev = v.ev;
patchChildren(n, o.c, v.c);
};
const patchChildren = (parent, oc, vc) => {
if (oc.length === 0 && vc.length === 0) return;
const keyed = vc.length > 0 && vc[0].k !== null && oc.length > 0 && oc[0].k !== null;
if (vc.length === 0 && parent.childNodes.length === oc.length) {
parent.textContent = ""; // clearing a whole list: one DOM op
return;
}
if (!keyed) {
const m = Math.min(oc.length, vc.length);
for (let i = 0; i < m; i++) patch(oc[i], vc[i]);
for (let i = m; i < vc.length; i++) parent.appendChild(create(vc[i]));
for (let i = m; i < oc.length; i++) oc[i].n.remove();
return;
}
patchKeyed(parent, oc, vc);
};
// Keyed children: skip the common prefix and suffix, then match the middle by
// key and move only the nodes outside the longest increasing subsequence of
// old positions. Swapping two rows of 1,000 moves 2 nodes, not 998.
const patchKeyed = (parent, oc, vc) => {
let os = 0, oe = oc.length - 1, vs = 0, ve = vc.length - 1;
while (os <= oe && vs <= ve && oc[os].k === vc[vs].k) patch(oc[os++], vc[vs++]);
while (os <= oe && vs <= ve && oc[oe].k === vc[ve].k) patch(oc[oe--], vc[ve--]);
const anchor = ve + 1 < vc.length ? vc[ve + 1].n : null;
if (os > oe) {
for (let i = vs; i <= ve; i++) parent.insertBefore(create(vc[i]), anchor);
return;
}
if (vs > ve) {
for (let i = os; i <= oe; i++) oc[i].n.remove();
return;
}
const at = new Map();
for (let i = vs; i <= ve; i++) at.set(vc[i].k, i);
if (os === 0 && oe === oc.length - 1 && parent.childNodes.length === oc.length &&
!oc.some((o) => at.has(o.k))) {
// Nothing reused (e.g. replacing every row): drop all, build all.
parent.textContent = "";
for (const v of vc) parent.appendChild(create(v));
return;
}
const src = new Int32Array(ve - vs + 1).fill(-1); // new slot -> old index
let moved = false, last = -1;
for (let i = os; i <= oe; i++) {
const o = oc[i], j = at.get(o.k);
if (j === undefined) { o.n.remove(); continue; }
src[j - vs] = i;
patch(o, vc[j]);
if (j < last) moved = true; else last = j;
}
const keep = moved ? lis(src) : null;
let li = keep ? keep.length - 1 : -1;
let next = anchor;
for (let j = ve; j >= vs; j--) {
const v = vc[j], p = j - vs;
if (src[p] === -1) parent.insertBefore(create(v), next);
else if (moved) {
if (li >= 0 && keep[li] === p) li--;
else parent.insertBefore(v.n, next);
}
next = v.n;
}
};
// Positions (into a) of a longest strictly increasing subsequence, skipping -1.
const lis = (a) => {
const prev = new Int32Array(a.length), tails = [];
for (let i = 0; i < a.length; i++) {
const x = a[i];
if (x === -1) continue;
let lo = 0, hi = tails.length;
while (lo < hi) { const m = (lo + hi) >> 1; if (a[tails[m]] < x) lo = m + 1; else hi = m; }
prev[i] = lo > 0 ? tails[lo - 1] : -1;
tails[lo] = i;
}
const out = new Array(tails.length);
for (let k = tails.length - 1, i = tails[k]; k >= 0; k--, i = prev[i]) out[k] = i;
return out;
};
// ------------------------------------------------------------ render
let prev = null;
// opts.onRender(stats) runs after each patch with timings in ms:
// { start, update, view, patch, end, nodes }
// where start is the first dispatch since the previous render.
function render() {
queued = false;
const t0 = performance.now();
if (frameQ.length) {
const q = frameQ; frameQ = [];
for (let i = 0; i < q.length; i += 2) ex.update(q[i], q[i + 1]);
}
const t1 = performance.now();
const top = node("#root");
stack = []; cur = top; nodes = 0;
ex.view();
const t2 = performance.now();
if (prev === null) {
root.textContent = "";
for (const c of top.c) root.appendChild(create(c));
} else {
patchChildren(root, prev.c, top.c);
}
prev = top;
const t3 = performance.now();
const stats = { start: since || t0, update: tUpdate + (t1 - t0),
view: t2 - t1, patch: t3 - t2, end: t3, nodes };
since = 0; tUpdate = 0;
if (opts.onRender) opts.onRender(stats);
}
// ------------------------------------------------------------ events
const find = (t, kind) => {
for (let n = t; n && n !== root; n = n.parentNode) if (n.__ev && n.__ev[kind]) return n.__ev[kind];
return null;
};
const on = (type, kind, pre) =>
root.addEventListener(type, (e) => {
if (pre && !pre(e)) return;
const h = find(e.target, kind);
if (!h) return;
if (kind === "input") strs[EVENT] = e.target.value;
dispatch(h[0], h[1]);
});
on("click", "click");
on("dblclick", "dblclick");
on("input", "input");
on("keydown", "enter", (e) => e.key === "Enter" && !e.isComposing);
on("keydown", "escape", (e) => e.key === "Escape");
// Long press: hold a pointer still for 500 ms. The click that ends the press is
// swallowed, and the browser's own context menu is suppressed where a handler exists.
let press = null, pressed = false;
const unpress = () => { if (press) { clearTimeout(press.t); press = null; } };
root.addEventListener("pointerdown", (e) => {
pressed = false;
unpress();
if (e.button > 0) return;
const h = find(e.target, "longpress");
if (!h) return;
press = { x: e.clientX, y: e.clientY,
t: setTimeout(() => { press = null; pressed = true; dispatch(h[0], h[1]); }, 500) };
});
root.addEventListener("pointermove", (e) => {
if (press && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10) unpress();
});
for (const t of ["pointerup", "pointercancel", "pointerleave"]) root.addEventListener(t, unpress);
root.addEventListener("click", (e) => {
if (pressed) { pressed = false; e.stopImmediatePropagation(); e.preventDefault(); }
}, true);
root.addEventListener("contextmenu", (e) => { if (find(e.target, "longpress")) e.preventDefault(); });
// Run module-level code (which calls init()), then first render.
ex.__main__global_stmts();
render();
return { dispatch, render, exports: ex, strs, vals };
}