Rewrite the launcher in MoonBit (old code moves to legacy/) #1

Merged
nandi merged 9 commits from moonbit-rewrite into main 2026-11-23 01:57:10 +00:00
28 changed files with 4278 additions and 0 deletions
Showing only changes of commit 28e0284d9b - Show all commits

No files matched your search

+307
View File
@@ -0,0 +1,307 @@
///|
/// The launcher as an Elm-style program, pure: `Model`, `Msg`, `update` (returns the
/// `Effect`s for the platform to run) and `view` (returns a `vdom` tree). It ports
/// legacy/web/app.py, the LPython app, and the gesture handling that lived in its
/// index.html. Nothing here touches a platform: the web/ package runs the effects and
/// renders the tree, and the tests below drive the whole thing headlessly.
///|
pub(all) struct AppInfo {
label : String
component : String
icon : String
/// A system app: it has no Uninstall.
system : Bool
}
///|
pub(all) struct WidgetInfo {
label : String
provider : String
icon : String
/// The label of the app the widget comes from (for the picker's search).
app : String
/// Natural height in CSS px.
h : Int
}
///|
/// How a widget may be resized, in CSS px (the shell's `widgetLimits`): its natural
/// width, min/max size (0: no max), and whether it resizes horizontally / vertically.
pub(all) struct Limits {
w : Int
min_w : Int
min_h : Int
max_w : Int
max_h : Int
h : Bool
v : Bool
}
///|
pub let default_limits : Limits = {
w: 0,
min_w: 120,
min_h: 80,
max_w: 0,
max_h: 0,
h: true,
v: true,
}
///|
#derive(Eq, Debug)
pub(all) enum Sheet {
NoSheet
/// The menu of the empty home.
HomeMenu
/// The menu of a home slot.
Item(Int)
/// The menu of a drawer app (row in the app list).
DrawerApp(Int)
WidgetPicker
}
///|
#derive(Eq, Debug)
pub(all) enum Edge {
Right
Bottom
Corner
}
///|
/// A resize in progress: a handle was pressed on the widget whose box (px, viewport) was
/// at `left`, `top`.
pub(all) struct ResizeDrag {
edge : Edge
slot : Int
left : Double
top : Double
mut cols : Int
mut rows : Int
}
///|
/// Where the lifted slot was held, and the cell it was last sent to.
pub(all) struct Carry {
dx : Double
dy : Double
mut cell : Int
}
///|
pub(all) struct Model {
mut apps : Array[AppInfo]
mut loading : Bool
mut load_error : String
mut widgets : Array[WidgetInfo]
mut wloading : Bool
/// The home screen, in order.
mut home : Array[@grid.Slot]
mut next_key : Int
/// Grid columns, and rows that fill the screen (0 until the page has measured).
mut cols : Int
mut nrows : Int
/// Where the grid is on the screen (px, viewport) and how wide a column is.
mut grid_left : Double
mut grid_top : Double
mut col_w : Double
mut query : String
mut wquery : String
mut drawer : Bool
/// The drawer is in "add apps" mode: taps toggle home slots.
mut picking : Bool
mut sheet : Sheet
/// The package being uninstalled: its home slot goes when it leaves the app list.
mut gone : String
/// Home slot picked up by a long press, being dragged.
mut lifted : Int
/// Widget slot showing resize handles.
mut resizing : Int
/// The lifted slot was grabbed while showing handles: drop it back into them.
mut regrab : Bool
mut carry : Carry?
mut resize : ResizeDrag?
/// Native widget views report their drags through `NativeDrag`; where it began.
mut native_from : (Double, Double)?
/// Widget row being added.
mut chosen : Int
mut limits : Map[Int, Limits]
mut notice : String
mut notice_gen : Int
// ---- self-update
mut installed : Int
mut declined : Int
mut checking : Bool
mut manual_check : Bool
mut apk_url : String?
mut release_tag : String
/// The layout JSON last handed to `SaveHome`.
mut saved : String
/// A pointer drag (lift or resize) happened since the pointer went down: the swipe
/// check that follows the touch ignores it.
mut dragged : Bool
/// A widget just added whose limits will set its starting width.
mut fresh : Int
mut gesture : @gesture.State
}
///|
pub fn Model::new() -> Model {
{
apps: [],
loading: true,
load_error: "",
widgets: [],
wloading: false,
home: [],
next_key: 1,
cols: 5,
nrows: 0,
grid_left: 0.0,
grid_top: 0.0,
col_w: 0.0,
query: "",
wquery: "",
drawer: false,
picking: false,
sheet: NoSheet,
gone: "",
lifted: -1,
resizing: -1,
regrab: false,
carry: None,
resize: None,
native_from: None,
chosen: -1,
limits: {},
notice: "",
notice_gen: 0,
installed: 0,
declined: -1,
checking: false,
manual_check: false,
apk_url: None,
release_tag: "",
saved: "",
dragged: false,
fresh: -1,
gesture: @gesture.State::new(),
}
}
///|
/// The most slots the home screen holds.
pub let home_cap : Int = 200
///|
pub let app_cap : Int = 512
///|
#derive(Eq, Debug)
/// What a view node can send. Raw pointer input goes through `Input` and the gesture
/// recogniser first; everything else is a Msg a handler or the shell sends directly.
pub(all) enum Msg {
// ---- from the platform
/// Boot: the saved layout (this app's JSON, and the old WebView build's
/// `ultra.home.*` localStorage as a JSON object), the clock, and the self-update state.
Restore(saved~ : String?, legacy~ : String?)
Started(now~ : Int64, last_check~ : Int64, declined~ : Int, installed~ : Int)
/// The page measured itself: viewport size, and where the home grid is.
Measured(vw~ : Int, vh~ : Int, grid_left~ : Double, grid_top~ : Double, grid_w~ : Double, bottom_pad~ : Double)
AppsLoaded(String?)
WidgetsLoaded(String?)
/// The shell's answer to `QueryLimits`.
LimitsKnown(Int, String?)
/// A package changed: look at the app list again.
Reload
/// The Home button or intent.
GoHome
Back
WidgetAdded(Int)
/// A long press on a native widget view lifts its slot.
WidgetMenu(Int)
/// A press on the native view of the widget showing handles picks it up.
WidgetGrab(Int)
NativeDrag(Double, Double)
NativeDrop(Bool)
/// The swipe the page saw: dx, dy, ms, whether the home is scrolled to the top, and
/// whether the drawer's list is at its end.
Touch(dx~ : Double, dy~ : Double, ms~ : Int, home_top~ : Bool, list_end~ : Bool)
ReleaseFetched(String?)
VersionFetched(String?)
UpdateDeclined(Int)
NoticeDone(Int)
// ---- from handlers
Query(String)
Clear
WQuery(String)
WClear
OpenDrawer
CloseDrawer
OpenApp(Int)
OpenFirst
OpenHome(Int)
AddHome(Int)
ToggleHome(Int)
AppMenu(Int)
AppInfoOf(Int)
UninstallOf(Int)
Menu
CloseSheet
PickApps
PickWidget
ChooseWidget(Int)
ChooseFirstWidget
Remove(Int)
/// Swap the slot with the one before it.
MoveEarlier(Int)
InfoOf(Int)
Settings
Wallpaper
Recents
CheckUpdates
Lift(Int)
Grab(Int)
ResizeBegin(Edge)
ResizeDone
/// Does nothing; stands in a chain to stop a tap reaching an element below.
Nop
/// The recogniser saw a drag / the pointer lift (see `input`).
Dragged(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double)
Released(moved~ : Bool, held~ : Bool)
}
///|
#derive(Eq, Debug)
pub(all) enum Effect {
Launch(String)
AppInfo(String)
Uninstall(String)
AddWidget(String)
RemoveWidget(Int)
OpenSettings
PickWallpaper
OpenRecents
Haptic
/// Fetch apps.json / widgets.json and answer `AppsLoaded` / `WidgetsLoaded`.
LoadApps
LoadWidgets
/// Ask the shell for a widget's limits and answer `LimitsKnown`.
QueryLimits(Int)
SaveHome(String)
SaveLastCheck(Int64)
SaveDeclined(Int)
/// Send the message after this many ms.
Delay(Int, Msg)
/// After this many ms, feed `Hold(token)` to `input` (the long-press timer).
HoldTimer(Int, Int)
FetchRelease(String)
FetchVersion(String)
InstallApk(String, Int)
/// The drawer opened with its search in front: focus it and raise the keyboard.
FocusSearch
HideKeyboard
ScrollTop
}
+10
View File
@@ -0,0 +1,10 @@
import {
"experiments/launcher/grid",
"experiments/launcher/gesture",
"experiments/launcher/updater",
"experiments/launcher/vdom",
"experiments/launcher/jsonx",
"moonbitlang/core/json",
"moonbitlang/core/cmp",
"moonbitlang/core/string",
}
+175
View File
@@ -0,0 +1,175 @@
///|
/// The saved home layout as JSON:
/// `{"v":1,"slots":[{"kind":"app","str":COMPONENT,"x":-1,"y":-1},
/// {"kind":"widget","str":LABEL,"wid":ID,"w":COLS,"rows":ROWS,"x":-1,"y":-1}]}`.
pub fn save_json(home : Array[@grid.Slot]) -> String {
let slots : Array[Json] = home.map(fn(s) {
match s.kind {
App => { "kind": "app", "str": s.str, "x": s.x, "y": s.y }
Widget =>
{
"kind": "widget",
"str": s.str,
"wid": s.wid,
"w": s.w,
"rows": s.rows,
"x": s.x,
"y": s.y,
}
}
})
Json::object({ "v": 1, "slots": Json::array(slots) }).stringify()
}
///|
/// Read a saved layout; `None` if the text is not one. Slots without a name are
/// dropped, and no more than `home_cap` are kept.
pub fn load_json(text : String, next_key : Ref[Int]) -> Array[@grid.Slot]? {
guard @jsonx.parse(text) is Some(j) else { return None }
guard @jsonx.get(j, "slots") is Some(Array(_)) else { return None }
let out : Array[@grid.Slot] = []
for s in @jsonx.arr(j, "slots") {
let str = @jsonx.str(s, "str")
if str == "" || out.length() >= home_cap {
continue
}
let slot = if @jsonx.str(s, "kind") == "widget" {
@grid.Slot::widget(
str,
@jsonx.int(s, "wid"),
w=@cmp.maximum(0, @jsonx.int(s, "w")),
rows=@cmp.maximum(1, @jsonx.int(s, "rows", default=1)),
key=take_key(next_key),
)
} else {
@grid.Slot::app(str, key=take_key(next_key))
}
slot.x = @jsonx.int(s, "x", default=-1)
slot.y = @jsonx.int(s, "y", default=-1)
out.push(slot)
}
Some(out)
}
///|
fn take_key(next_key : Ref[Int]) -> Int {
let k = next_key.val
next_key.val = k + 1
k
}
///|
/// The WebView build kept its home in localStorage as `ultra.home.n` and, for slot i,
/// `ultra.home.{kind,str,wid,h,w,cx,cy}.i` (all strings; kind 1 is a widget, `h` its
/// height in px, `cx`/`cy` the pinned cell). `text` is those keys as a JSON object. Widget
/// heights in px become whole rows.
pub fn legacy_import(text : String, next_key : Ref[Int]) -> Array[@grid.Slot] {
guard @jsonx.parse(text) is Some(kv) else { return [] }
fn num(k : String, i : Int, d : Int) -> Int {
match @jsonx.get(kv, "ultra.home.\{k}.\{i}") {
Some(String(s)) =>
try @string.parse_int(s) catch {
_ => d
}
Some(Number(n, ..)) => n.to_int()
_ => d
}
}
let n = num2(kv, "ultra.home.n")
let out : Array[@grid.Slot] = []
for i in 0..<n {
let str = match @jsonx.get(kv, "ultra.home.str.\{i}") {
Some(String(s)) => s
_ => ""
}
if str == "" || out.length() >= home_cap {
continue
}
let slot = if num("kind", i, 0) == 1 {
@grid.Slot::widget(
str,
num("wid", i, 0),
w=@cmp.maximum(0, num("w", i, 0)),
rows=@grid.widget_rows(num("h", i, 120)),
key=take_key(next_key),
)
} else {
@grid.Slot::app(str, key=take_key(next_key))
}
slot.x = num("cx", i, -1)
slot.y = num("cy", i, -1)
out.push(slot)
}
out
}
///|
fn num2(kv : Json, key : String) -> Int {
match @jsonx.get(kv, key) {
Some(String(s)) =>
try @string.parse_int(s) catch {
_ => 0
}
Some(Number(n, ..)) => n.to_int()
_ => 0
}
}
///|
/// The apps.json the shell (or the demo) serves: `{"apps": [{"label", "component",
/// "icon", "system"}]}`, capped at `app_cap`.
pub fn parse_apps(text : String) -> Array[AppInfo]? {
guard @jsonx.parse(text) is Some(j) else { return None }
guard @jsonx.get(j, "apps") is Some(Array(_)) else { return None }
let out : Array[AppInfo] = []
for a in @jsonx.arr(j, "apps") {
if out.length() >= app_cap {
break
}
out.push({
label: @jsonx.str(a, "label"),
component: @jsonx.str(a, "component"),
icon: @jsonx.str(a, "icon"),
system: @jsonx.bool(a, "system"),
})
}
Some(out)
}
///|
/// widgets.json: `{"widgets": [{"label", "app", "provider", "icon", "h"}]}`.
pub fn parse_widgets(text : String) -> Array[WidgetInfo]? {
guard @jsonx.parse(text) is Some(j) else { return None }
guard @jsonx.get(j, "widgets") is Some(Array(_)) else { return None }
let out : Array[WidgetInfo] = []
for w in @jsonx.arr(j, "widgets") {
if out.length() >= 256 {
break
}
out.push({
label: @jsonx.str(w, "label"),
provider: @jsonx.str(w, "provider"),
icon: @jsonx.str(w, "icon"),
app: @jsonx.str(w, "app"),
h: @jsonx.int(w, "h"),
})
}
Some(out)
}
///|
/// The shell's `widgetLimits` JSON (`{"w","minW","minH","maxW","maxH","h","v"}`);
/// missing fields take the defaults.
pub fn parse_limits(text : String) -> Limits {
guard @jsonx.parse(text) is Some(j) else { return default_limits }
{
w: @jsonx.int(j, "w"),
min_w: @jsonx.int(j, "minW"),
min_h: @jsonx.int(j, "minH"),
max_w: @jsonx.int(j, "maxW"),
max_h: @jsonx.int(j, "maxH"),
h: @jsonx.bool(j, "h", default=true),
v: @jsonx.bool(j, "v", default=true),
}
}
+243
View File
@@ -0,0 +1,243 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/app"
import {
"experiments/launcher/gesture",
"experiments/launcher/grid",
"experiments/launcher/vdom",
"moonbitlang/core/debug",
"moonbitlang/core/ref",
}
// Values
pub let app_cap : Int32
pub let default_limits : Limits
pub fn handler_table(Array[@vdom.Node[Msg]]) -> Array[@vdom.Handlers[Msg]]
pub let home_cap : Int32
pub fn input(Model, Array[@vdom.Handlers[Msg]], @gesture.Input) -> Array[Effect]
pub fn key(Model, Array[@vdom.Handlers[Msg]], Array[Int32], Key) -> Array[Effect]
pub fn legacy_import(String, @ref.Ref[Int32]) -> Array[@grid.Slot]
pub fn load_json(String, @ref.Ref[Int32]) -> Array[@grid.Slot]?
pub fn matches_query(String, String) -> Bool
pub fn parse_apps(String) -> Array[AppInfo]?
pub fn parse_limits(String) -> Limits
pub fn parse_widgets(String) -> Array[WidgetInfo]?
pub fn save_json(Array[@grid.Slot]) -> String
pub fn typed(Model, Array[@vdom.Handlers[Msg]], Array[Int32], String) -> Array[Effect]
pub fn update(Model, Msg) -> Array[Effect]
pub fn view(Model) -> Array[@vdom.Node[Msg]]
// Errors
// Types and methods
pub(all) struct AppInfo {
label : String
component : String
icon : String
system : Bool
}
pub(all) struct Carry {
dx : Double
dy : Double
mut cell : Int32
}
#derive(Eq, @debug.Debug)
pub(all) enum Edge {
Right
Bottom
Corner
}
pub(all) enum Effect {
Launch(String)
AppInfo(String)
Uninstall(String)
AddWidget(String)
RemoveWidget(Int32)
OpenSettings
PickWallpaper
OpenRecents
Haptic
LoadApps
LoadWidgets
QueryLimits(Int32)
SaveHome(String)
SaveLastCheck(Int64)
SaveDeclined(Int32)
Delay(Int32, Msg)
HoldTimer(Int32, Int32)
FetchRelease(String)
FetchVersion(String)
InstallApk(String, Int32)
FocusSearch
HideKeyboard
ScrollTop
}
pub(all) enum Key {
Enter
Escape
}
pub(all) struct Limits {
w : Int32
min_w : Int32
min_h : Int32
max_w : Int32
max_h : Int32
h : Bool
v : Bool
}
pub(all) struct Model {
mut apps : Array[AppInfo]
mut loading : Bool
mut load_error : String
mut widgets : Array[WidgetInfo]
mut wloading : Bool
mut home : Array[@grid.Slot]
mut next_key : Int32
mut cols : Int32
mut nrows : Int32
mut grid_left : Double
mut grid_top : Double
mut col_w : Double
mut query : String
mut wquery : String
mut drawer : Bool
mut picking : Bool
mut sheet : Sheet
mut gone : String
mut lifted : Int32
mut resizing : Int32
mut regrab : Bool
mut carry : Carry?
mut resize : ResizeDrag?
mut native_from : (Double, Double)?
mut chosen : Int32
mut limits : Map[Int32, Limits]
mut notice : String
mut notice_gen : Int32
mut installed : Int32
mut declined : Int32
mut checking : Bool
mut manual_check : Bool
mut apk_url : String?
mut release_tag : String
mut saved : String
mut dragged : Bool
mut fresh : Int32
mut gesture : @gesture.State
}
pub fn Model::app_row(Self, String) -> Int32
pub fn Model::first_match(Self) -> Int32
pub fn Model::first_widget_match(Self) -> Int32
pub fn Model::hidden(Self, Int32) -> Bool
pub fn Model::home_of(Self, Int32) -> Int32
pub fn Model::new() -> Self
pub fn Model::packed(Self) -> @grid.Packed
pub fn Model::slot_of_widget(Self, Int32) -> Int32
pub fn Model::widget_matches(Self, Int32) -> Bool
pub(all) enum Msg {
Restore(saved~ : String?, legacy~ : String?)
Started(now~ : Int64, last_check~ : Int64, declined~ : Int32, installed~ : Int32)
Measured(vw~ : Int32, vh~ : Int32, grid_left~ : Double, grid_top~ : Double, grid_w~ : Double, bottom_pad~ : Double)
AppsLoaded(String?)
WidgetsLoaded(String?)
LimitsKnown(Int32, String?)
Reload
GoHome
Back
WidgetAdded(Int32)
WidgetMenu(Int32)
WidgetGrab(Int32)
NativeDrag(Double, Double)
NativeDrop(Bool)
Touch(dx~ : Double, dy~ : Double, ms~ : Int32, home_top~ : Bool, list_end~ : Bool)
ReleaseFetched(String?)
VersionFetched(String?)
UpdateDeclined(Int32)
NoticeDone(Int32)
Query(String)
Clear
WQuery(String)
WClear
OpenDrawer
CloseDrawer
OpenApp(Int32)
OpenFirst
OpenHome(Int32)
AddHome(Int32)
ToggleHome(Int32)
AppMenu(Int32)
AppInfoOf(Int32)
UninstallOf(Int32)
Menu
CloseSheet
PickApps
PickWidget
ChooseWidget(Int32)
ChooseFirstWidget
Remove(Int32)
MoveEarlier(Int32)
InfoOf(Int32)
Settings
Wallpaper
Recents
CheckUpdates
Lift(Int32)
Grab(Int32)
ResizeBegin(Edge)
ResizeDone
Nop
Dragged(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double)
Released(moved~ : Bool, held~ : Bool)
}
pub(all) struct ResizeDrag {
edge : Edge
slot : Int32
left : Double
top : Double
mut cols : Int32
mut rows : Int32
}
#derive(Eq, @debug.Debug)
pub(all) enum Sheet {
NoSheet
HomeMenu
Item(Int32)
DrawerApp(Int32)
WidgetPicker
}
pub(all) struct WidgetInfo {
label : String
provider : String
icon : String
app : String
h : Int32
}
// Type aliases
// Traits
+826
View File
@@ -0,0 +1,826 @@
///|
/// A headless harness: a model, its rendered tree, and pointer input aimed at elements
/// found by class and text, as the page would aim it.
///|
let apps_json : String =
#|{"apps":[
#|{"label":"Calculator","component":"c.calc/.Main","icon":"i1"},
#|{"label":"Calendar","component":"c.cal/.Main","icon":"i2"},
#|{"label":"Chrome","component":"c.chrome/.Main","icon":"i3"},
#|{"label":"Gmail","component":"c.gmail/.Main","icon":"i4"},
#|{"label":"Phone","component":"c.phone/.Main","icon":"i5","system":true},
#|{"label":"Weather","component":"c.weather/.Main","icon":"i6"}]}
///|
let widgets_json : String =
#|{"widgets":[
#|{"label":"Clock","app":"Clock","provider":"c.clock/.W","icon":"w1","h":140},
#|{"label":"Weather","app":"Google","provider":"c.google/.W","icon":"w2","h":120},
#|{"label":"Calendar","app":"Calendar","provider":"c.cal/.W","icon":"w3","h":200}]}
///|
struct Sim {
m : Model
mut tree : Array[@vdom.Node[Msg]]
mut table : Array[@vdom.Handlers[Msg]]
log : Array[Effect]
mut last_x : Double
mut last_y : Double
}
///|
fn Sim::new() -> Sim {
let m = Model::new()
let s = { m, tree: [], table: [], log: [], last_x: 0.0, last_y: 0.0 }
s.run(update(m, Restore(saved=None, legacy=None)))
s.send(Measured(vw=390, vh=800, grid_left=16.0, grid_top=150.0, grid_w=358.0, bottom_pad=24.0))
s.send(AppsLoaded(Some(apps_json)))
s
}
///|
fn Sim::refresh(self : Sim) -> Unit {
self.tree = view(self.m)
self.table = handler_table(self.tree)
}
///|
fn Sim::run(self : Sim, fx : Array[Effect]) -> Unit {
for e in fx {
self.log.push(e)
}
self.refresh()
}
///|
fn Sim::send(self : Sim, msg : Msg) -> Unit {
self.run(update(self.m, msg))
}
///|
fn text_of(n : @vdom.Node[Msg]) -> String {
match n {
Text(s) => s
El(e) => e.children.map(text_of).join("")
}
}
///|
/// The chain (handler numbers, innermost first) of the first element matching `pred`.
fn Sim::chain_where(
self : Sim,
pred : (@vdom.Element[Msg]) -> Bool,
from? : Int = 0,
) -> Array[Int]? {
let mut counter = 0
let mut found : Array[Int]? = None
let stack : Array[Int] = []
fn walk(n : @vdom.Node[Msg]) -> Unit {
if found is Some(_) {
return
}
if n is El(e) {
let has = !e.handlers.is_empty()
if has {
stack.push(counter)
counter += 1
}
if pred(e) {
found = Some(stack.rev())
return
}
for c in e.children {
walk(c)
}
if has {
ignore(stack.pop())
}
}
}
let mut top = 0
for n in self.tree {
if top < from {
walk_count(n, fn() { counter += 1 })
} else {
walk(n)
}
top += 1
}
found
}
///|
/// Count the handler-bearing elements below a node without matching (to keep numbering).
fn walk_count(n : @vdom.Node[Msg], bump : () -> Unit) -> Unit {
if n is El(e) {
if !e.handlers.is_empty() {
bump()
}
for c in e.children {
walk_count(c, bump)
}
}
}
///|
fn Sim::chain(
self : Sim,
class : String,
label? : String = "",
from? : Int = 0,
) -> Array[Int] {
match
self.chain_where(from~, fn(e) {
e.classes.contains(class) &&
(label == "" || text_of(El(e)).contains(label))
}) {
Some(c) => c
None => abort("no .\{class} \{label} in the tree")
}
}
///|
fn Sim::feed(self : Sim, inp : @gesture.Input) -> Unit {
self.run(input(self.m, self.table, inp))
}
///|
fn Sim::press(self : Sim, chain : Array[Int], x? : Double = 0.0, y? : Double = 0.0) -> Unit {
self.feed(Down(x~, y~, chain~))
self.last_x = x
self.last_y = y
}
///|
fn Sim::hold(self : Sim) -> Unit {
let mut token = -1
for e in self.log {
if e is HoldTimer(_, t) {
token = t
}
}
self.feed(Hold(token))
}
///|
fn Sim::move_to(self : Sim, x : Double, y : Double) -> Unit {
self.feed(Move(x~, y~))
self.last_x = x
self.last_y = y
}
///|
fn Sim::release(self : Sim) -> Unit {
self.feed(Up(x=self.last_x, y=self.last_y))
}
///|
fn Sim::tap(
self : Sim,
class : String,
label? : String = "",
from? : Int = 0,
) -> Unit {
self.press(self.chain(class, label~, from~))
self.release()
}
///|
fn Sim::long_press(self : Sim, chain : Array[Int], x? : Double = 0.0, y? : Double = 0.0) -> Unit {
self.press(chain, x~, y~)
self.hold()
self.release()
}
///|
fn Sim::home_names(self : Sim) -> Array[String] {
self.m.home.map(fn(s) {
if s.kind == Widget {
"[" + s.str + "]"
} else {
self.m.apps[self.m.app_row(s.str)].label
}
})
}
///|
/// The sheet (dialog) as HTML.
fn Sim::sheet_html(self : Sim) -> String {
for n in self.tree {
if n is El(e) && e.classes.contains("sheet") {
return @vdom.to_html(n)
}
}
""
}
///|
fn Sim::has_effect(self : Sim, e : Effect) -> Bool {
self.log.contains(e)
}
///|
/// Centre of the cell (col, row) in viewport px.
fn cell_center(col : Int, row : Int) -> (Double, Double) {
(
16.0 + col.to_double() * (65.2 + 8.0) + 32.6,
150.0 + row.to_double() * 72.0 + 32.0,
)
}
///|
/// Add apps to the home screen through the long-press menu and the drawer's pick mode.
fn Sim::add_apps(self : Sim, labels : Array[String]) -> Unit {
self.long_press(self.chain("home"))
self.tap("sheet-item", label="Add apps")
for l in labels {
self.tap("tile", label=l, from=1) // the drawer's, not the home screen's under it
}
self.tap("btn", label="Done")
}
///|
test "boot: blank home with a hint, apps load" {
let s = Sim::new()
assert_true(s.has_effect(LoadApps))
assert_eq(s.m.apps.length(), 6)
assert_eq(s.m.home.length(), 0)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("Swipe down for all apps"))
}
///|
test "long press on the blank home opens the menu; Check for updates closes it" {
let s = Sim::new()
s.long_press(s.chain("home"))
assert_eq(s.m.sheet, HomeMenu)
assert_true(s.has_effect(Haptic))
s.tap("sheet-item", label="Check for updates")
assert_eq(s.m.sheet, NoSheet)
assert_true(s.has_effect(FetchRelease(@updater.release_api)))
assert_eq(s.m.notice, "Checking for updates…")
}
///|
test "add apps through the drawer's pick mode" {
let s = Sim::new()
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Add apps")
assert_true(s.m.drawer && s.m.picking)
assert_true(!s.has_effect(FocusSearch)) // picking is for scrolling: no keyboard
s.tap("tile", label="Chrome", from=1)
s.tap("tile", label="Gmail", from=1)
s.tap("tile", label="Phone", from=1)
s.tap("tile", label="Gmail", from=1) // toggled off again
s.tap("btn", label="Done")
assert_true(!s.m.drawer)
assert_eq(s.home_names(), ["Chrome", "Phone"])
}
///|
test "swipe down opens the drawer, swipe up closes it" {
let s = Sim::new()
s.send(Touch(dx=3.0, dy=120.0, ms=200, home_top=true, list_end=false))
assert_true(s.m.drawer)
assert_true(s.has_effect(FocusSearch))
s.send(Touch(dx=3.0, dy=-120.0, ms=200, home_top=false, list_end=false))
assert_true(s.m.drawer) // the list isn't at its end yet
s.send(Touch(dx=3.0, dy=-120.0, ms=200, home_top=false, list_end=true))
assert_true(!s.m.drawer)
assert_true(s.has_effect(HideKeyboard))
s.send(Touch(dx=3.0, dy=40.0, ms=200, home_top=true, list_end=false))
assert_true(!s.m.drawer) // too short
}
///|
test "the home search pill opens the drawer" {
let s = Sim::new()
s.tap("search-pill")
assert_true(s.m.drawer && !s.m.picking)
assert_true(s.has_effect(FocusSearch))
}
///|
test "search filters the drawer; Enter opens the first match" {
let s = Sim::new()
s.send(OpenDrawer)
let names = fn() {
let out : Array[String] = []
for n in s.tree {
ignore(n)
}
for a in s.m.apps {
if matches_query(a.label, s.m.query) {
out.push(a.label)
}
}
out
}
assert_eq(names().length(), 6)
let input_chain = s.chain("input")
s.run(typed(s.m, s.table, input_chain, "ca"))
assert_eq(names(), ["Calculator", "Calendar", "Camera".to_string()].filter(fn(x) { x != "Camera" }))
s.run(typed(s.m, s.table, input_chain, " CAL"))
assert_eq(names(), ["Calculator", "Calendar"])
s.run(key(s.m, s.table, input_chain, Enter))
assert_true(s.has_effect(Launch("c.calc/.Main")))
assert_true(!s.m.drawer)
assert_eq(s.m.query, "")
}
///|
test "Enter with no search text or no match opens nothing" {
let s = Sim::new()
s.send(OpenDrawer)
let c = s.chain("input")
s.run(key(s.m, s.table, c, Enter))
assert_true(s.m.drawer)
s.run(typed(s.m, s.table, c, "zzz"))
s.run(key(s.m, s.table, c, Enter))
assert_true(s.m.drawer)
assert_true(@vdom.to_html(s.tree[1]).contains("No apps match."))
s.run(key(s.m, s.table, c, Escape))
assert_eq(s.m.query, "")
}
///|
test "tapping an app in the drawer launches it" {
let s = Sim::new()
s.send(OpenDrawer)
s.tap("tile", label="Gmail", from=1)
assert_true(s.has_effect(Launch("c.gmail/.Main")))
assert_true(!s.m.drawer)
}
///|
test "long press on a drawer app: menu; system apps have no uninstall" {
let s = Sim::new()
s.send(OpenDrawer)
s.long_press(s.chain("tile", label="Gmail", from=1))
assert_eq(s.m.sheet, DrawerApp(3))
let html = s.sheet_html()
assert_true(html.contains("Add to home"))
assert_true(html.contains("App info"))
assert_true(html.contains("Uninstall"))
s.tap("sheet-item", label="Add to home")
assert_eq(s.home_names(), ["Gmail"])
s.long_press(s.chain("tile", label="Phone", from=1))
assert_true(!s.sheet_html().contains("Uninstall"))
s.tap("sheet-overlay")
assert_eq(s.m.sheet, NoSheet)
s.long_press(s.chain("tile", label="Gmail", from=1))
assert_true(s.sheet_html().contains("Remove from home"))
}
///|
test "uninstall asks the shell; the slot goes when the app leaves the list" {
let s = Sim::new()
s.add_apps(["Gmail"])
s.send(OpenDrawer)
s.long_press(s.chain("tile", label="Gmail", from=1))
s.tap("sheet-item", label="Uninstall")
assert_true(s.has_effect(Uninstall("c.gmail/.Main")))
assert_eq(s.home_names(), ["Gmail"])
s.send(AppsLoaded(Some("{\"apps\":[{\"label\":\"Chrome\",\"component\":\"c.chrome/.Main\",\"icon\":\"\"}]}")))
assert_eq(s.m.home.length(), 0)
}
///|
test "home slots: tap launches, long press without moving opens the menu" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail", "Phone"])
s.tap("tile", label="Gmail")
assert_true(s.has_effect(Launch("c.gmail/.Main")))
s.long_press(s.chain("tile", label="Gmail"))
assert_eq(s.m.sheet, Item(1))
s.tap("sheet-item", label="Move earlier")
assert_eq(s.home_names(), ["Gmail", "Chrome", "Phone"])
s.long_press(s.chain("tile", label="Gmail"))
s.tap("sheet-item", label="Move later")
assert_eq(s.home_names(), ["Chrome", "Gmail", "Phone"])
s.long_press(s.chain("tile", label="Chrome"))
assert_true(!s.sheet_html().contains("Move earlier"))
s.tap("sheet-item", label="Remove from home")
assert_eq(s.home_names(), ["Gmail", "Phone"])
}
///|
test "dragging a home app over another reorders; a drag does not open the menu" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail", "Phone"])
let (ax, ay) = cell_center(1, 0)
let (bx, by) = cell_center(0, 0)
s.press(s.chain("tile", label="Gmail"), x=ax, y=ay)
s.hold()
assert_eq(s.m.lifted, 1)
s.move_to(bx + 5.0, by)
s.move_to(bx, by)
s.release()
assert_eq(s.home_names(), ["Gmail", "Chrome", "Phone"])
assert_eq(s.m.sheet, NoSheet)
assert_eq(s.m.lifted, -1)
}
///|
test "an app dropped in an empty cell stays there; the rest stay packed" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail", "Phone"])
let (px, py) = cell_center(2, 0)
let (tx, ty) = cell_center(3, 2)
s.press(s.chain("tile", label="Phone"), x=px, y=py)
s.hold()
s.move_to(tx - 30.0, ty)
s.move_to(tx, ty)
s.release()
assert_eq(s.home_names(), ["Chrome", "Gmail", "Phone"])
assert_eq((s.m.home[2].x, s.m.home[2].y), (3, 2))
let cells = s.m.packed().cells
assert_eq(cells[0], Some({ col: 0, row: 0, w: 1, h: 1 }))
assert_eq(cells[2], Some({ col: 3, row: 2, w: 1, h: 1 }))
// and it survives a save and a load
let back = load_json(save_json(s.m.home), Ref::new(1)).unwrap()
assert_eq((back[2].x, back[2].y), (3, 2))
}
///|
test "dropping a pinned app onto another pinned one moves that one on" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail"])
for (label, col, row) in [("Chrome", 3, 1), ("Gmail", 3, 3)] {
let from = cell_center(0, 0) // Gmail flows up into the first cell once Chrome is pinned
let (fx, fy) = from
let (tx, ty) = cell_center(col, row)
s.press(s.chain("tile", label=label), x=fx, y=fy)
s.hold()
s.move_to(tx, ty)
s.release()
}
assert_eq((s.m.home[0].x, s.m.home[0].y), (3, 1))
assert_eq((s.m.home[1].x, s.m.home[1].y), (3, 3))
// drag Gmail on top of Chrome's cell: Chrome is unpinned
let (gx, gy) = cell_center(3, 3)
let (cx, cy) = cell_center(3, 2) // a free cell next to it
s.press(s.chain("tile", label="Gmail"), x=gx, y=gy)
s.hold()
s.move_to(cx, cy)
s.release()
assert_eq((s.m.home[1].x, s.m.home[1].y), (3, 2))
}
///|
test "add a widget: picker search, choose, shell adds it" {
let s = Sim::new()
s.add_apps(["Chrome"])
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Add widget")
assert_true(s.has_effect(LoadWidgets))
assert_true(s.sheet_html().contains("Loading widgets"))
s.send(WidgetsLoaded(Some(widgets_json)))
let names = fn() {
let out : Array[String] = []
for i in 0..<s.m.widgets.length() {
if s.m.widget_matches(i) {
out.push(s.m.widgets[i].label)
}
}
out
}
let c = s.chain("widget-search")
s.run(typed(s.m, s.table, c, "cal"))
assert_eq(names(), ["Calendar"])
s.run(typed(s.m, s.table, c, "goo"))
assert_eq(names(), ["Weather"]) // by the app it comes from
s.run(typed(s.m, s.table, c, "zzz"))
assert_true(s.sheet_html().contains("No widgets match."))
s.run(typed(s.m, s.table, c, ""))
s.press(s.chain_where(fn(e) { e.tag == "li" && text_of(El(e)).contains("Clock") }).unwrap())
s.release()
assert_true(s.has_effect(AddWidget("c.clock/.W")))
s.send(WidgetAdded(100))
assert_eq(s.home_names(), ["Chrome", "[Clock]"])
assert_eq(s.m.home[1].wid, 100)
assert_eq(s.m.home[1].rows, 2) // 140px: two rows
assert_true(s.has_effect(QueryLimits(100)))
// its natural width sets the starting columns: 110px wide = 2 columns
s.send(LimitsKnown(100, Some("{\"w\":110,\"minW\":110,\"minH\":80,\"h\":true,\"v\":true}")))
assert_eq(s.m.home[1].w, 2)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("data-wid=\"100\""))
assert_true(html.contains("widget-slot"))
}
///|
test "widget picker Enter chooses the first match" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
let c = s.chain("widget-search")
s.run(typed(s.m, s.table, c, "cal"))
s.run(key(s.m, s.table, c, Enter))
assert_true(s.has_effect(AddWidget("c.cal/.W")))
assert_eq(s.m.sheet, NoSheet)
}
///|
test "a widget: hold opens resize handles; drag the handles; Done" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(100))
s.send(LimitsKnown(100, Some("{\"w\":0,\"minW\":64,\"minH\":64,\"h\":true,\"v\":true}")))
assert_eq(s.m.home[0].w, 0)
let (wx, wy) = cell_center(2, 0)
s.long_press(s.chain("widget-slot"), x=wx, y=wy)
assert_eq(s.m.resizing, 0) // no item menu for a widget: handles
assert_eq(s.m.sheet, NoSheet)
let html = @vdom.to_html(s.tree[0])
assert_true(html.contains("resize-handle"))
assert_true(@vdom.to_html(s.tree[1]).contains("Drag to move, or drag the handles to resize"))
// drag the bottom handle down to the fourth row
let hc = s.chain_where(fn(e) { e.attrs.contains(("data-edge", "b")) }).unwrap()
s.press(hc, x=100.0, y=150.0 + 2.0 * 72.0 + 70.0)
assert_true(s.has_effect(QueryLimits(100)))
s.move_to(100.0, 150.0 + 3.0 * 72.0 + 40.0)
s.release()
assert_eq(s.m.home[0].rows, 4)
assert_eq(s.m.resizing, 0) // handles stay
// the right handle to three columns (the widget starts the full row)
let rc = s.chain_where(fn(e) { e.attrs.contains(("data-edge", "r")) }).unwrap()
s.press(rc, x=370.0, y=170.0)
let (c3x, _) = cell_center(2, 0)
s.move_to(c3x + 36.0, 170.0)
s.release()
assert_eq(s.m.home[0].w, 3)
// pressing the widget's body picks it up at once; letting go keeps the handles
let wc = s.chain("widget-slot")
s.press(wc, x=wx, y=wy)
assert_eq(s.m.lifted, 0)
s.release()
assert_eq(s.m.resizing, 0)
assert_eq(s.m.lifted, -1)
// Done (a tap on the bar's button) ends it
s.tap("btn", label="Done")
assert_eq(s.m.resizing, -1)
assert_eq(s.m.home[0].w, 3)
}
///|
test "resizing stays within the widget's limits" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(100))
s.send(LimitsKnown(100, Some("{\"w\":0,\"minW\":200,\"maxW\":220,\"minH\":64,\"h\":true,\"v\":false}")))
let (wx, wy) = cell_center(2, 0)
s.long_press(s.chain("widget-slot"), x=wx, y=wy)
let rc = s.chain_where(fn(e) { e.attrs.contains(("data-edge", "rb")) }).unwrap()
s.press(rc, x=370.0, y=250.0)
s.move_to(60.0, 600.0) // far left and down
s.release()
assert_eq(s.m.home[0].w, 3) // 3 columns = 204px, the nearest to 200 within the limit
assert_eq(s.m.home[0].rows, 2) // vertical resizing is off
}
///|
test "a native widget view lifts, drags and drops its slot" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(2))
s.send(WidgetAdded(7))
s.send(LimitsKnown(7, Some("{\"w\":130,\"minW\":64,\"minH\":64,\"h\":true,\"v\":true}")))
assert_eq(s.m.home[0].w, 2)
s.send(WidgetMenu(7))
assert_eq(s.m.lifted, 0)
let (x, y) = cell_center(1, 0)
s.send(NativeDrag(x, y))
let (tx, ty) = cell_center(2, 3)
s.send(NativeDrag(tx, ty))
s.send(NativeDrop(true))
assert_eq(s.m.lifted, -1)
assert_eq(s.m.sheet, NoSheet)
assert_eq((s.m.home[0].x, s.m.home[0].y), (1, 3)) // it moved by the finger's travel
// lifting and letting go without moving shows the handles
s.send(WidgetMenu(7))
s.send(NativeDrop(false))
assert_eq(s.m.resizing, 0)
// a press on the native view while handles show picks it up
s.send(WidgetGrab(7))
assert_eq(s.m.lifted, 0)
s.send(NativeDrop(false))
assert_eq(s.m.resizing, 0)
}
///|
test "widgets and apps drawn under a sheet or the drawer are not live" {
let s = Sim::new()
s.send(PickWidget)
s.send(WidgetsLoaded(Some(widgets_json)))
s.send(ChooseWidget(0))
s.send(WidgetAdded(5))
assert_true(@vdom.to_html(s.tree[0]).contains("data-wid=\"5\""))
s.send(OpenDrawer)
assert_true(!@vdom.to_html(s.tree[0]).contains("data-wid"))
}
///|
test "back and home close things from the top down" {
let s = Sim::new()
s.send(OpenDrawer)
s.long_press(s.chain("tile", label="Gmail", from=1))
assert_eq(s.m.sheet, DrawerApp(3))
s.send(Back)
assert_eq(s.m.sheet, NoSheet)
assert_true(s.m.drawer)
s.send(Back)
assert_true(!s.m.drawer)
s.send(OpenDrawer)
s.send(GoHome)
assert_true(!s.m.drawer)
assert_true(s.has_effect(ScrollTop))
}
///|
test "the layout is saved on every change and restored" {
let s = Sim::new()
s.add_apps(["Chrome", "Gmail"])
let mut saved = ""
for e in s.log {
if e is SaveHome(j) {
saved = j
}
}
assert_eq(saved, save_json(s.m.home))
let s2 = Sim::new()
s2.run(update(s2.m, Restore(saved=Some(saved), legacy=None)))
assert_eq(s2.home_names(), ["Chrome", "Gmail"])
// restoring what is already saved doesn't save it again
let n = s2.log.filter(fn(e) { e is SaveHome(_) }).length() - 1 // Sim::new saved the empty one
assert_eq(n, 0)
}
///|
test "the old WebView build's home screen is brought over once" {
let legacy =
#|{"ultra.home.n":"3",
#|"ultra.home.kind.0":"0","ultra.home.str.0":"c.chrome/.Main","ultra.home.cx.0":"-1","ultra.home.cy.0":"-1",
#|"ultra.home.kind.1":"1","ultra.home.str.1":"Clock","ultra.home.wid.1":"12","ultra.home.h.1":"136",
#|"ultra.home.w.1":"3","ultra.home.cx.1":"1","ultra.home.cy.1":"2",
#|"ultra.home.kind.2":"0"}
let next = Ref::new(1)
let slots = legacy_import(legacy, next)
assert_eq(slots.length(), 2)
assert_eq((slots[0].kind, slots[0].str), (App, "c.chrome/.Main"))
assert_eq((slots[1].wid, slots[1].w, slots[1].rows, slots[1].x, slots[1].y), (12, 3, 2, 1, 2))
assert_eq(legacy_import("{}", Ref::new(1)).length(), 0)
assert_eq(legacy_import("garbage", Ref::new(1)).length(), 0)
let s = Sim::new()
s.run(update(s.m, Restore(saved=None, legacy=Some(legacy))))
assert_eq(s.m.home.length(), 2)
assert_true(s.log.contains(SaveHome(save_json(s.m.home)))) // saved in the new format
// a saved layout wins over the old one
let s2 = Sim::new()
s2.run(update(s2.m, Restore(saved=Some(save_json([slot_app("c.gmail/.Main")])), legacy=Some(legacy))))
assert_eq(s2.m.home.length(), 1)
}
///|
fn slot_app(c : String) -> @grid.Slot {
@grid.Slot::app(c)
}
///|
test "load_json rejects what is not a layout and drops nameless slots" {
assert_true(load_json("nope", Ref::new(1)) is None)
assert_true(load_json("{}", Ref::new(1)) is None)
let r = load_json("{\"slots\":[{\"kind\":\"app\"},{\"kind\":\"app\",\"str\":\"a\"}]}", Ref::new(1)).unwrap()
assert_eq(r.length(), 1)
}
///|
test "self-update: automatic check, newer build, install" {
let s = Sim::new()
s.send(Started(now=100000000L, last_check=0L, declined=-1, installed=10))
assert_true(s.has_effect(SaveLastCheck(100000000L)))
assert_true(s.has_effect(FetchRelease(@updater.release_api)))
s.send(
ReleaseFetched(
Some(
"{\"tag_name\":\"build-12\",\"assets\":[{\"name\":\"version.json\",\"browser_download_url\":\"u/v\"},{\"name\":\"ultra-launcher.apk\",\"browser_download_url\":\"u/a\"}]}",
),
),
)
assert_true(s.has_effect(FetchVersion("u/v")))
s.send(VersionFetched(Some("{\"versionCode\":12}")))
assert_true(s.has_effect(InstallApk("u/a", 12)))
assert_eq(s.m.notice, "Downloading launcher update (build 12)…")
assert_true(!s.m.checking)
}
///|
test "self-update: up to date is silent unless asked; declined builds are not offered" {
let rel =
#|{"tag_name":"build-10","assets":[{"name":"version.json","browser_download_url":"u/v"},{"name":"ultra-launcher.apk","browser_download_url":"u/a"}]}
let s = Sim::new()
s.send(Started(now=100000000L, last_check=0L, declined=-1, installed=10))
s.send(ReleaseFetched(Some(rel)))
s.send(VersionFetched(Some("{\"versionCode\":10}")))
assert_eq(s.m.notice, "")
assert_true(s.log.filter(fn(e) { e is InstallApk(_, _) }).length() == 0)
// manual says so
s.send(CheckUpdates)
s.send(ReleaseFetched(Some(rel)))
s.send(VersionFetched(Some("{\"versionCode\":10}")))
assert_eq(s.m.notice, "ultra Home is up to date (build 10)")
// a declined build: silent for automatic checks, offered again when asked
let s2 = Sim::new()
s2.send(Started(now=100000000L, last_check=0L, declined=11, installed=10))
s2.send(ReleaseFetched(Some(rel)))
s2.send(VersionFetched(Some("{\"versionCode\":11}")))
assert_true(s2.log.filter(fn(e) { e is InstallApk(_, _) }).length() == 0)
s2.send(CheckUpdates)
s2.send(ReleaseFetched(Some(rel)))
s2.send(VersionFetched(Some("{\"versionCode\":11}")))
assert_true(s2.has_effect(InstallApk("u/a", 11)))
s2.send(UpdateDeclined(11))
assert_true(s2.has_effect(SaveDeclined(11)))
}
///|
test "self-update: recent check is skipped; failures and the tag fallback" {
let s = Sim::new()
s.send(Started(now=1000L, last_check=900L, declined=-1, installed=10))
assert_true(!s.has_effect(FetchRelease(@updater.release_api)))
s.send(CheckUpdates)
s.send(CheckUpdates) // already checking
assert_eq(s.m.notice, "Already checking for updates")
s.send(ReleaseFetched(None))
assert_eq(s.m.notice, "Couldn't check for updates")
assert_true(!s.m.checking)
// version.json unreadable: the release tag says the build number
s.send(CheckUpdates)
s.send(
ReleaseFetched(
Some(
"{\"tag_name\":\"build-20\",\"assets\":[{\"name\":\"version.json\",\"browser_download_url\":\"u/v\"},{\"name\":\"ultra-launcher.apk\",\"browser_download_url\":\"u/a\"}]}",
),
),
)
s.send(VersionFetched(None))
assert_true(s.has_effect(InstallApk("u/a", 20)))
}
///|
test "menu items reach the shell" {
let s = Sim::new()
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Wallpaper")
assert_true(s.has_effect(PickWallpaper))
s.long_press(s.chain("home"))
s.tap("sheet-item", label="Settings")
assert_true(s.has_effect(OpenSettings))
s.tap("panel-btn")
assert_true(s.has_effect(OpenRecents))
}
///|
test "app info for a home slot" {
let s = Sim::new()
s.add_apps(["Chrome"])
s.long_press(s.chain("tile", label="Chrome"))
s.tap("sheet-item", label="App info")
assert_true(s.has_effect(AppInfo("c.chrome/.Main")))
}
///|
test "view snapshot: home with an app" {
let s = Sim::new()
s.add_apps(["Chrome"])
inspect(
@vdom.to_html(s.tree[0]),
content=(
#|<div class="home" on="press">
#| <section class="panel" aria-label="Shortcuts">
#| <button class="panel-btn" on="tap">
#| <span class="windows-glyph" aria-hidden="true"></span>
#| <span>Windows</span>
#| </button>
#| </section>
#| <button class="search-pill" aria-label="Search apps" on="tap">
#| <span class="magnifier" aria-hidden="true"></span>
#| <span>Search apps</span>
#| </button>
#| <ul class="slots" style="grid-template-columns:repeat(5,minmax(0,1fr));grid-template-rows:repeat(8,64px)">
#| <li class="tile" data-slot="0" style="grid-column:1 / span 1;grid-row:1 / span 1" on="tap press">
#| <img class="icon" alt="" draggable="false" data-icon="i3"></img>
#| <span class="name">Chrome</span>
#| </li>
#| </ul>
#|</div>
),
)
}
+795
View File
@@ -0,0 +1,795 @@
///|
fn trimmed(s : String) -> String {
s.trim().to_string()
}
///|
/// The lower-cased, trimmed search text matches the label.
pub fn matches_query(label : String, query : String) -> Bool {
let q = trimmed(query).to_lower()
q == "" || label.to_lower().contains(q)
}
///|
pub fn Model::app_row(self : Model, component : String) -> Int {
for i in 0..<self.apps.length() {
if self.apps[i].component == component {
return i
}
}
-1
}
///|
/// The home slot holding the app at `row` in the app list, or -1.
pub fn Model::home_of(self : Model, row : Int) -> Int {
let comp = self.apps[row].component
for i in 0..<self.home.length() {
if self.home[i].kind == App && self.home[i].str == comp {
return i
}
}
-1
}
///|
pub fn Model::slot_of_widget(self : Model, wid : Int) -> Int {
for i in 0..<self.home.length() {
if self.home[i].kind == Widget && self.home[i].wid == wid {
return i
}
}
-1
}
///|
/// The first app (row in the list) whose label matches the search.
pub fn Model::first_match(self : Model) -> Int {
for i in 0..<self.apps.length() {
if matches_query(self.apps[i].label, self.query) {
return i
}
}
-1
}
///|
pub fn Model::widget_matches(self : Model, i : Int) -> Bool {
matches_query(self.widgets[i].label, self.wquery) ||
matches_query(self.widgets[i].app, self.wquery) && trimmed(self.wquery) != ""
}
///|
pub fn Model::first_widget_match(self : Model) -> Int {
for i in 0..<self.widgets.length() {
if self.widget_matches(i) {
return i
}
}
-1
}
///|
/// Home slots that are not drawn: apps that are not installed.
pub fn Model::hidden(self : Model, i : Int) -> Bool {
self.home[i].kind == App && self.app_row(self.home[i].str) < 0
}
///|
pub fn Model::packed(self : Model) -> @grid.Packed {
@grid.pack(self.home, self.cols, self.nrows, hidden=fn(i) { self.hidden(i) })
}
///|
fn Model::say(self : Model, text : String, fx : Array[Effect]) -> Unit {
self.notice = text
self.notice_gen += 1
fx.push(Delay(1800, NoticeDone(self.notice_gen)))
}
///|
fn Model::push_slot(self : Model, s : @grid.Slot) -> Unit {
self.home.push(s)
}
///|
fn Model::new_key(self : Model) -> Int {
let k = self.next_key
self.next_key += 1
k
}
///|
fn Model::remove_slot(self : Model, at : Int, fx : Array[Effect]) -> Unit {
if at < 0 || at >= self.home.length() {
return
}
if self.home[at].kind == Widget {
fx.push(RemoveWidget(self.home[at].wid))
}
ignore(self.home.remove(at))
if self.lifted == at {
self.lifted = -1
} else if self.lifted > at {
self.lifted -= 1
}
if self.resizing == at {
self.resizing = -1
} else if self.resizing > at {
self.resizing -= 1
}
}
///|
fn Model::add_app(self : Model, row : Int, fx : Array[Effect]) -> Unit {
if self.home_of(row) >= 0 {
self.say("Already on the home screen", fx)
} else if self.home.length() >= home_cap {
self.say("The home screen is full", fx)
} else {
self.push_slot(@grid.Slot::app(self.apps[row].component, key=self.new_key()))
self.say("Added to home", fx)
}
}
///|
/// Once an app uninstalled from the drawer is out of the list, take it off home.
fn Model::drop_gone(self : Model, fx : Array[Effect]) -> Unit {
if self.gone == "" {
return
}
if self.app_row(self.gone) >= 0 {
return
}
for i in 0..<self.home.length() {
if self.home[i].kind == App && self.home[i].str == self.gone {
self.remove_slot(i, fx)
break
}
}
self.gone = ""
}
///|
fn Model::close_all(self : Model, fx : Array[Effect]) -> Unit {
if self.drawer {
fx.push(HideKeyboard)
}
self.query = ""
self.drawer = false
self.picking = false
self.sheet = NoSheet
self.lifted = -1
self.resizing = -1
self.regrab = false
self.carry = None
self.resize = None
}
///|
fn Model::open_drawer(self : Model, fx : Array[Effect]) -> Unit {
if self.sheet == NoSheet && !self.drawer {
self.drawer = true
fx.push(FocusSearch)
}
}
///|
fn Model::close_drawer(self : Model, fx : Array[Effect]) -> Unit {
if self.drawer && self.sheet == NoSheet {
self.drawer = false
self.picking = false
self.query = ""
fx.push(HideKeyboard)
}
}
// ---- dragging -----------------------------------------------------------------
///|
/// The box (px, viewport) of slot `i`, from the packing.
fn Model::slot_box(
self : Model,
packed : @grid.Packed,
i : Int,
) -> (Double, Double, Double, Double)? {
match packed.cells[i] {
Some(c) => {
let (x, y, w, h) = @grid.box(c, self.col_w)
Some((x + self.grid_left, y + self.grid_top, w, h))
}
None => None
}
}
///|
fn inside(b : (Double, Double, Double, Double), x : Double, y : Double) -> Bool {
x >= b.0 && x <= b.0 + b.2 && y >= b.1 && y <= b.1 + b.3
}
///|
/// The slot (not the lifted one) under a point, or -1.
fn Model::slot_at(self : Model, packed : @grid.Packed, x : Double, y : Double) -> Int {
for i in 0..<self.home.length() {
if i == self.lifted {
continue
}
if self.slot_box(packed, i) is Some(b) && inside(b, x, y) {
return i
}
}
-1
}
///|
/// The pointer is at x, y with a slot lifted (it went down at x0, y0). An app over
/// another slot takes its place in the order; over an empty cell it is left in that cell.
/// A widget goes to the cell under it wherever that is (apps flow around it).
fn Model::drag_lifted(
self : Model,
x : Double,
y : Double,
x0 : Double,
y0 : Double,
) -> Unit {
if self.lifted < 0 || self.lifted >= self.home.length() || self.col_w <= 0.0 {
return
}
let packed = self.packed()
let lifted = self.home[self.lifted]
let carry = match self.carry {
Some(c) => c
None => {
let (bx, by) = match self.slot_box(packed, self.lifted) {
Some(b) => (b.0, b.1)
None => (x0, y0)
}
let c = { dx: x0 - bx, dy: y0 - by, cell: -1 }
self.carry = Some(c)
c
}
}
let widget = lifted.kind == Widget
if !widget &&
self.slot_box(packed, self.lifted) is Some(b) &&
inside(b, x, y) {
return
}
let half_w = self.col_w / 2.0
let half_h = @grid.cell_px.to_double() / 2.0
let (fc, fr) = @grid.cell_at(
x - self.grid_left - half_w,
y - self.grid_top - half_h,
self.col_w,
)
let mut to = self.slot_at(packed, x, y)
if to < 0 {
let cx = self.grid_left + fc.to_double() * (self.col_w + @grid.col_gap.to_double()) + half_w
let cy = self.grid_top +
fr.to_double() * (@grid.cell_px + @grid.row_gap).to_double() +
half_h
to = self.slot_at(packed, cx, cy)
}
if to >= 0 && !widget {
carry.cell = -1
lifted.x = -1 // back into the flow, at that place in the order
lifted.y = -1
@grid.move_slot(self.home, self.lifted, to)
self.lifted = to
return
}
let grid_bottom = self.grid_top +
(packed.rows * (@grid.cell_px + @grid.row_gap)).to_double()
if y > grid_bottom {
return // below the grid
}
let (col, row) = @grid.cell_at(
x - self.grid_left - carry.dx,
y - self.grid_top - carry.dy,
self.col_w,
)
let cell = row * 64 + @cmp.minimum(col, 63)
if cell != carry.cell {
carry.cell = cell
@grid.pin(self.home, self.lifted, col, row, self.cols, self.nrows)
}
}
///|
/// The pointer is up. Letting go without moving opens the item's menu (a widget gets
/// resize handles instead); letting go of a dragged one just drops it, and whatever it
/// then covers moves on to free cells.
fn Model::drop_lifted(self : Model, moved : Bool) -> Unit {
self.carry = None
if self.lifted < 0 || self.lifted >= self.home.length() {
self.lifted = -1
self.regrab = false
return
}
let s = self.home[self.lifted]
if s.x >= 0 {
@grid.clear_cells(self.home, self.lifted, self.cols)
}
if !moved || self.regrab {
match s.kind {
Widget => self.resizing = self.lifted
App => self.sheet = Item(self.lifted)
}
}
self.lifted = -1
self.regrab = false
}
///|
fn Model::begin_resize(self : Model, edge : Edge, fx : Array[Effect]) -> Unit {
let i = self.resizing
if i < 0 || i >= self.home.length() {
return
}
let s = self.home[i]
let (left, top) = match self.slot_box(self.packed(), i) {
Some(b) => (b.0, b.1)
None => (self.grid_left, self.grid_top)
}
self.resize = Some({ edge, slot: i, left, top, cols: s.cols(self.cols), rows: s.height() })
fx.push(QueryLimits(s.wid))
}
///|
/// Dragging a handle snaps the widget to whole columns and rows, within its limits.
fn Model::drag_resize(
self : Model,
r : ResizeDrag,
x : Double,
y : Double,
fx : Array[Effect],
) -> Unit {
if r.slot >= self.home.length() || self.col_w <= 0.0 {
return
}
let s = self.home[r.slot]
let lim = self.limits.get(s.wid).unwrap_or(default_limits)
let n = self.cols
let mut cols = r.cols
let mut rows = r.rows
if r.edge != Bottom && lim.h {
cols = @grid.fit(
x - r.left,
1,
n,
self.col_w,
@grid.col_gap.to_double(),
lim.min_w,
lim.max_w,
)
}
if r.edge != Right && lim.v {
rows = @grid.fit(
y - r.top,
1,
20,
@grid.cell_px.to_double(),
@grid.row_gap.to_double(),
lim.min_h,
lim.max_h,
)
}
if cols == r.cols && rows == r.rows {
return
}
r.cols = cols
r.rows = rows
fx.push(Haptic)
s.w = if cols >= n { 0 } else { cols }
s.rows = rows
if s.x >= 0 {
@grid.pin(self.home, r.slot, s.x, s.y, self.cols, self.nrows)
@grid.clear_cells(self.home, r.slot, self.cols)
}
}
// ---- update -------------------------------------------------------------------
///|
/// Apply a message to the model; returns the effects for the platform to run. The
/// saved layout is kept in step automatically (a `SaveHome` whenever it changed).
pub fn update(m : Model, msg : Msg) -> Array[Effect] {
let fx : Array[Effect] = []
step(m, msg, fx)
let json = save_json(m.home)
if json != m.saved {
m.saved = json
fx.push(SaveHome(json))
}
fx
}
///|
fn Model::choose_widget(self : Model, i : Int, fx : Array[Effect]) -> Unit {
if i >= 0 && i < self.widgets.length() {
if self.home.length() < home_cap {
self.chosen = i
fx.push(AddWidget(self.widgets[i].provider))
} else {
self.say("The home screen is full", fx)
}
self.sheet = NoSheet
}
}
///|
fn step(m : Model, msg : Msg, fx : Array[Effect]) -> Unit {
match msg {
Restore(saved~, legacy~) => {
let next = Ref::new(m.next_key)
let mut slots = None
if saved is Some(text) {
slots = load_json(text, next)
if slots is Some(_) {
m.saved = text
}
}
if slots is None && legacy is Some(text) {
slots = Some(legacy_import(text, next))
}
if slots is Some(s) {
m.home = s
}
m.next_key = next.val
fx.push(LoadApps)
}
Started(now~, last_check~, declined~, installed~) => {
m.installed = installed
m.declined = declined
if @updater.should_check(now, last_check, manual=false) && !m.checking {
m.checking = true
m.manual_check = false
fx.push(SaveLastCheck(now))
fx.push(FetchRelease(@updater.release_api))
}
}
Measured(vw~, vh~, grid_left~, grid_top~, grid_w~, bottom_pad~) => {
m.cols = @grid.columns_for(vw)
m.grid_left = grid_left
m.grid_top = grid_top
m.col_w = @grid.column_width(grid_w, m.cols)
m.nrows = @grid.rows_fit(vh.to_double() - bottom_pad - grid_top)
}
AppsLoaded(text) => {
m.loading = false
match text.bind(parse_apps) {
Some(apps) => {
m.apps = apps
m.load_error = ""
m.drop_gone(fx)
}
None => m.load_error = "no response"
}
if m.sheet is DrawerApp(_) {
m.sheet = NoSheet // rows may have moved
}
}
WidgetsLoaded(text) => {
m.wloading = false
m.widgets = text.bind(parse_widgets).unwrap_or([])
}
LimitsKnown(wid, text) => {
let lim = match text {
Some(t) => parse_limits(t)
None => default_limits
}
m.limits[wid] = lim
if m.fresh == wid {
m.fresh = -1
let i = m.slot_of_widget(wid)
if i >= 0 && m.col_w > 0.0 {
m.home[i].w = @grid.widget_cols(lim.w, m.col_w, m.cols)
}
}
}
Reload => fx.push(LoadApps)
GoHome => {
m.close_all(fx)
fx.push(ScrollTop)
}
Back =>
if m.lifted >= 0 {
m.lifted = -1
m.regrab = false
m.carry = None
} else if m.resizing >= 0 {
m.resizing = -1
} else if m.sheet != NoSheet {
m.sheet = NoSheet
} else if m.drawer {
m.drawer = false
m.picking = false
m.query = ""
fx.push(HideKeyboard)
}
WidgetAdded(id) =>
if m.chosen >= 0 && m.chosen < m.widgets.length() && m.home.length() < home_cap {
let w = m.widgets[m.chosen]
m.push_slot(
@grid.Slot::widget(
w.label,
id,
rows=@grid.widget_rows(w.h),
key=m.new_key(),
),
)
m.chosen = -1
m.fresh = id
fx.push(QueryLimits(id))
}
WidgetMenu(wid) => {
let i = m.slot_of_widget(wid)
if i >= 0 && !m.drawer && m.sheet == NoSheet {
m.resizing = -1
m.regrab = false
m.lifted = i
m.native_from = None
}
}
WidgetGrab(wid) => {
let i = m.slot_of_widget(wid)
if i >= 0 && i == m.resizing && !m.drawer && m.sheet == NoSheet {
m.resizing = -1
m.regrab = true
m.lifted = i
m.native_from = None
}
}
NativeDrag(x, y) => {
m.dragged = true
let (x0, y0) = match m.native_from {
Some(p) => p
None => {
m.native_from = Some((x, y))
(x, y)
}
}
m.drag_lifted(x, y, x0, y0)
}
NativeDrop(moved) => {
m.native_from = None
m.drop_lifted(moved)
}
Touch(dx~, dy~, ms~, home_top~, list_end~) =>
if !m.dragged && m.lifted < 0 && m.sheet == NoSheet {
match @gesture.classify_swipe(dx, dy, ms) {
Some(Down) => if !m.drawer && home_top { m.open_drawer(fx) }
Some(Up) => if m.drawer && list_end { m.close_drawer(fx) }
None => ()
}
}
ReleaseFetched(text) => {
let release = text.bind(@updater.parse_release)
match release {
Some({ version_url: Some(v), apk_url: Some(a), tag }) => {
m.apk_url = Some(a)
m.release_tag = tag
fx.push(FetchVersion(v))
}
_ => {
m.checking = false
if m.manual_check {
m.say("Couldn't check for updates", fx)
}
}
}
}
VersionFetched(text) => {
m.checking = false
let latest = match text.bind(@updater.parse_version) {
Some(v) => Some(v)
None => @updater.tag_version(m.release_tag)
}
match (latest, m.apk_url) {
(Some(latest), Some(url)) =>
match
@updater.decide(latest, m.installed, m.declined, manual=m.manual_check) {
UpToDate(n) =>
if m.manual_check {
m.say("ultra Home is up to date (build \{n})", fx)
}
Declined(_) => ()
Install(n) => {
m.say("Downloading launcher update (build \{n})…", fx)
fx.push(InstallApk(url, n))
}
}
_ =>
if m.manual_check {
m.say("Couldn't check for updates", fx)
}
}
}
UpdateDeclined(n) => {
m.declined = n
fx.push(SaveDeclined(n))
}
NoticeDone(gen) => if gen == m.notice_gen { m.notice = "" }
Query(q) => m.query = q
Clear => m.query = ""
WQuery(q) => m.wquery = q
WClear => m.wquery = ""
OpenDrawer => m.open_drawer(fx)
CloseDrawer => m.close_drawer(fx)
OpenApp(row) =>
if row >= 0 && row < m.apps.length() {
fx.push(Launch(m.apps[row].component))
m.close_all(fx)
}
OpenFirst => {
let i = m.first_match()
if i >= 0 && trimmed(m.query) != "" {
fx.push(Launch(m.apps[i].component))
m.close_all(fx)
}
}
OpenHome(i) =>
if i >= 0 && i < m.home.length() {
m.resizing = -1
fx.push(Launch(m.home[i].str))
}
AddHome(row) => {
m.add_app(row, fx)
m.sheet = NoSheet
}
ToggleHome(row) => {
let i = m.home_of(row)
if i >= 0 {
m.remove_slot(i, fx)
} else if m.home.length() < home_cap {
m.push_slot(@grid.Slot::app(m.apps[row].component, key=m.new_key()))
}
}
AppMenu(row) =>
if m.drawer && m.sheet == NoSheet {
fx.push(Haptic)
m.sheet = DrawerApp(row)
}
AppInfoOf(row) => {
fx.push(AppInfo(m.apps[row].component))
m.sheet = NoSheet
}
UninstallOf(row) => {
m.gone = m.apps[row].component
fx.push(Uninstall(m.gone))
m.sheet = NoSheet
}
Menu => {
m.resizing = -1
fx.push(Haptic)
m.sheet = HomeMenu
}
CloseSheet => m.sheet = NoSheet
PickApps => {
m.sheet = NoSheet
m.drawer = true
m.picking = true
}
PickWidget => {
m.sheet = WidgetPicker
m.wquery = ""
m.wloading = true
fx.push(LoadWidgets)
}
ChooseWidget(i) => m.choose_widget(i, fx)
ChooseFirstWidget => m.choose_widget(m.first_widget_match(), fx)
Remove(i) => {
m.resizing = -1
m.remove_slot(i, fx)
m.sheet = NoSheet
}
MoveEarlier(k) => {
if k > 0 && k < m.home.length() {
let a = m.home[k]
m.home[k] = m.home[k - 1]
m.home[k - 1] = a
}
m.sheet = NoSheet
}
InfoOf(i) => {
if i >= 0 && i < m.home.length() {
fx.push(AppInfo(m.home[i].str))
}
m.sheet = NoSheet
}
Settings => {
fx.push(OpenSettings)
m.sheet = NoSheet
}
Wallpaper => {
fx.push(PickWallpaper)
m.sheet = NoSheet
}
Recents => fx.push(OpenRecents)
CheckUpdates => {
m.sheet = NoSheet
if m.checking {
m.say("Already checking for updates", fx)
} else {
m.checking = true
m.manual_check = true
m.say("Checking for updates…", fx)
fx.push(FetchRelease(@updater.release_api))
}
}
Lift(i) =>
if !m.drawer && m.sheet == NoSheet && i != m.lifted && i < m.home.length() {
fx.push(Haptic)
m.resizing = -1
m.regrab = false
m.lifted = i
}
Grab(i) =>
if i >= 0 && i == m.resizing && !m.drawer && m.sheet == NoSheet {
m.resizing = -1
m.regrab = true
m.lifted = i
}
ResizeBegin(edge) => m.begin_resize(edge, fx)
ResizeDone => m.resizing = -1
Nop => ()
Dragged(x~, y~, x0~, y0~) => {
m.dragged = true
match m.resize {
Some(r) => m.drag_resize(r, x, y, fx)
None => m.drag_lifted(x, y, x0, y0)
}
}
Released(moved~, held~) => {
ignore(held)
m.resize = None
m.drop_lifted(moved)
}
}
}
// ---- pointer input --------------------------------------------------------------
///|
/// Feed raw pointer input through the gesture recogniser and on to the handlers.
/// `table` holds the handlers of the nodes of the tree last rendered (`vdom` numbers the
/// elements that have any, in document order); an input's `chain` lists those numbers
/// from the innermost element up. Returns the effects to run.
pub fn input(
m : Model,
table : Array[@vdom.Handlers[Msg]],
inp : @gesture.Input,
) -> Array[Effect] {
let fx : Array[Effect] = []
fn nearest(chain : Array[Int], pick : (@vdom.Handlers[Msg]) -> Msg?) -> Msg? {
for id in chain {
if id >= 0 && id < table.length() {
if pick(table[id]) is Some(msg) {
return Some(msg)
}
}
}
None
}
if inp is Down(..) {
m.dragged = false
}
for out in m.gesture.step(inp) {
let msg : Msg? = match out {
Schedule(ms, token) => {
fx.push(HoldTimer(ms, token))
None
}
Began(chain~, ..) => nearest(chain, fn(h) { h.down })
Tap(chain~) => nearest(chain, fn(h) { h.tap })
Press(chain~) => nearest(chain, fn(h) { h.press })
Drag(x~, y~, x0~, y0~) => Some(Dragged(x~, y~, x0~, y0~))
Release(moved~, held~) => Some(Released(moved~, held~))
}
if msg is Some(msg) {
fx.append(update(m, msg))
}
}
fx
}
+502
View File
@@ -0,0 +1,502 @@
///|
using @vdom {type Node, type Handlers, el, text, cls_if}
///|
fn tap(msg : Msg) -> Handlers[Msg] {
{ ..Handlers::none(), tap: Some(msg) }
}
///|
fn icon(key : String) -> Node[Msg] {
el(
"img",
classes=["icon"],
attrs=[("alt", ""), ("draggable", "false"), ("data-icon", key)],
)
}
///|
/// The `grid-column` / `grid-row` of a cell: explicit, so the packing is the model's.
fn cell_style(c : @grid.Cell) -> String {
"grid-column:\{c.col + 1} / span \{c.w};grid-row:\{c.row + 1} / span \{c.h}"
}
///|
fn handle(edge : String, e : Edge) -> Node[Msg] {
el(
"span",
classes=["resize-handle"],
attrs=[("data-edge", edge), ("aria-hidden", "true")],
handlers={ ..Handlers::none(), down: Some(ResizeBegin(e)), tap: Some(Nop) },
)
}
///|
fn Model::view_slot(
self : Model,
i : Int,
packed : @grid.Packed,
) -> Node[Msg]? {
let s = self.home[i]
guard packed.cells[i] is Some(cell) else { return None }
let style = cell_style(cell)
match s.kind {
Widget => {
let live = !self.drawer &&
self.sheet == NoSheet &&
(self.resizing < 0 || i == self.resizing)
let attrs = [("data-slot", i.to_string())]
if live {
attrs.push(("data-wid", s.wid.to_string()))
}
let children = [el("span", classes=["widget-label"], children=[text(s.str)])]
if i == self.resizing {
children.push(handle("r", Right))
children.push(handle("b", Bottom))
children.push(handle("rb", Corner))
}
Some(
el(
"li",
key=s.key,
classes=["widget-slot", cls_if("lifted", i == self.lifted), cls_if("resizing", i == self.resizing)],
attrs~,
style~,
handlers={
..Handlers::none(),
press: Some(Lift(i)),
down: if i == self.resizing { Some(Grab(i)) } else { None },
tap: if i == self.resizing { Some(Nop) } else { None },
},
children~,
),
)
}
App => {
let row = self.app_row(s.str)
let a = self.apps[row]
Some(
el(
"li",
key=s.key,
classes=["tile", cls_if("lifted", i == self.lifted)],
attrs=[("data-slot", i.to_string())],
style~,
handlers={ ..Handlers::none(), tap: Some(OpenHome(i)), press: Some(Lift(i)) },
children=[icon(a.icon), el("span", classes=["name"], children=[text(a.label)])],
),
)
}
}
}
///|
fn view_panel() -> Node[Msg] {
el(
"section",
classes=["panel"],
attrs=[("aria-label", "Shortcuts")],
children=[
el(
"button",
classes=["panel-btn"],
handlers=tap(Recents),
children=[
el("span", classes=["windows-glyph"], attrs=[("aria-hidden", "true")]),
el("span", children=[text("Windows")]),
],
),
],
)
}
///|
/// The pill under the panel: a tap opens the drawer, where the search takes the keyboard.
fn view_search_pill() -> Node[Msg] {
el(
"button",
classes=["search-pill"],
attrs=[("aria-label", "Search apps")],
handlers=tap(OpenDrawer),
children=[
el("span", classes=["magnifier"], attrs=[("aria-hidden", "true")]),
el("span", children=[text("Search apps")]),
],
)
}
///|
fn Model::view_home(self : Model) -> Node[Msg] {
let packed = self.packed()
let slots : Array[Node[Msg]] = []
for i in 0..<self.home.length() {
if self.view_slot(i, packed) is Some(n) {
slots.push(n)
}
}
let rows = if self.home.length() > 0 { packed.rows } else { 0 }
let children = [
view_panel(),
view_search_pill(),
el(
"ul",
classes=["slots", cls_if("dragging", self.lifted >= 0)],
style="grid-template-columns:repeat(\{self.cols},minmax(0,1fr));grid-template-rows:repeat(\{rows},\{@grid.cell_px}px)",
children=slots,
),
]
if self.home.length() == 0 {
children.push(
el(
"p",
classes=["hint"],
children=[text("Swipe down for all apps. Long-press to add apps and widgets.")],
),
)
}
el(
"div",
classes=["home"],
handlers={
..Handlers::none(),
press: Some(Menu),
tap: if self.resizing >= 0 { Some(ResizeDone) } else { None },
},
children~,
)
}
///|
fn Model::view_drawer(self : Model) -> Node[Msg] {
let tiles : Array[Node[Msg]] = []
for i in 0..<self.apps.length() {
let a = self.apps[i]
if !matches_query(a.label, self.query) {
continue
}
tiles.push(
el(
"li",
key=i + 1,
classes=["tile", cls_if("on", self.picking && self.home_of(i) >= 0)],
handlers=if self.picking {
tap(ToggleHome(i))
} else {
{ ..Handlers::none(), tap: Some(OpenApp(i)), press: Some(AppMenu(i)) }
},
children=[icon(a.icon), el("span", classes=["name"], children=[text(a.label)])],
),
)
}
let children : Array[Node[Msg]] = [
el(
"div",
classes=["drawer-head"],
children=[
el(
"input",
classes=["input"],
attrs=[
("type", "search"),
("placeholder", "Search apps"),
("enterkeyhint", "go"),
("aria-label", "Search apps"),
("autocomplete", "off"),
],
props=[("value", self.query)],
handlers={
..Handlers::none(),
input: Some(fn(v) { Query(v) }),
enter: Some(OpenFirst),
escape: Some(Clear),
},
),
el(
"button",
classes=["btn", "ghost", "sm"],
handlers=tap(CloseDrawer),
children=[text(if self.picking { "Done" } else { "Close" })],
),
],
),
]
if self.picking {
children.push(
el(
"p",
classes=["drawer-note"],
children=[text("Tap apps to add them to the home screen or take them off.")],
),
)
}
if self.load_error != "" {
children.push(
el(
"div",
classes=["alert", "destructive"],
attrs=[("role", "alert")],
children=[text("Could not list apps")],
),
)
}
children.push(el("ul", classes=["apps"], children=tiles))
if self.loading {
children.push(el("p", classes=["empty"], children=[text("Loading apps…")]))
} else if tiles.length() == 0 {
children.push(el("p", classes=["empty"], children=[text("No apps match.")]))
}
el("div", classes=["drawer", cls_if("picking", self.picking)], children~)
}
///|
fn sheet_btn(label : String, msg : Msg) -> Node[Msg] {
el("button", classes=["sheet-item"], handlers=tap(msg), children=[text(label)])
}
///|
fn sheet_title(label : String) -> Node[Msg] {
el("h2", classes=["sheet-title"], children=[text(label)])
}
///|
fn Model::view_sheet(self : Model) -> Array[Node[Msg]] {
let items : Array[Node[Msg]] = []
match self.sheet {
NoSheet => ()
HomeMenu => {
items.push(sheet_title("Home screen"))
items.push(sheet_btn("Add apps", PickApps))
items.push(sheet_btn("Add widget", PickWidget))
items.push(sheet_btn("Wallpaper", Wallpaper))
items.push(sheet_btn("Settings", Settings))
items.push(sheet_btn("Check for updates", CheckUpdates))
}
Item(i) =>
if i >= 0 && i < self.home.length() {
let s = self.home[i]
let row = self.app_row(s.str)
items.push(
sheet_title(
if s.kind == Widget {
s.str
} else if row >= 0 {
self.apps[row].label
} else {
s.str
},
),
)
if i > 0 {
items.push(sheet_btn("Move earlier", MoveEarlier(i)))
}
if i < self.home.length() - 1 {
items.push(sheet_btn("Move later", MoveEarlier(i + 1)))
}
if s.kind == App {
items.push(sheet_btn("App info", InfoOf(i)))
items.push(sheet_btn("Remove from home", Remove(i)))
} else {
items.push(sheet_btn("Remove widget", Remove(i)))
}
}
DrawerApp(row) =>
if row >= 0 && row < self.apps.length() {
items.push(sheet_title(self.apps[row].label))
let h = self.home_of(row)
if h >= 0 {
items.push(sheet_btn("Remove from home", Remove(h)))
} else {
items.push(sheet_btn("Add to home", AddHome(row)))
}
items.push(sheet_btn("App info", AppInfoOf(row)))
if !self.apps[row].system {
items.push(sheet_btn("Uninstall", UninstallOf(row)))
}
}
WidgetPicker => {
items.push(sheet_title("Add a widget"))
if self.wloading {
items.push(el("p", classes=["empty"], children=[text("Loading widgets…")]))
} else if self.widgets.length() == 0 {
items.push(el("p", classes=["empty"], children=[text("No widgets installed.")]))
} else {
items.push(
el(
"input",
classes=["input", "widget-search"],
attrs=[
("type", "search"),
("placeholder", "Search widgets"),
("enterkeyhint", "go"),
("aria-label", "Search widgets"),
("autocomplete", "off"),
],
props=[("value", self.wquery)],
handlers={
..Handlers::none(),
input: Some(fn(v) { WQuery(v) }),
enter: Some(ChooseFirstWidget),
escape: Some(WClear),
},
),
)
}
let rows : Array[Node[Msg]] = []
for i in 0..<self.widgets.length() {
if !self.widget_matches(i) {
continue
}
let w = self.widgets[i]
let name : Array[Node[Msg]] = [text(w.label)]
if w.app != "" && w.app != w.label {
name.push(el("small", children=[text(w.app)]))
}
rows.push(
el(
"li",
key=i + 1,
handlers=tap(ChooseWidget(i)),
children=[icon(w.icon), el("span", classes=["widget-name"], children=name)],
),
)
}
items.push(el("ul", classes=["widget-list"], children=rows))
if !self.wloading && self.widgets.length() > 0 && rows.length() == 0 {
items.push(el("p", classes=["empty"], children=[text("No widgets match.")]))
}
}
}
[
el("div", classes=["sheet-overlay"], handlers=tap(CloseSheet)),
el(
"div",
classes=["sheet"],
attrs=[("role", "dialog"), ("aria-modal", "true")],
handlers={ ..Handlers::none(), escape: Some(CloseSheet) },
children=items,
),
]
}
///|
fn Model::view_resize_bar(self : Model) -> Node[Msg] {
el(
"div",
classes=["resize-bar"],
attrs=[("role", "toolbar")],
children=[
el(
"span",
classes=["resize-hint"],
children=[text("Drag to move, or drag the handles to resize")],
),
el(
"button",
classes=["btn", "ghost", "sm"],
handlers=tap(Remove(self.resizing)),
children=[text("Remove")],
),
el(
"button",
classes=["btn", "primary", "sm"],
handlers=tap(ResizeDone),
children=[text("Done")],
),
],
)
}
///|
/// The whole screen as a tree.
pub fn view(m : Model) -> Array[Node[Msg]] {
let out : Array[Node[Msg]] = [m.view_home()]
if m.drawer {
out.push(m.view_drawer())
}
if m.sheet != NoSheet {
out.append(m.view_sheet())
} else if m.resizing >= 0 && !m.drawer {
out.push(m.view_resize_bar())
}
if m.notice != "" {
out.push(
el(
"div",
classes=["notice"],
attrs=[("role", "status")],
children=[text(m.notice)],
),
)
}
out
}
///|
/// The handlers of a tree's elements, numbered in document order (pre-order): the
/// platform layer marks each such element with its number and reports pointer input as
/// chains of them (see `input`).
pub fn handler_table(nodes : Array[Node[Msg]]) -> Array[Handlers[Msg]] {
let out : Array[Handlers[Msg]] = []
fn walk(n : Node[Msg]) -> Unit {
if n is El(e) {
if !e.handlers.is_empty() {
out.push(e.handlers)
}
for c in e.children {
walk(c)
}
}
}
for n in nodes {
walk(n)
}
out
}
///|
pub(all) enum Key {
Enter
Escape
}
///|
/// A key pressed in an input; `chain` as for `input`.
pub fn key(
m : Model,
table : Array[Handlers[Msg]],
chain : Array[Int],
k : Key,
) -> Array[Effect] {
for id in chain {
if id >= 0 && id < table.length() {
let h = table[id]
let msg = match k {
Enter => h.enter
Escape => h.escape
}
if msg is Some(msg) {
return update(m, msg)
}
}
}
[]
}
///|
/// An input's text changed.
pub fn typed(
m : Model,
table : Array[Handlers[Msg]],
chain : Array[Int],
value : String,
) -> Array[Effect] {
for id in chain {
if id >= 0 && id < table.length() {
if table[id].input is Some(f) {
return update(m, f(value))
}
}
}
[]
}
+141
View File
@@ -0,0 +1,141 @@
///|
/// Pointer gestures as a pure state machine. The platform layer reports raw pointer
/// input (down, move, up, cancel, and the long-press timer firing); this decides what
/// it was and answers with `Out`s. It knows nothing about what was touched: a target is
/// a `chain` of node ids from the innermost element up, and the app resolves them.
///
/// - a stationary hold for `hold_ms` is a *press* (long press); moving more than
/// `slop` px first cancels it
/// - a press that ends without moving is a *release* with `moved = false`
/// (the home screen opens the item's menu)
/// - letting go without a hold or a move is a *tap*
/// - once the pointer has moved past the slop, every move is a *drag*
/// (whether it means anything depends on what the app has lifted)
///|
/// How long a stationary hold takes to become a long press.
pub let hold_ms : Int = 500
///|
/// How far (px) the pointer may travel before it stops being a tap or a hold.
pub let slop : Double = 10.0
///|
#derive(Eq, Debug)
pub(all) enum Input {
Down(x~ : Double, y~ : Double, chain~ : Array[Int])
Move(x~ : Double, y~ : Double)
Up(x~ : Double, y~ : Double)
Cancel
/// The timer started by `Schedule(_, token)` fired.
Hold(Int)
}
///|
#derive(Eq, Debug)
pub(all) enum Out {
/// Start a timer of this many ms, then send `Hold(token)`.
Schedule(Int, Int)
/// The pointer went down on this chain (the app may act at once, e.g. grab a widget).
Began(chain~ : Array[Int], x~ : Double, y~ : Double)
Tap(chain~ : Array[Int])
Press(chain~ : Array[Int])
/// The pointer is at x, y; it went down at x0, y0.
Drag(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double)
/// The pointer is up. `moved`: it travelled past the slop; `held`: a press fired.
Release(moved~ : Bool, held~ : Bool)
}
///|
pub(all) struct State {
mut down : Bool
mut x0 : Double
mut y0 : Double
mut moved : Bool
mut held : Bool
mut chain : Array[Int]
mut token : Int
}
///|
pub fn State::new() -> State {
{ down: false, x0: 0.0, y0: 0.0, moved: false, held: false, chain: [], token: 0 }
}
///|
/// Feed one input; returns what happened.
pub fn State::step(self : State, input : Input) -> Array[Out] {
match input {
Down(x~, y~, chain~) => {
self.down = true
self.x0 = x
self.y0 = y
self.moved = false
self.held = false
self.chain = chain
self.token += 1
[Began(chain~, x~, y~), Schedule(hold_ms, self.token)]
}
Move(x~, y~) =>
if !self.down {
[]
} else {
if !self.moved {
let dx = x - self.x0
let dy = y - self.y0
if (dx * dx + dy * dy).sqrt() >= slop {
self.moved = true
self.token += 1 // a hold timer still running is stale now
}
}
if self.moved {
[Drag(x~, y~, x0=self.x0, y0=self.y0)]
} else {
[]
}
}
Up(..) | Cancel =>
if !self.down {
[]
} else {
let chain = self.chain
let moved = self.moved
let held = self.held
self.down = false
self.token += 1
let tap : Array[Out] = if !moved && !held && input is Up(..) {
[Tap(chain~)]
} else {
[]
}
[..tap, Release(moved~, held~)]
}
Hold(token) =>
if self.down && token == self.token && !self.moved && !self.held {
self.held = true
[Press(chain=self.chain)]
} else {
[]
}
}
}
///|
#derive(Eq, Debug)
pub(all) enum Swipe {
Down
Up
}
///|
/// A touch that travelled dx, dy px in dt ms is a swipe when it was quick, long enough
/// and more vertical than horizontal.
pub fn classify_swipe(dx : Double, dy : Double, dt : Int) -> Swipe? {
if dt >= 700 || dy.abs() < 60.0 || dx.abs() > dy.abs() {
None
} else if dy > 0.0 {
Some(Down)
} else {
Some(Up)
}
}
+66
View File
@@ -0,0 +1,66 @@
///|
test "a tap: down then up without moving" {
let g = State::new()
assert_eq(
g.step(Down(x=10.0, y=10.0, chain=[3, 1])),
[Began(chain=[3, 1], x=10.0, y=10.0), Schedule(500, 1)],
)
assert_eq(g.step(Up(x=11.0, y=10.0)), [Tap(chain=[3, 1]), Release(moved=false, held=false)])
}
///|
test "a long press: the timer fires, then the release is not a tap" {
let g = State::new()
ignore(g.step(Down(x=0.0, y=0.0, chain=[7])))
assert_eq(g.step(Hold(1)), [Press(chain=[7])])
assert_eq(g.step(Up(x=0.0, y=0.0)), [Release(moved=false, held=true)])
}
///|
test "moving past the slop cancels the hold and starts a drag" {
let g = State::new()
ignore(g.step(Down(x=0.0, y=0.0, chain=[7])))
assert_eq(g.step(Move(x=5.0, y=0.0)), [])
assert_eq(g.step(Move(x=20.0, y=0.0)), [Drag(x=20.0, y=0.0, x0=0.0, y0=0.0)])
assert_eq(g.step(Hold(1)), []) // the stale timer does nothing
assert_eq(g.step(Move(x=30.0, y=2.0)), [Drag(x=30.0, y=2.0, x0=0.0, y0=0.0)])
assert_eq(g.step(Up(x=30.0, y=2.0)), [Release(moved=true, held=false)])
}
///|
test "a press then a drag, then release" {
let g = State::new()
ignore(g.step(Down(x=0.0, y=0.0, chain=[7])))
ignore(g.step(Hold(1)))
assert_eq(g.step(Move(x=40.0, y=0.0)), [Drag(x=40.0, y=0.0, x0=0.0, y0=0.0)])
assert_eq(g.step(Up(x=40.0, y=0.0)), [Release(moved=true, held=true)])
}
///|
test "cancel releases without a tap; stray input is ignored" {
let g = State::new()
assert_eq(g.step(Up(x=0.0, y=0.0)), [])
assert_eq(g.step(Move(x=0.0, y=0.0)), [])
ignore(g.step(Down(x=0.0, y=0.0, chain=[1])))
assert_eq(g.step(Cancel), [Release(moved=false, held=false)])
assert_eq(g.step(Hold(1)), [])
}
///|
test "a stale timer from an earlier press is ignored" {
let g = State::new()
ignore(g.step(Down(x=0.0, y=0.0, chain=[1])))
ignore(g.step(Up(x=0.0, y=0.0)))
ignore(g.step(Down(x=0.0, y=0.0, chain=[2])))
assert_eq(g.step(Hold(1)), [])
assert_eq(g.step(Hold(3)), [Press(chain=[2])])
}
///|
test "swipes" {
assert_eq(classify_swipe(5.0, 100.0, 300), Some(Down))
assert_eq(classify_swipe(5.0, -100.0, 300), Some(Up))
assert_eq(classify_swipe(5.0, 50.0, 300), None) // too short
assert_eq(classify_swipe(120.0, 100.0, 300), None) // more sideways than down
assert_eq(classify_swipe(5.0, 100.0, 900), None) // too slow
}
View File
Whitespace-only changes.
+57
View File
@@ -0,0 +1,57 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/gesture"
import {
"moonbitlang/core/debug",
}
// Values
pub fn classify_swipe(Double, Double, Int32) -> Swipe?
pub let hold_ms : Int32
pub let slop : Double
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum Input {
Down(x~ : Double, y~ : Double, chain~ : Array[Int32])
Move(x~ : Double, y~ : Double)
Up(x~ : Double, y~ : Double)
Cancel
Hold(Int32)
}
#derive(Eq, @debug.Debug)
pub(all) enum Out {
Schedule(Int32, Int32)
Began(chain~ : Array[Int32], x~ : Double, y~ : Double)
Tap(chain~ : Array[Int32])
Press(chain~ : Array[Int32])
Drag(x~ : Double, y~ : Double, x0~ : Double, y0~ : Double)
Release(moved~ : Bool, held~ : Bool)
}
pub(all) struct State {
mut down : Bool
mut x0 : Double
mut y0 : Double
mut moved : Bool
mut held : Bool
mut chain : Array[Int32]
mut token : Int32
}
pub fn State::new() -> Self
pub fn State::step(Self, Input) -> Array[Out]
#derive(Eq, @debug.Debug)
pub(all) enum Swipe {
Down
Up
}
// Type aliases
// Traits
+353
View File
@@ -0,0 +1,353 @@
///|
/// The home grid as plain functions over a list of slots: packing, the cell under a
/// point, pinning, resize steps. Pure; ported from legacy/qt/qml/Layout.js and the
/// packing logic of legacy/web/app.py.
///
/// A slot is an app (one cell) or a widget (`w` columns by `rows` rows). `x`/`y` is the
/// cell it was dropped into (column, row from 0), or -1/-1: placed in order into the
/// first free cells that fit it ("dense" packing, so apps fill the cells beside a widget
/// and the grid has no holes).
///|
/// Row height in px.
pub let cell_px : Int = 64
///|
/// Gap between rows in px.
pub let row_gap : Int = 8
///|
/// Gap between columns in px.
pub let col_gap : Int = 8
///|
#derive(Eq, Debug)
pub(all) enum Kind {
App
Widget
}
///|
#derive(Eq, Debug)
pub(all) struct Slot {
kind : Kind
/// An app's component name, or a widget's label.
str : String
/// A widget's host id (0 for apps).
wid : Int
/// A widget's width in columns (0: the whole row).
mut w : Int
/// A widget's height in rows.
mut rows : Int
mut x : Int
mut y : Int
/// A stable identity for the view's keyed diff (not persisted).
key : Int
}
///|
pub fn Slot::app(str : String, key~ : Int = 0) -> Slot {
{ kind: App, str, wid: 0, w: 0, rows: 1, x: -1, y: -1, key }
}
///|
pub fn Slot::widget(
str : String,
wid : Int,
w~ : Int = 0,
rows~ : Int = 1,
key~ : Int = 0,
) -> Slot {
{ kind: Widget, str, wid, w, rows, x: -1, y: -1, key }
}
///|
/// Rows of app tiles nearest to a widget height in px, at least one.
pub fn widget_rows(px : Int) -> Int {
let k = (px + row_gap + (cell_px + row_gap) / 2) / (cell_px + row_gap)
if k < 1 {
1
} else {
k
}
}
///|
pub fn Slot::cols(self : Slot, cols : Int) -> Int {
match self.kind {
App => 1
Widget => if self.w <= 0 || self.w > cols { cols } else { self.w }
}
}
///|
pub fn Slot::height(self : Slot) -> Int {
match self.kind {
App => 1
Widget => if self.rows < 1 { 1 } else { self.rows }
}
}
///|
pub fn Slot::pinned(self : Slot, cols : Int) -> Bool {
self.x >= 0 && self.y >= 0 && self.x + self.cols(cols) <= cols
}
///|
/// Where a slot goes, in cells.
#derive(Eq, Debug)
pub(all) struct Cell {
col : Int
row : Int
w : Int
h : Int
}
///|
pub(all) struct Packed {
/// One per slot, `None` for a hidden one.
cells : Array[Cell?]
/// Rows used, at least the rows that fill the screen.
rows : Int
}
///|
/// Where each slot goes, and the rows used (at least `nrows`, the rows that fill the
/// screen). Pinned slots keep their cell (they may overlap each other while one is
/// carried); the rest go in order into the first free cells that fit them. `hidden[i]`
/// leaves slot i out (an app that is not installed).
pub fn pack(
slots : Array[Slot],
cols : Int,
nrows : Int,
hidden~ : (Int) -> Bool = fn(_) { false },
) -> Packed {
let occ : Array[Array[Bool]] = []
fn taken(c : Int, r : Int) -> Bool {
r < occ.length() && occ[r][c]
}
fn fits(c : Int, r : Int, w : Int, h : Int) -> Bool {
if c < 0 || c + w > cols {
return false
}
for y in r..<(r + h) {
for x in c..<(c + w) {
if taken(x, y) {
return false
}
}
}
true
}
fn mark(c : Int, r : Int, w : Int, h : Int) -> Unit {
for y in r..<(r + h) {
while occ.length() <= y {
occ.push(Array::make(cols, false))
}
for x in c..<(c + w) {
occ[y][x] = true
}
}
}
let n = slots.length()
let cells : Array[Cell?] = Array::make(n, None)
let mut rows = if nrows < 0 { 0 } else { nrows }
for i in 0..<n {
let s = slots[i]
if hidden(i) || !s.pinned(cols) {
continue
}
let w = s.cols(cols)
let h = s.height()
cells[i] = Some({ col: s.x, row: s.y, w, h })
mark(s.x, s.y, w, h)
rows = @cmp.maximum(rows, s.y + h)
}
for i in 0..<n {
let s = slots[i]
if hidden(i) || cells[i] is Some(_) {
continue
}
let w = s.cols(cols)
let h = s.height()
let mut r = 0
while cells[i] is None {
let mut c = 0
while c + w <= cols {
if fits(c, r, w, h) {
cells[i] = Some({ col: c, row: r, w, h })
mark(c, r, w, h)
rows = @cmp.maximum(rows, r + h)
break
}
c += 1
}
r += 1
}
}
{ cells, rows }
}
///|
/// A cell's box in px, given the column width: (x, y, w, h).
pub fn box(cell : Cell, col_w : Double) -> (Double, Double, Double, Double) {
let cg = col_gap.to_double()
let rg = row_gap.to_double()
(
cell.col.to_double() * (col_w + cg),
cell.row.to_double() * (cell_px.to_double() + rg),
cell.w.to_double() * col_w + (cell.w - 1).to_double() * cg,
cell.h.to_double() * cell_px.to_double() + (cell.h - 1).to_double() * rg,
)
}
///|
/// The cell nearest to a point (px in the grid, from its top left): (col, row).
pub fn cell_at(x : Double, y : Double, col_w : Double) -> (Int, Int) {
let c = ((x / (col_w + col_gap.to_double()) + 0.5).floor()).to_int()
let r = ((y / (cell_px + row_gap).to_double() + 0.5).floor()).to_int()
(@cmp.maximum(0, c), @cmp.maximum(0, r))
}
///|
/// The cell whose box contains a point, or `None` outside every cell (in the gaps).
pub fn cell_under(
x : Double,
y : Double,
col_w : Double,
) -> (Int, Int)? {
if x < 0.0 || y < 0.0 {
return None
}
let pw = col_w + col_gap.to_double()
let ph = (cell_px + row_gap).to_double()
let c = (x / pw).floor().to_int()
let r = (y / ph).floor().to_int()
if x - c.to_double() * pw > col_w || y - r.to_double() * ph > cell_px.to_double() {
None
} else {
Some((c, r))
}
}
///|
/// Pin slot `i` with its top left at `col`, `row`, kept on the screen's grid (`nrows` of
/// 0: no limit on rows).
pub fn pin(
slots : Array[Slot],
i : Int,
col : Int,
row : Int,
cols : Int,
nrows : Int,
) -> Unit {
let s = slots[i]
let mut x = col
let mut y = row
if x + s.cols(cols) > cols {
x = cols - s.cols(cols)
}
if nrows > 0 && y + s.height() > nrows {
y = nrows - s.height()
}
s.x = @cmp.maximum(0, x)
s.y = @cmp.maximum(0, y)
}
///|
/// Unpin the slots under pinned slot `i`, so they flow into free cells.
pub fn clear_cells(slots : Array[Slot], i : Int, cols : Int) -> Unit {
let a = slots[i]
for j in 0..<slots.length() {
let b = slots[j]
if j == i || b.x < 0 {
continue
}
if b.x < a.x + a.cols(cols) &&
a.x < b.x + b.cols(cols) &&
b.y < a.y + a.height() &&
a.y < b.y + b.height() {
b.x = -1
b.y = -1
}
}
}
///|
/// Take slot `a` out and put it back at `b`, shifting the slots between.
pub fn move_slot(slots : Array[Slot], a : Int, b : Int) -> Unit {
let s = slots.remove(a)
slots.insert(b, s)
}
///|
/// The size in px of `k` cells of `size` px, `gap` apart.
pub fn span(k : Int, size : Double, gap : Double) -> Double {
k.to_double() * size + (k - 1).to_double() * gap
}
///|
/// Resize steps: the number of cells (of `size` px, `gap` apart) nearest to `want` px,
/// kept within `min`..`max` px where it can be (`max` of 0: no limit), and within
/// `lo`..`hi` cells.
pub fn fit(
want : Double,
lo : Int,
hi : Int,
size : Double,
gap : Double,
min : Int,
max : Int,
) -> Int {
let mut k = ((want + gap) / (size + gap) + 0.5).floor().to_int()
while k < hi && span(k, size, gap) < (min - 8).to_double() {
k += 1
}
while k > lo && max > 0 && span(k, size, gap) > (max + 8).to_double() {
k -= 1
}
@cmp.maximum(lo, @cmp.minimum(hi, k))
}
///|
/// Columns a new widget of natural width `px` starts at (0: the whole row).
pub fn widget_cols(px : Int, col_w : Double, cols : Int) -> Int {
if px <= 0 {
return 0
}
let k = @cmp.maximum(
1,
((px + col_gap - 8).to_double() / (col_w + col_gap.to_double())).ceil().to_int(),
)
if k >= cols {
0
} else {
k
}
}
///|
/// How many grid columns the screen has for a viewport width in CSS px.
pub fn columns_for(width : Int) -> Int {
if width >= 480 {
6
} else {
5
}
}
///|
/// The width of one column, given the width of the grid.
pub fn column_width(grid_width : Double, cols : Int) -> Double {
(grid_width - (cols - 1).to_double() * col_gap.to_double()) / cols.to_double()
}
///|
/// How many rows of the grid fit in `height` px.
pub fn rows_fit(height : Double) -> Int {
let r = ((height + row_gap.to_double()) / (cell_px + row_gap).to_double()).floor().to_int()
@cmp.maximum(1, r)
}
+162
View File
@@ -0,0 +1,162 @@
///|
fn app(x? : Int = -1, y? : Int = -1) -> Slot {
let s = Slot::app("a")
s.x = x
s.y = y
s
}
///|
fn widget(w : Int, rows : Int, x? : Int = -1, y? : Int = -1) -> Slot {
let s = Slot::widget("W", 1, w~, rows~)
s.x = x
s.y = y
s
}
///|
fn cells(
home : Array[Slot],
cols? : Int = 5,
nrows? : Int = 0,
) -> Array[(Int, Int, Int, Int)?] {
pack(home, cols, nrows).cells.map(fn(c) {
match c {
Some(c) => Some((c.col, c.row, c.w, c.h))
None => None
}
})
}
///|
test "apps fill rows left to right" {
assert_eq(
cells([app(), app(), app(), app(), app(), app()]),
[
Some((0, 0, 1, 1)),
Some((1, 0, 1, 1)),
Some((2, 0, 1, 1)),
Some((3, 0, 1, 1)),
Some((4, 0, 1, 1)),
Some((0, 1, 1, 1)),
],
)
}
///|
test "a whole-row widget takes its rows; apps go below" {
assert_eq(cells([widget(0, 2), app()]), [Some((0, 0, 5, 2)), Some((0, 2, 1, 1))])
}
///|
test "dense: apps fill the cells beside a narrow widget" {
assert_eq(
cells([widget(3, 2), app(), app(), app(), app(), app()]),
[
Some((0, 0, 3, 2)),
Some((3, 0, 1, 1)),
Some((4, 0, 1, 1)),
Some((3, 1, 1, 1)),
Some((4, 1, 1, 1)),
Some((0, 2, 1, 1)),
],
)
}
///|
test "a widget too wide for the rest of a row starts the next; apps backfill" {
assert_eq(
cells([app(), app(), app(), widget(3, 1), app()]),
[
Some((0, 0, 1, 1)),
Some((1, 0, 1, 1)),
Some((2, 0, 1, 1)),
Some((0, 1, 3, 1)),
Some((3, 0, 1, 1)),
],
)
}
///|
test "pinned slots keep their cell; the rest flow around them" {
assert_eq(
cells([app(), app(x=2, y=3), app()]),
[Some((0, 0, 1, 1)), Some((2, 3, 1, 1)), Some((1, 0, 1, 1))],
)
}
///|
test "rows: at least nrows, more if the slots need them" {
assert_eq(pack([app()], 5, 9).rows, 9)
assert_eq(pack([app(x=0, y=12)], 5, 9).rows, 13)
}
///|
test "a pin that no longer fits the columns flows instead" {
assert_eq(cells([widget(3, 1, x=3, y=0)]), [Some((0, 0, 3, 1))])
}
///|
test "hidden slots take no cell" {
let p = pack([app(), app()], 5, 0, hidden=fn(i) { i == 0 })
assert_eq(p.cells[0], None)
assert_eq(p.cells[1], Some({ col: 0, row: 0, w: 1, h: 1 }))
}
///|
test "pinning stays on the grid; dropping unpins what it covers" {
let h = [widget(2, 2), app(x=1, y=1), app(x=4, y=4)]
pin(h, 0, 4, 9, 5, 8)
assert_eq((h[0].x, h[0].y), (3, 6))
pin(h, 0, 0, 0, 5, 8)
clear_cells(h, 0, 5)
assert_eq((h[1].x, h[1].y, h[2].x, h[2].y), (-1, -1, 4, 4))
}
///|
test "moving in the order" {
let h = ["a", "b", "c", "d"]
let s = h.map(fn(x) { Slot::app(x) })
move_slot(s, 0, 2)
assert_eq(s.map(fn(x) { x.str }), ["b", "c", "a", "d"])
move_slot(s, 3, 0)
assert_eq(s.map(fn(x) { x.str }), ["d", "b", "c", "a"])
}
///|
test "widget heights in px to rows" {
assert_eq([40, 64, 100, 136, 208, 420].map(widget_rows), [1, 1, 2, 2, 3, 6])
}
///|
test "resize steps snap to cells within the widget's limits" {
assert_eq(fit(150.0, 1, 5, 64.0, 8.0, 0, 0), 2)
assert_eq(fit(10.0, 1, 5, 64.0, 8.0, 200, 0), 3)
assert_eq(fit(400.0, 1, 5, 64.0, 8.0, 0, 150), 2)
}
///|
test "a new widget's columns from its natural width" {
assert_eq(widget_cols(0, 70.0, 5), 0)
assert_eq(widget_cols(110, 70.0, 5), 2)
assert_eq(widget_cols(400, 70.0, 5), 0)
}
///|
test "boxes and cells in px" {
let b = box({ col: 1, row: 2, w: 2, h: 1 }, 70.0)
assert_eq(b, (78.0, 144.0, 148.0, 64.0))
assert_eq(cell_at(80.0, 150.0, 70.0), (1, 2))
assert_eq(cell_under(80.0, 150.0, 70.0), Some((1, 2)))
assert_eq(cell_under(72.0, 150.0, 70.0), None) // in the column gap
assert_eq(cell_under(-1.0, 5.0, 70.0), None)
}
///|
test "viewport to grid" {
assert_eq(columns_for(390), 5)
assert_eq(columns_for(600), 6)
assert_eq(column_width(358.0, 5), 65.2)
assert_eq(rows_fit(500.0), 7)
assert_eq(rows_fit(10.0), 1)
}
+3
View File
@@ -0,0 +1,3 @@
import {
"moonbitlang/core/cmp",
}
+84
View File
@@ -0,0 +1,84 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/grid"
import {
"moonbitlang/core/debug",
}
// Values
pub fn box(Cell, Double) -> (Double, Double, Double, Double)
pub fn cell_at(Double, Double, Double) -> (Int32, Int32)
pub let cell_px : Int32
pub fn cell_under(Double, Double, Double) -> (Int32, Int32)?
pub fn clear_cells(Array[Slot], Int32, Int32) -> Unit
pub let col_gap : Int32
pub fn column_width(Double, Int32) -> Double
pub fn columns_for(Int32) -> Int32
pub fn fit(Double, Int32, Int32, Double, Double, Int32, Int32) -> Int32
pub fn move_slot(Array[Slot], Int32, Int32) -> Unit
pub fn pack(Array[Slot], Int32, Int32, hidden? : (Int32) -> Bool) -> Packed
pub fn pin(Array[Slot], Int32, Int32, Int32, Int32, Int32) -> Unit
pub let row_gap : Int32
pub fn rows_fit(Double) -> Int32
pub fn span(Int32, Double, Double) -> Double
pub fn widget_cols(Int32, Double, Int32) -> Int32
pub fn widget_rows(Int32) -> Int32
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) struct Cell {
col : Int32
row : Int32
w : Int32
h : Int32
}
#derive(Eq, @debug.Debug)
pub(all) enum Kind {
App
Widget
}
pub(all) struct Packed {
cells : Array[Cell?]
rows : Int32
}
#derive(Eq, @debug.Debug)
pub(all) struct Slot {
kind : Kind
str : String
wid : Int32
mut w : Int32
mut rows : Int32
mut x : Int32
mut y : Int32
key : Int32
}
pub fn Slot::app(String, key? : Int32) -> Self
pub fn Slot::cols(Self, Int32) -> Int32
pub fn Slot::height(Self) -> Int32
pub fn Slot::pinned(Self, Int32) -> Bool
pub fn Slot::widget(String, Int32, w? : Int32, rows? : Int32, key? : Int32) -> Self
// Type aliases
// Traits
+52
View File
@@ -0,0 +1,52 @@
///|
/// Small accessors over `Json`, so decoding code reads as lookups with defaults.
///|
pub fn get(j : Json, key : String) -> Json? {
match j {
Object(o) => o.get(key)
_ => None
}
}
///|
pub fn str(j : Json, key : String, default? : String = "") -> String {
match get(j, key) {
Some(String(s)) => s
_ => default
}
}
///|
pub fn int(j : Json, key : String, default? : Int = 0) -> Int {
match get(j, key) {
Some(Number(n, ..)) => n.to_int()
Some(True) => 1
_ => default
}
}
///|
pub fn bool(j : Json, key : String, default? : Bool = false) -> Bool {
match get(j, key) {
Some(True) => true
Some(False) => false
Some(Number(n, ..)) => n != 0.0
_ => default
}
}
///|
pub fn arr(j : Json, key : String) -> Array[Json] {
match get(j, key) {
Some(Array(a)) => a
_ => []
}
}
///|
pub fn parse(text : String) -> Json? {
try Some(@json.parse(text)) catch {
_ => None
}
}
+13
View File
@@ -0,0 +1,13 @@
///|
test "accessors with defaults" {
let j = parse("{\"a\":\"x\",\"n\":3,\"b\":true,\"l\":[1,2],\"o\":{}}").unwrap()
assert_eq(str(j, "a"), "x")
assert_eq(str(j, "zz", default="d"), "d")
assert_eq(int(j, "n"), 3)
assert_eq(int(j, "b"), 1)
assert_eq(int(j, "a", default=-1), -1)
assert_true(bool(j, "b"))
assert_eq(arr(j, "l").length(), 2)
assert_eq(arr(j, "o").length(), 0)
assert_true(parse("{") is None)
}
+3
View File
@@ -0,0 +1,3 @@
import {
"moonbitlang/core/json",
}
+27
View File
@@ -0,0 +1,27 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/jsonx"
import {
"moonbitlang/core/json",
}
// Values
pub fn arr(@json.Json, String) -> Array[@json.Json]
pub fn bool(@json.Json, String, default? : Bool) -> Bool
pub fn get(@json.Json, String) -> @json.Json?
pub fn int(@json.Json, String, default? : Int32) -> Int32
pub fn parse(String) -> @json.Json?
pub fn str(@json.Json, String, default? : String) -> String
// Errors
// Types and methods
// Type aliases
// Traits
+15
View File
@@ -0,0 +1,15 @@
name = "experiments/launcher"
version = "0.1.0" // sweet-version
readme = "README.md"
repository = "https://git.site.latha.org/experiments/launcher"
license = "Apache-2.0"
keywords = [ "android", "launcher", "home-screen" ]
description = "Android home screen launcher: pure MoonBit core and UI, rendered in a WebView by a thin Java shell"
preferred_target = "js"
+3
View File
@@ -0,0 +1,3 @@
import {
"experiments/launcher/jsonx",
}
+45
View File
@@ -0,0 +1,45 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/updater"
import {
"moonbitlang/core/debug",
}
// Values
pub let apk_asset : String
pub let check_every_ms : Int64
pub fn decide(Int32, Int32, Int32, manual~ : Bool) -> Decision
pub fn parse_release(String) -> Release?
pub fn parse_version(String) -> Int32?
pub let release_api : String
pub fn should_check(Int64, Int64, manual~ : Bool) -> Bool
pub fn tag_version(String) -> Int32?
pub let version_asset : String
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum Decision {
UpToDate(Int32)
Install(Int32)
Declined(Int32)
}
pub(all) struct Release {
tag : String
version_url : String?
apk_url : String?
}
// Type aliases
// Traits
+111
View File
@@ -0,0 +1,111 @@
///|
/// Self-update logic, pure. The shell does the network and the install; this decides
/// what the releases it fetched mean.
///
/// CI publishes a Gitea release `build-<versionCode>` holding `ultra-launcher.apk` and
/// `version.json` (`{"versionCode": N, "commit": SHA}`), with N also the APK's
/// versionCode. The latest-release API names the download URLs of both assets.
///|
pub let release_api : String =
"https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/latest"
///|
pub let apk_asset : String = "ultra-launcher.apk"
///|
pub let version_asset : String = "version.json"
///|
/// How often the home screen checks by itself (6 hours).
pub let check_every_ms : Int64 = 6L * 60L * 60L * 1000L
///|
pub(all) struct Release {
tag : String
version_url : String?
apk_url : String?
}
///|
/// The latest-release JSON from the Gitea API.
pub fn parse_release(text : String) -> Release? {
let json = @jsonx.parse(text)
guard json is Some(json) else { return None }
let mut version_url = None
let mut apk_url = None
for a in @jsonx.arr(json, "assets") {
let name = @jsonx.str(a, "name")
let url = @jsonx.str(a, "browser_download_url")
if url != "" {
if name == version_asset {
version_url = Some(url)
} else if name == apk_asset {
apk_url = Some(url)
}
}
}
Some({ tag: @jsonx.str(json, "tag_name"), version_url, apk_url })
}
///|
/// The versionCode in a `version.json`.
pub fn parse_version(text : String) -> Int? {
guard @jsonx.parse(text) is Some(json) else { return None }
match @jsonx.get(json, "versionCode") {
Some(Number(n, ..)) => Some(n.to_int())
_ => None
}
}
///|
/// The versionCode a release tag `build-<N>` stands for.
pub fn tag_version(tag : String) -> Int? {
guard tag.has_prefix("build-") else { return None }
let rest = tag.clamped_view(start=6)
if rest.length() == 0 {
return None
}
let mut n = 0
for c in rest {
if c < '0' || c > '9' {
return None
}
n = n * 10 + (c.to_int() - '0'.to_int())
}
Some(n)
}
///|
#derive(Eq, Debug)
pub(all) enum Decision {
UpToDate(Int)
/// A newer build exists and should be installed.
Install(Int)
/// The user already cancelled this build's install; not offered again unless they ask.
Declined(Int)
}
///|
/// `latest` is the newest published versionCode, `installed` the running one, `declined`
/// the last build whose install the user cancelled (-1: none).
pub fn decide(
latest : Int,
installed : Int,
declined : Int,
manual~ : Bool,
) -> Decision {
if latest <= installed {
UpToDate(installed)
} else if !manual && latest == declined {
Declined(latest)
} else {
Install(latest)
}
}
///|
/// An automatic check runs at most every `check_every_ms`; a manual one always runs.
pub fn should_check(now : Int64, last : Int64, manual~ : Bool) -> Bool {
manual || now - last >= check_every_ms
}
+54
View File
@@ -0,0 +1,54 @@
///|
let sample : String =
#|{"tag_name":"build-29000123","assets":[
#|{"name":"version.json","browser_download_url":"https://x/v.json"},
#|{"name":"ultra-launcher.apk","browser_download_url":"https://x/a.apk"}]}
///|
test "release assets by name" {
let r = parse_release(sample).unwrap()
assert_eq(r.tag, "build-29000123")
assert_eq(r.version_url, Some("https://x/v.json"))
assert_eq(r.apk_url, Some("https://x/a.apk"))
}
///|
test "bad or partial release json" {
assert_eq(parse_release("nope").map(fn(r) { r.tag }), None)
let r = parse_release("{\"tag_name\":\"t\"}").unwrap()
assert_eq(r.apk_url, None)
}
///|
test "version.json" {
assert_eq(parse_version("{\"versionCode\": 29000123, \"commit\": \"abc\"}"), Some(29000123))
assert_eq(parse_version("{}"), None)
assert_eq(parse_version("x"), None)
}
///|
test "tags compare as build numbers" {
assert_eq(tag_version("build-29000123"), Some(29000123))
assert_eq(tag_version("build-"), None)
assert_eq(tag_version("v1.2.3"), None)
assert_eq(tag_version("build-12x"), None)
assert_true(tag_version("build-10").unwrap() < tag_version("build-9000").unwrap())
}
///|
test "deciding" {
assert_eq(decide(5, 5, -1, manual=false), UpToDate(5))
assert_eq(decide(4, 5, -1, manual=true), UpToDate(5))
assert_eq(decide(6, 5, -1, manual=false), Install(6))
assert_eq(decide(6, 5, 6, manual=false), Declined(6))
assert_eq(decide(6, 5, 6, manual=true), Install(6))
assert_eq(decide(7, 5, 6, manual=false), Install(7))
}
///|
test "throttling the automatic check" {
let h = 60L * 60L * 1000L
assert_true(should_check(7L * h, 0L, manual=false))
assert_true(!should_check(5L * h, 0L, manual=false))
assert_true(should_check(1L, 0L, manual=true))
}
View File
Whitespace-only changes.
+45
View File
@@ -0,0 +1,45 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/launcher/vdom"
// Values
pub fn cls_if(String, Bool) -> String
pub fn[M] el(String, key? : Int32, classes? : Array[String], attrs? : Array[(String, String)], props? : Array[(String, String)], style? : String, handlers? : Handlers[M], children? : Array[Node[M]]) -> Node[M]
pub fn[M] text(String) -> Node[M]
pub fn[M] to_html(Node[M], indent? : Int32) -> String
// Errors
// Types and methods
pub(all) struct Element[M] {
tag : String
key : Int32
classes : Array[String]
attrs : Array[(String, String)]
props : Array[(String, String)]
style : String
handlers : Handlers[M]
children : Array[Node[M]]
}
pub(all) struct Handlers[M] {
down : M?
tap : M?
press : M?
enter : M?
escape : M?
input : ((String) -> M)?
}
pub fn[M] Handlers::is_empty(Self[M]) -> Bool
pub fn[M] Handlers::none() -> Self[M]
pub(all) enum Node[M] {
Text(String)
El(Element[M])
}
// Type aliases
// Traits
+168
View File
@@ -0,0 +1,168 @@
///|
/// A tiny virtual DOM, pure data, generic over the message type `M` the handlers send.
/// The app's `view` builds a tree; a platform layer (web/) turns it into real DOM and
/// patches it by key. Because the tree is plain data, views are unit-tested by
/// rendering them to HTML text (`to_html`).
///|
/// What the user can do to an element. Pointer gestures are recognised by the gesture
/// package; the platform layer reports them against the chain of elements that have
/// handlers.
pub(all) struct Handlers[M] {
/// Pointer went down (acted on at once, e.g. grabbing a widget).
down : M?
/// A tap (down and up without a hold or a move).
tap : M?
/// A long press.
press : M?
/// Enter pressed in an input.
enter : M?
/// Escape pressed in an input.
escape : M?
/// An input's text changed.
input : ((String) -> M)?
}
///|
pub fn[M] Handlers::none() -> Handlers[M] {
{ down: None, tap: None, press: None, enter: None, escape: None, input: None }
}
///|
pub fn[M] Handlers::is_empty(self : Handlers[M]) -> Bool {
self.down is None &&
self.tap is None &&
self.press is None &&
self.enter is None &&
self.escape is None &&
self.input is None
}
///|
pub(all) enum Node[M] {
Text(String)
El(Element[M])
}
///|
pub(all) struct Element[M] {
tag : String
/// Identity among siblings for the keyed diff (0: none).
key : Int
classes : Array[String]
attrs : Array[(String, String)]
/// DOM properties (not attributes), e.g. an input's `value`.
props : Array[(String, String)]
style : String
handlers : Handlers[M]
children : Array[Node[M]]
}
///|
/// An element builder: `el("div", classes=["a"], children=[...])`.
pub fn[M] el(
tag : String,
key? : Int = 0,
classes? : Array[String] = [],
attrs? : Array[(String, String)] = [],
props? : Array[(String, String)] = [],
style? : String = "",
handlers? : Handlers[M] = Handlers::none(),
children? : Array[Node[M]] = [],
) -> Node[M] {
El({ tag, key, classes, attrs, props, style, handlers, children })
}
///|
pub fn[M] text(s : String) -> Node[M] {
Text(s)
}
///|
/// `cls("a", on=false)` is the empty class, so callers can build lists with `filter`.
pub fn cls_if(name : String, on : Bool) -> String {
if on { name } else { "" }
}
///|
fn escape_html(s : String) -> String {
let b = StringBuilder()
for c in s {
match c {
'&' => b.write_string("&amp;")
'<' => b.write_string("&lt;")
'>' => b.write_string("&gt;")
'"' => b.write_string("&quot;")
_ => b.write_char(c)
}
}
b.to_string()
}
///|
fn[M] handler_names(h : Handlers[M]) -> String {
let names : Array[String] = []
if h.down is Some(_) {
names.push("down")
}
if h.tap is Some(_) {
names.push("tap")
}
if h.press is Some(_) {
names.push("press")
}
if h.enter is Some(_) {
names.push("enter")
}
if h.escape is Some(_) {
names.push("escape")
}
if h.input is Some(_) {
names.push("input")
}
names.join(" ")
}
///|
/// Render a node as HTML text, one element per line (children indented), for tests.
/// Handlers show as an `on="tap press"` attribute.
pub fn[M] to_html(node : Node[M], indent? : Int = 0) -> String {
let pad = " ".repeat(indent)
match node {
Text(s) => pad + escape_html(s)
El(e) => {
let b = StringBuilder()
b.write_string("\{pad}<\{e.tag}")
let classes = e.classes.filter(fn(c) { c != "" })
if classes.length() > 0 {
b.write_string(" class=\"\{classes.join(" ")}\"")
}
for kv in e.attrs {
b.write_string(" \{kv.0}=\"\{escape_html(kv.1)}\"")
}
for kv in e.props {
b.write_string(" .\{kv.0}=\"\{escape_html(kv.1)}\"")
}
if e.style != "" {
b.write_string(" style=\"\{e.style}\"")
}
let on = handler_names(e.handlers)
if on != "" {
b.write_string(" on=\"\{on}\"")
}
b.write_string(">")
if e.children.length() == 1 && e.children[0] is Text(s) {
b.write_string("\{escape_html(s)}</\{e.tag}>")
} else if e.children.length() == 0 {
b.write_string("</\{e.tag}>")
} else {
for c in e.children {
b.write_string("\n")
b.write_string(to_html(c, indent=indent + 1))
}
b.write_string("\n\{pad}</\{e.tag}>")
}
b.to_string()
}
}
}
+18
View File
@@ -0,0 +1,18 @@
///|
test "to_html" {
let n : Node[Int] = el(
"div",
classes=["a", cls_if("b", false), cls_if("c", true)],
handlers={ ..Handlers::none(), tap: Some(1) },
children=[el("span", children=[text("x < y")]), text("tail")],
)
inspect(
to_html(n),
content=(
#|<div class="a c" on="tap">
#| <span>x &lt; y</span>
#| tail
#|</div>
),
)
}