ui_controls

source of toasts

1// Toasts (decisions/F11.md, F11a): short news in one layer in2// the window's bottom end corner, newest at the bottom, three at most3// with the rest waiting, each going after its duration, its time paused4// while the pointer is over it or the focus is in it. An error stays5// until closed, and so does a toast with an action while a screen reader6// reads; each is spoken as it shows (`announce`) rather than read from7// the tree, which still holds its buttons, Tab reaching them after the8// content.910import std::string;11import std::vector;12import std::option;13import std::time;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_controls;3536const SHOWN_AT_MOST: u64 = 3;3738// A toast shown or waiting, by its number.39pub type ShownToast = struct {40    pub id: u64,41    pub toast: Toast,42};4344// How long a shown toast has left: running since a time, or paused.45pub type ToastClock = struct {46    pub id: u64,47    pub left: u64, // nanoseconds48    pub since: Option<u64>, // when it last started running49    pub card: Option<Element>,50    pub sticky: bool,51};5253pub type ToastState = struct {54    pub shown: Option<Signal<Vector<ShownToast>>> = ::None,55    pub clocks: Vector<ToastClock> = Vector<ToastClock>::empty(),56    pub waiting: Vector<ShownToast> = Vector<ShownToast>::empty(),57    pub layer: Option<Layer> = ::None,58    pub timer: Option<Timer> = ::None,59    pub timer_at: u64 = 0,60    pub count: u64 = 0,61};6263// The toasts' state, an extension installed by the first toast, so a64// program showing none carries none of its code: what it keeps, and in a65// replay each toast's text as it showed.66pub type Toasts : Extension = struct {67    pub state: ToastState = ToastState {},68    pub recorded: Vector<String> = Vector<String>::empty(),69};7071// Each update while toasts show, their times.72pub fn updating(self t: &var Toasts, ui: &var Ui) {73    if (t.state.layer is ::Some) {74        ui.tick_toasts();75    }76}7778pub fn replayed(self t: &var Toasts, ui: &var Ui, replayed: &var Replayed) {79    replayed.toasts = move t.recorded;80    t.recorded = Vector<String>::empty();81}8283fn toasts(self ui: &var Ui) -> &var Toasts {84    if (ui.extension<Toasts>() is ::None) {85        ui.install(new Toasts {});86    }87    if (ui.extension_var<Toasts>() is ::Some |&var t|) {88        return &var t;89    }90    panic "pkg::alloy::ui: no toasts";91}9293pub fn toast_state(self ui: &var Ui) -> &var ToastState => &var ui.toasts().state;9495pub fn show_toast(self ui: &var Ui, toast: Toast) {96    ui.toast_state().count += 1;97    var entry = ShownToast { .id = ui.toast_state().count, .toast = move toast };98    if (ui.toast_state().clocks.length() >= SHOWN_AT_MOST) {99        ui.toast_state().waiting.push(move entry);100        return;101    }102    ui.reveal_toast(move entry);103}104105fn reveal_toast(self ui: &var Ui, shown_entry: ShownToast) {106    var entry = move shown_entry;107    const t = &entry.toast;108    const sticky = t.kind is ::Error || (t.action is ::Some && ui.access_on);109    ui.toast_state().clocks.push(ToastClock {110        .id = entry.id,111        .left = t.duration.nanoseconds,112        .since = ::Some(ui.time.nanoseconds),113        .card = ::None,114        .sticky = sticky115    });116    ui.announce(copy t.text, t.kind is ::Error);117    if (ui.replaying) {118        ui.toasts().recorded.push(copy t.text);119    }120    if (ui.toast_state().shown is ::None) {121        // the app's, kept from one showing of the toasts to the next122        const saved_owner = ui.owner;123        ui.owner = 0;124        ui.toast_state().shown = ::Some(ui.signal(Vector<ShownToast>::empty()));125        ui.owner = saved_owner;126    }127    const shown = if (ui.toast_state().shown is ::Some |s|) s else {128        return;129    };130    if (ui.toast_state().layer is ::None) {131        shown.peek_var(&var ui).clear();132        shown.peek_var(&var ui).push(move entry);133        const saved = ui.handling;134        ui.handling = ::None;135        ui.toast_state().layer = ::Some(ui.open_layer(Overlay {136            .place = Place::Corner(Corner::BottomEnd),137            .label = String::from(&"Notifications"),138            .outside = false,139            .escape = false,140            .panel = false,141            .keyboard = false142        }, |shown| (ui: &var Ui, layer: Layer) -> Element {143            return ui.add(Column {144                .gap = 8.0,145                .align = Alignment::End,146                .children = &[ui.each(shown, (t) => t.id, (ui, t) => toast_card(&var ui, t))],147            });148        }));149        ui.handling = saved;150    } else {151        shown.update(152            &var ui,153            |move entry| (list: &var Vector<ShownToast>) => list.push(move entry)154        );155    }156}157158// The card of a toast: its kind's mark, its text, its action and a159// button closing it.160fn toast_card(ui: &var Ui, item: Signal<ShownToast>) -> Element {161    const id = item.peek(&ui).id;162    const toast = &item.peek(&ui).toast;163    var parts = Vector<Element>::empty();164    const mark: Option<Ink> = match (toast.kind) {165        ::Info ::None;166        ::Success ::Some(Ink::rgb(0.13, 0.6, 0.33));167        ::Error ::Some(Ink::rgb(0.86, 0.2, 0.18));168    };169    if (mark is ::Some |ink|) {170        parts.push(ui.add(Stack {171            .background = ink,172            .radius = 4.0,173            .sizing = { .width = ::Some(8.0), .height = ::Some(8.0) },174        }));175    }176    parts.push(ui.add(Text { .text = copy toast.text, .sizing = { .grow = 1.0 } }));177    if (toast.action is ::Some |&action|) {178        var pressed = copy action.on_press;179        parts.push(ui.add(Button::plain(&action.label.view(), |move pressed, id| (ui: &var Ui) {180            pressed(&var ui);181            ui.dismiss_toast(id);182        })));183    }184    parts.push(ui.add(Button {185        .label = String::from(&"×"),186        .accessible = String::from(&"Close"),187        .variant = ButtonVariant::Plain,188        .padding = Padding::symmetric(8.0, 4.0),189        .on_press = (ui) => ui.dismiss_toast(id),190    }));191    const card = ui.add(Row {192        .gap = 10.0,193        .align = Alignment::Center,194        .padding = Padding { .start = 14.0, .top = 8.0, .end = 6.0, .bottom = 8.0 },195        .background = Ink::Surface,196        .border = Ink::Border,197        .radius = ui.theme.radius,198        .sizing = { .min_width = 240.0, .max_width = 380.0 },199        .children = &parts.view(),200    });201    for (ui.toast_state().clocks.items()) |&var clock| {202        if (clock.id == id) {203            clock.card = ::Some(card);204        }205    }206    // up from the edge, and down to where those going left room207    return ui.transition(card, Transition {208        .slide = Point { .x = 0.0, .y = 16.0 },209        .moves = true,210        .motion = Motion { .duration = ui.theme.motion.medium },211    });212}213214// Takes the toast away, showing the next waiting.215pub fn dismiss_toast(self ui: &var Ui, id: u64) {216    for ([..ui.toast_state().clocks.length()]) |k| {217        if (ui.toast_state().clocks.get(k).id == id) {218            ui.toast_state().clocks.remove(k);219            break;220        }221    }222    if (ui.toast_state().shown is ::Some |shown|) {223        shown.update(&var ui, (list: &var Vector<ShownToast>) {224            for ([..list.length()]) |k| {225                if (list.get(k).id == id) {226                    list.remove(k);227                    break;228                }229            }230        });231    }232    while (233        ui.toast_state().clocks.length() < SHOWN_AT_MOST234        && ui.toast_state().waiting.length() > 0235    ) {236        var next = ui.toast_state().waiting.remove(0);237        ui.reveal_toast(move next);238    }239    if (ui.toast_state().clocks.length() == 0) {240        if (ui.toast_state().layer is ::Some |layer|) {241            ui.close(layer);242        }243        if (ui.toast_state().timer is ::Some |timer|) {244            ui.cancel(timer);245        }246        ui.forget_toasts();247    }248}249250fn forget_toasts(self ui: &var Ui) {251    var kept = ToastState { .shown = ui.toast_state().shown, .count = ui.toast_state().count };252    ui.toast_state() = move kept;253}254255// Pauses the toasts the pointer or the focus is on and runs the others,256// takes those whose time is up away, and sets the timer for the next.257pub fn tick_toasts(self ui: &var Ui) {258    if (ui.toast_state().layer is ::Some |layer| && ui.layer_index(layer) is ::None) {259        // its owner went260        ui.forget_toasts();261        return;262    }263    const now = ui.time.nanoseconds;264    var gone = Vector<u64>::empty();265    var next = Option<u64>::None;266    for ([..ui.toast_state().clocks.length()]) |k| {267        const clock = copy ui.toast_state().clocks.get(k);268        var paused = clock.sticky;269        if (clock.card is ::Some |card| && ui.exists(card)) {270            const frame = ui.frame_of(card);271            if (ui.pointer is ::Some |p| && holds(&frame, p)) {272                paused = true;273            }274            if (ui.focused is ::Some |f| && ui.within(f, card.index)) {275                paused = true;276            }277        }278        const c = &var ui.toast_state().clocks.get_var(k);279        if (c.since is ::Some |since|) {280            const ran = if (now > since) now - since else 0;281            c.left = if (ran >= c.left) 0 else c.left - ran;282            c.since = if (paused) ::None else ::Some(now);283        } else if (!paused) {284            c.since = ::Some(now);285        }286        if (c.left == 0 && !clock.sticky) {287            gone.push(c.id);288        } else if (c.since is ::Some) {289            const at = now + c.left;290            next = ::Some(if (next is ::Some |n| && n < at) n else at);291        }292    }293    for (gone.view()) |id| {294        ui.dismiss_toast(id);295    }296    if (gone.length() > 0) {297        if (ui.toast_state().clocks.length() > 0) {298            ui.tick_toasts();299        }300        return;301    }302    const wanted = if (next is ::Some |at|) at else 0;303    if (ui.toast_state().timer is ::Some && ui.toast_state().timer_at == wanted) {304        return;305    }306    if (ui.toast_state().timer is ::Some |timer|) {307        ui.cancel(timer);308        ui.toast_state().timer = ::None;309    }310    if (next is ::Some |at|) {311        ui.toast_state().timer = ::Some(ui.new_toast_timer(at));312        ui.toast_state().timer_at = at;313    }314}315316fn new_toast_timer(self ui: &var Ui, at: u64) -> Timer {317    const saved = ui.owner;318    ui.owner = 0;319    const delay = Duration::from_nanoseconds(320        if (at > ui.time.nanoseconds) at - ui.time.nanoseconds else 0321    );322    const timer = ui.after(delay, (ui) {323        ui.toast_state().timer = ::None;324        ui.tick_toasts();325    });326    ui.owner = saved;327    return timer;328}