ui_app

source of screens

1// Navigators (decisions/F11.md, F11c): stacks of screens whose2// top one shows, the others kept hidden as views are (views.alloy). Back3// comes from the program, the mouse, the keys and, on the web, the4// page's history, which the navigators on screen keep in step with their5// stacks.67import std::string;8import std::vector;9import std::option;10import std::math;11import std::map;12import std::hash as hash;13import std::process;14import pkg::alloy::window;15import pkg::alloy::draw;1617import pkg::alloy::ui;18import pkg::alloy::ui::store;19import pkg::alloy::ui::tree;20import pkg::alloy::ui::layout;21import pkg::alloy::ui::painting;22import pkg::alloy::ui::events;23import pkg::alloy::ui::widgets;24import pkg::alloy::ui::fields;25import pkg::alloy::ui::scrolling;26import pkg::alloy::ui::running;27import pkg::alloy::ui::timers;28import pkg::alloy::ui::layers;29import pkg::alloy::ui::motion;30import pkg::alloy::ui::transitions;31import pkg::alloy::ui::languages;32import pkg::alloy::ui::extensions;33import pkg::alloy::ui::views;34import ui_app;3536/* --- Navigators --- */3738// A navigator's routes, the top one shown, each with a serial telling a39// route replaced from the one before; those `back` took, which the40// browser's Forward brings back; its paths, and the element showing its41// screens.42pub type Routes<R> = struct {43    pub routes: Vector<R>,44    pub serials: Vector<u64>,45    pub forward: Vector<R>,46    pub serial: u64,47    pub paths: Option<Paths<R>>,48    pub screens: Option<Element>,49    // asked before going back from the top screen (`on_leaving`)50    pub leaving: Option<|=| (&var Ui, R) -> bool> = ::None,51};5253pub fn add<R>(self r: &var Routes<R>, route: R) {54    r.serial += 1;55    r.serials.push(r.serial);56    r.routes.push(move route);57}5859// What the Ui asks of its navigators, whatever their routes.60pub interface Navigable {61    fn alive(self: &, ui: &Ui) -> bool;62    fn screens_of(self: &, ui: &Ui) -> Option<Element>;63    fn stack_depth(self: &, ui: &Ui) -> u64;64    fn path_of(self: &, ui: &Ui) -> Option<String>;65    fn step_back(self: &, ui: &var Ui) -> bool;66    fn can_forward(self: &, ui: &Ui, path: Option<&[u8]>) -> bool;67    fn step_forward(self: &, ui: &var Ui, path: Option<&[u8]>);68}6970// The navigators made, an extension installed by the first: Back by the71// mouse and the keys, the page's history moving, and where the72// navigators on screen are in it after each event.73pub type Navigation : Extension = struct {74    pub navigators: Vector<*var Navigable> = Vector<*var Navigable>::empty(),75};7677// Alt+Left or Command+[ goes back a screen, before any element.78pub fn key(self n: &var Navigation, ui: &var Ui, key: &KeyEvent) -> bool {79    return key.pressed && goes_back(&key) && ui.go_back();80}8182pub fn event(self n: &var Navigation, ui: &var Ui, event: &Event) {83    match (event) {84        ::Button |&b| {85            // a page's browser goes back by the button itself, which86            // comes as Navigated87            if (b.button is ::Back && b.pressed && target() != "web-wasm32") {88                ui.go_back();89            }90        }91        ::Navigated |&entry| {92            ui.navigated(&entry);93        }94        else {}95    }96}9798pub fn show_in(self n: &var Navigation, ui: &var Ui, window: &var Window) {99    var entry = ui.history_entry();100    window.set_history(entry.depth, move entry.path);101}102103pub fn navigation(self ui: &var Ui) -> &var Navigation {104    if (ui.extension<Navigation>() is ::None) {105        ui.install(new Navigation {});106    }107    if (ui.extension_var<Navigation>() is ::Some |&var n|) {108        return &var n;109    }110    panic "pkg::alloy::ui: no navigators";111}112113// The navigators made, none before the first.114fn navigators(self ui: &Ui) -> &[*var Navigable] {115    if (ui.extension<Navigation>() is ::Some |&n|) {116        return &n.navigators.view();117    }118    return &[];119}120121pub fn make_navigator<R>(self ui: &var Ui, first: R, paths: Option<Paths<R>>) -> Navigator<R> {122    var routes = Routes<R> {123        .routes = Vector<R>::empty(),124        .serials = Vector<u64>::empty(),125        .forward = Vector<R>::empty(),126        .serial = 0,127        .paths = ::None,128        .screens = ::None129    };130    // a page opened at another path than the first screen's starts at131    // that path's screen, over the first132    var opened = Option<R>::None;133    if (paths is ::Some |&p| && ui.start_path.length() > 0) {134        if (p.path(&first) != ui.start_path) {135            opened = p.parse(&ui.start_path.view());136        }137        ui.start_path.clear();138    }139    routes.add(move first);140    if (opened is ::Some |move route|) {141        routes.add(move route);142    }143    routes.paths = move paths;144    const nav = Navigator<R> { .state = ui.signal(move routes) };145    ui.navigation().navigators.push(new nav);146    return nav;147}148149pub fn alive<R>(self nav: &Navigator<R>, ui: &Ui) -> bool {150    return ui.signal_alive(nav.state.index, nav.state.generation);151}152153pub fn screens_of<R>(self nav: &Navigator<R>, ui: &Ui) -> Option<Element> {154    return nav.state.peek(&ui).screens;155}156157pub fn stack_depth<R>(self nav: &Navigator<R>, ui: &Ui) -> u64 {158    return nav.state.peek(&ui).routes.length();159}160161pub fn path_of<R>(self nav: &Navigator<R>, ui: &Ui) -> Option<String> {162    const routes = &nav.state.peek(&ui);163    if (routes.paths is ::Some |&p|) {164        return ::Some(p.path(&routes.routes.last()));165    }166    return ::None;167}168169pub fn step_back<R>(self nav: &Navigator<R>, ui: &var Ui) -> bool => nav.back(&var ui);170171// Whether `on_leaving`, when set, lets the top screen go: asked with its172// route, the function taken out while it runs.173pub fn may_leave<R>(self nav: &Navigator<R>, ui: &var Ui) -> bool {174    var asking = move nav.state.peek_var(&var ui).leaving;175    nav.state.peek_var(&var ui).leaving = ::None;176    var leaves = true;177    if (asking is ::Some |&ask|) {178        leaves = ask(&var ui, copy nav.state.peek(&ui).routes.last());179    }180    if (nav.alive(&ui)) {181        nav.state.peek_var(&var ui).leaving = move asking;182    }183    return leaves;184}185186// Whether Forward has a screen to show: the path's, when given, or one187// `back` took.188pub fn can_forward<R>(self nav: &Navigator<R>, ui: &Ui, path: Option<&[u8]>) -> bool {189    const routes = &nav.state.peek(&ui);190    if (routes.paths is ::Some |&p| && path is ::Some |&at| && p.parse(&at) is ::Some) {191        return true;192    }193    return routes.forward.length() > 0;194}195196// Shows the path's screen, when given, or the last one `back` took.197pub fn step_forward<R>(self nav: &Navigator<R>, ui: &var Ui, path: Option<&[u8]>) {198    var parsed = Option<R>::None;199    if (nav.state.peek(&ui).paths is ::Some |&p| && path is ::Some |&at|) {200        parsed = p.parse(&at);201    }202    nav.state.update(&var ui, |move parsed| (routes: &var Routes<R>) {203        var later = routes.forward.pop();204        if (parsed is ::Some |move route|) {205            routes.add(move route);206        } else if (later is ::Some |move route|) {207            routes.add(move route);208        }209    });210}211212/* --- Screens --- */213214// A screen made: its route's serial, its view, and the element that215// had the focus as it was hidden, given it back when it shows again.216pub type ScreenSlot = struct {217    pub serial: u64,218    pub view: View,219    pub returns: Option<Element> = ::None,220    pub ring: bool = false,221};222223// What a screen stands on: the theme's page background over all the224// screen takes, so one sliding or fading in covers the one under it, as225// one taken off does the one it uncovers.226pub type Ground : Widget = struct {227    pub children: &[Element],228    pub sizing: Sizing, // its screen's share of a row's room229};230231// The screen within the limits it was given, unchanged.232pub fn layout(self g: &var Ground, arrange: &var Arrange, limits: Limits) -> Extent {233    var size = Extent::zero();234    for ([..arrange.count()]) |k| {235        const child = arrange.lay_out(k, limits);236        arrange.place(k, Point { .x = 0.0, .y = 0.0 });237        size.width = max(size.width, child.width);238        size.height = max(size.height, child.height);239    }240    return size;241}242243pub fn paint(self g: &Ground, look: &Look, paint: &var Paint) {244    paint.rect(245        Rect::sized(look.size.width, look.size.height),246        Fill::Color(look.theme.background)247    );248}249250pub fn renew(self g: &var Ground, next: Ground) -> Change => Change::Nothing;251252pub fn children(self g: &Ground) -> &[Element] => &g.children;253254pub fn sizing(self g: &Ground) -> Sizing => g.sizing;255256// Brings the screens up to the routes: those above the routes kept are257// freed, the new ones made, all but the top one hidden.258pub fn run_screens<R>(259    self ui: &var Ui,260    element: Element,261    nav: Navigator<R>,262    state: Signal<Vector<ScreenSlot>>,263    screen: &|&| (&var Ui, &R) -> Element264) {265    const serials = copy nav.state.get(&ui).serials;266    var slots = copy state.peek(&ui);267    var kept: u64 = 0;268    while (269        kept < serials.length()270        && kept < slots.length()271        && serials.get(kept) == slots.get(kept).serial272    ) {273        kept += 1;274    }275    if (kept == serials.length() && kept == slots.length()) {276        return;277    }278    const first = slots.length() == 0;279    // the screen shown, now under new ones, keeps what had the focus280    if (kept == slots.length() && kept > 0 && ui.focused is ::Some |f|) {281        const top = &var slots.get_var(kept - 1);282        if (ui.within(f, top.view.root)) {283            top.returns = ::Some(ui.element(f));284            top.ring = ui.focus_ring;285        }286    }287    // the screen shown, taken off, slides away over the one under288    const was_shown = if (289        !first && slots.length() > kept290    ) ::Some(slots.last().view.root) else Option<u32>::None;291    if (was_shown is ::Some |root|) {292        ui.pop_screen(root);293    }294    while (slots.length() > kept) {295        if (slots.pop() is ::Some |gone|) {296            ui.free_owner(gone.view.owner);297        }298    }299    const under = if (300        kept > 0 && was_shown is ::None301    ) ::Some(slots.get(kept - 1).view.root) else Option<u32>::None;302    const made = serials.length() > kept;303    for ([kept..serials.length()]) |k| {304        const route = copy nav.state.peek(&ui).routes.get(k);305        const owner = ui.new_owner(ui.owner);306        const root = ui.owned(owner, &|&screen, &route| (ui: &var Ui) -> Element {307            const made = screen(&var ui, &route);308            return ui.add(Ground {309                .children = &[made],310                .sizing = Sizing { .grow = ui.node_sizing(made.index).grow }311            });312        });313        ui.adopt(element.index, root);314        slots.push(ScreenSlot {315            .serial = serials.get(k),316            .view = View { .owner = owner, .root = root.index }317        });318    }319    const top = slots.length() - 1;320    for (slots.view(), [..slots.length()]) |&slot, k| {321        ui.set_view_hidden(slot.view, k != top);322    }323    // a screen pushed slides in over the one shown324    if (!first && made) {325        ui.push_screen(slots.get(top).view.root, under);326    }327    if (!first) {328        const shown = &slots.get(top);329        ui.focus_after = ::Some(ScreenFocus {330            .root = ui.element(shown.view.root),331            .element = if (made) ::None else shown.returns,332            .ring = if (made) ui.focus_ring else shown.ring333        });334    }335    state.peek_var(&var ui) = move slots;336    ui.mark_layout(element.index);337}338339/* --- Back, forward and the page's history --- */340341// How deep the navigator's screens are in the element tree, when it is342// on screen: alive, showing its screens, in no hidden view.343fn on_screen(self ui: &Ui, nav: &Navigable) -> Option<u64> {344    if (!nav.alive(&ui)) {345        return ::None;346    }347    const screens = if (nav.screens_of(&ui) is ::Some |e| && ui.exists(e)) e else {348        return ::None;349    };350    var depth: u64 = 0;351    var at: Option<u32> = ::Some(screens.index);352    while (at is ::Some |k|) {353        if (ui.node(k).hidden) {354            return ::None;355        }356        depth += 1;357        at = ui.node(k).parent;358    }359    return ::Some(depth);360}361362// Which way history moves.363type Way = enum {364    Back,365    Forward,366};367368// The deepest navigator on screen that can go the way.369fn deepest(self ui: &Ui, way: Way, path: Option<&[u8]>) -> Option<u64> {370    var found = Option<u64>::None;371    var deepest: u64 = 0;372    const navigators = &ui.navigators();373    for (navigators, [..navigators.length()]) |&nav, k| {374        if (ui.on_screen(&nav) is ::Some |depth| && depth >= deepest) {375            const can = match (way) {376                ::Back nav.stack_depth(&ui) > 1;377                ::Forward nav.can_forward(&ui, path);378            };379            if (can) {380                found = ::Some(k);381                deepest = depth;382            }383        }384    }385    return found;386}387388// Takes the top screen off the deepest navigator on screen that has389// more than one; whether one did.390pub fn go_back(self ui: &var Ui) -> bool {391    if (ui.deepest(Way::Back, ::None) is ::Some |k|) {392        const nav = new ui.navigators()[k];393        return nav.step_back(&var ui);394    }395    return false;396}397398// Shows the screen the browser's Forward goes to, the path's when given,399// in the deepest navigator on screen that has one; whether one did.400fn go_forward(self ui: &var Ui, path: Option<&[u8]>) -> bool {401    if (ui.deepest(Way::Forward, path) is ::Some |k|) {402        const nav = new ui.navigators()[k];403        nav.step_forward(&var ui, path);404        return true;405    }406    return false;407}408409// Where the navigators on screen are, as the page's history keeps it:410// one entry, and one more for each screen over a navigator's first; the411// path of the deepest navigator with paths. The navigators gone are412// forgotten.413pub fn history_entry(self ui: &var Ui) -> HistoryEntry {414    var k: u64 = 0;415    while (k < ui.navigation().navigators.length()) {416        if (ui.navigation().navigators.get(k).alive(&ui)) {417            k += 1;418        } else {419            ui.navigation().navigators.remove(k);420        }421    }422    var entry = HistoryEntry { .depth = 1, .path = String::empty() };423    var deepest: u64 = 0;424    for (ui.navigators()) |&nav| {425        if (ui.on_screen(&nav) is ::Some |depth|) {426            entry.depth += nav.stack_depth(&ui) - 1;427            if (depth >= deepest && nav.path_of(&ui) is ::Some |move path|) {428                entry.path = move path;429                deepest = depth;430            }431        }432    }433    return move entry;434}435436// The browser moved in the page's history: the navigators go back or437// forward until they are as deep, the last screen forward the entry's438// path's when it reads as one.439pub fn navigated(self ui: &var Ui, entry: &HistoryEntry) {440    var at = ui.history_entry().depth;441    while (at > entry.depth && ui.go_back()) {442        ui.flush();443        at = ui.history_entry().depth;444    }445    while (at < entry.depth) {446        const path: Option<&[u8]> = if (at + 1 == entry.depth) ::Some(447            &entry.path.view()448        ) else ::None;449        if (!ui.go_forward(path)) {450            break;451        }452        ui.flush();453        at = ui.history_entry().depth;454    }455}456457// Whether the key goes back: Alt and Left, Command and [ on macOS.458pub fn goes_back(k: &KeyEvent) -> bool {459    const m = &k.modifiers;460    if (target() == "macos-arm64" || target() == "macos-x86_64") {461        const bracket = if (k.key is ::Character |c|) c == '[' to u32 else false;462        return bracket && m.super && !m.shift && !m.alt && !m.control;463    }464    return k.key is ::Left && m.alt && !m.shift && !m.control && !m.super;465}466467/* --- Screens moving --- */468469// A screen pushed over the one shown slides in from the end over it,470// which stays shown until covered.471pub fn push_screen(self ui: &var Ui, shown: u32, under: Option<u32>) {472    if (!ui.drawn) {473        return;474    }475    ui.use_motion();476    const motion = Motion { .duration = ui.theme.motion.long };477    const entry = if (ui.fit(Pose { .x = ui.viewport.width }, motion) is ::Some |e|) e else Fitted {478        .pose = Pose { .opacity = 0.0 },479        .motion = Motion { .duration = ui.theme.motion.short }480    };481    ui.move_element(ui.element(shown), entry.pose, REST, entry.motion, Finish::Stay);482    if (under is ::Some |u|) {483        ui.move_element(ui.element(u), REST, REST, entry.motion, Finish::Hide);484    }485}486487// The screen shown taken off slides out to the end, over the one under.488pub fn pop_screen(self ui: &var Ui, shown: u32) {489    ui.keep_going(490        shown,491        Pose { .x = ui.viewport.width },492        Motion { .duration = ui.theme.motion.long }493    );494}