ui

source of layers

1// Layers (decisions/F11.md, F11a): element trees of their own2// over the window's content, in the order they open: dialogs, popups,3// menus, tooltips and toasts. A layer is a host element covering the4// window, drawing the scrim of a modal one, holding a panel placed by5// the layer's `Place` around the element its view made. The topmost6// takes the pointer first and a modal one keeps the pointer and the7// keyboard from what is below it. What a layer's view made belongs to8// an owner of the layer's, under the owner of the element whose handler9// opened it, and goes when the layer closes.1011import std::string;12import std::vector;13import std::option;14import std::math;15import pkg::alloy::window;16import pkg::alloy::draw;1718import ui;19import store;20import tree;21import layout;22import events;23import scrolling;24import transitions;25import timers;2627// What a layer keeps from the window's edges.28const MARGIN: f32 = 16.0;2930// Between an element and what is placed below, above or beside it.31const GAP: f32 = 4.0;3233// A layer open: its overlay, the owner of what it made, its host and34// panel, the element given the focus back when it closes, and its35// anchor's frame as it was last placed by.36exp type LayerSlot = struct {37    pub id: u32,38    exp overlay: Overlay,39    exp owner: u32,40    exp host: Element,41    exp panel: u32,42    pub returns: Option<Element> = ::None,43    exp ring: bool = false,44    pub anchor: Option<Rect> = ::None,45};4647// A layer's root, over the whole window: the scrim of a modal layer, and48// its one child, the panel, placed by `place`.49pub type LayerHost : Widget = struct {50    pub children: &[Element],51    pub place: Place,52    pub modal: bool,53};5455// What holds a layer's view: the theme's surface, rounded and shadowed,56// when `drawn`; what a screen reader calls the layer.57pub type Panel : Widget = struct {58    pub children: &[Element],59    pub role: LayerRole,60    pub label: String,61    pub modal: bool,62    pub drawn: bool,63};6465// What the Ui calls of the layers once the first opens: a press outside66// them, Escape, a release after a press that opened a popup, a screen67// reader dismissing one, and after each update.68pub type LayerCalls : Extension = struct {};6970pub fn pressed(self l: &var LayerCalls, ui: &var Ui, at: Point) -> bool => ui.press_outside(at);7172pub fn released(self l: &var LayerCalls, ui: &var Ui, at: Point, under: Option<u32>) {73    ui.release_on_popup(at, under);74}7576pub fn escaped(self l: &var LayerCalls, ui: &var Ui) -> bool {77    return ui.layers.length() > 0 && ui.escape_layer();78}7980pub fn dismissed(self l: &var LayerCalls, ui: &var Ui, index: u32) {81    if (ui.layer_of(index) is ::Some |k|) {82        ui.close_at(k);83    }84}8586pub fn updated(self l: &var LayerCalls, ui: &var Ui) {87    if (ui.layers.length() > 0) {88        ui.follow_layers();89        ui.flush();90        ui.lay_out_all();91    }92}9394// What a widget holding a popup closes once a binding gives it other95// options: a Select's list, a DatePicker's calendar.96exp interface Popup {97    fn take_closing(self: &var) -> Option<Layer>;98}99100/* --- Opening and closing --- */101102exp fn open_layer(103    self ui: &var Ui,104    overlay: Overlay,105    view: |=| (&var Ui, Layer) -> Element106) -> Layer {107    if (ui.extension<LayerCalls>() is ::None) {108        ui.install(new LayerCalls {});109    }110    ui.layer_serial += 1;111    const layer = Layer { .id = ui.layer_serial };112    // what has the focus before the view may give it to one of its own113    const before = ui.focused;114    const ring = ui.focus_ring;115    const above = if (ui.handling is ::Some |h|) ui.owner_of(h) else 0;116    const owner = ui.new_owner(above);117    const content = ui.owned(118        owner,119        &|&view,120        layer| (ui: &var Ui) -> Element => view(&var ui, layer)121    );122    const saved = ui.owner;123    ui.owner = owner;124    const panel = ui.add(Panel {125        .children = &[content],126        .role = overlay.role,127        .label = copy overlay.label,128        .modal = overlay.modal,129        .drawn = overlay.panel130    });131    const host = ui.add(LayerHost {132        .children = &[panel],133        .place = overlay.place,134        .modal = overlay.modal135    });136    ui.owner = saved;137    var slot = LayerSlot {138        .id = layer.id,139        .overlay = move overlay,140        .owner = owner,141        .host = host,142        .panel = panel.index143    };144    const focused_inside = if (ui.focused is ::Some |f|) ui.within(f, host.index) else false;145    if (146        slot.overlay.keyboard147        && before is ::Some |f|148        && ui.node(f).alive149        && !ui.within(f, host.index)150    ) {151        slot.ring = ring;152        slot.returns = ::Some(ui.element(f));153    }154    ui.layers.push(move slot);155    if (ui.layers.last().overlay.keyboard && !focused_inside) {156        // the first element taking the focus, or none in a modal layer157        var order = Vector<u32>::empty();158        ui.collect_focusable(host.index, &var order);159        if (order.try_get(0) is ::Some |&first|) {160            ui.focus_node(::Some(first), ui.focus_ring);161        } else if (ui.layers.last().overlay.modal) {162            ui.focus_node(::None, false);163        }164    }165    ui.enter_layer(ui.layers.length() - 1);166    ui.mark_layout(host.index);167    ui.paint_pending = true;168    ui.access_stale = true;169    return layer;170}171172// The owner whose element the node is, the app's when none.173exp fn owner_of(self ui: &Ui, index: u32) -> u32 {174    for (ui.owners.view(), [..ui.owners.length()]) |&owner, k| {175        if (owner.alive) {176            for (owner.nodes.view()) |n| {177                if (n == index) {178                    return k to u32;179                }180            }181        }182    }183    return 0;184}185186// Whether the node is the other or under it.187exp fn within(self ui: &Ui, index: u32, ancestor: u32) -> bool {188    var at: Option<u32> = ::Some(index);189    while (at is ::Some |k|) {190        if (k == ancestor) {191            return true;192        }193        at = ui.node(k).parent;194    }195    return false;196}197198// Where the layer is among those open.199exp fn layer_index(self ui: &Ui, layer: Layer) -> Option<u64> {200    for (ui.layers.view(), [..ui.layers.length()]) |&slot, k| {201        if (slot.id == layer.id) {202            return ::Some(k);203        }204    }205    return ::None;206}207208// The layer holding the node, none for the content's.209exp fn layer_of(self ui: &Ui, index: u32) -> Option<u64> {210    var top = index;211    while (ui.node(top).parent is ::Some |p|) {212        top = p;213    }214    for (ui.layers.view(), [..ui.layers.length()]) |&slot, k| {215        if (slot.host.index == top) {216            return ::Some(k);217        }218    }219    return ::None;220}221222// Closes the layer at the index, with those opened from what it made,223// giving the focus back when it was inside, then calls its `on_close`.224exp fn close_at(self ui: &var Ui, k: u64) {225    var slot = ui.layers.remove(k);226    const had_focus = if (ui.focused is ::Some |f|) ui.within(f, slot.host.index) else false;227    ui.leave_layer(&slot);228    ui.free_owner(slot.owner);229    ui.prune_layers();230    if (had_focus || ui.focused is ::None) {231        if (slot.returns is ::Some |back| && ui.exists(back)) {232            ui.focus_node(::Some(back.index), slot.ring);233        }234    }235    ui.paint_pending = true;236    ui.access_stale = true;237    const close = &slot.overlay.on_close;238    close(&var ui);239}240241// Forgets the layers whose owner went, as a row's when the row goes.242pub fn prune_layers(self ui: &var Ui) {243    var k: u64 = 0;244    while (k < ui.layers.length()) {245        if (ui.exists(ui.layers.get(k).host)) {246            k += 1;247        } else {248            const slot = ui.layers.remove(k);249            if (ui.focused is ::None && slot.returns is ::Some |back| && ui.exists(back)) {250                ui.focus_node(::Some(back.index), slot.ring);251            }252        }253    }254}255256// The layers whose owner went forgotten, those whose anchor went or left257// the view closed, and those whose anchor moved placed again.258pub fn follow_layers(self ui: &var Ui) {259    ui.prune_layers();260    var k: u64 = 0;261    while (k < ui.layers.length()) {262        const anchor = ui.layers.get(k).overlay.place.anchor();263        if (anchor is ::Some |a|) {264            if (!ui.exists(a) || !ui.in_view(a.index)) {265                ui.close_at(k);266                continue;267            }268            const frame = ui.frame_of(a);269            if (ui.layers.get(k).anchor != ::Some(frame)) {270                ui.layers.get_var(k).anchor = ::Some(frame);271                ui.mark_layout(ui.layers.get(k).host.index);272            }273        }274        k += 1;275    }276}277278// The element a place is beside.279pub fn anchor(self place: &Place) -> Option<Element> => match (place) {280    ::Below, ::Above, ::After |e| ::Some(e);281    else ::None;282};283284// Whether some of the element shows within the elements clipping it,285// in no hidden view.286fn in_view(self ui: &Ui, index: u32) -> bool {287    if (ui.node(index).hidden) {288        return false;289    }290    var area = ui.frame_of(ui.element(index));291    var at = ui.node(index).parent;292    while (at is ::Some |k|) {293        const node = &ui.node(k);294        if (node.hidden) {295            return false;296        }297        if (!node.transparent && node.widget is ::Some |&widget| && widget.clips()) {298            area = area.intersection(&ui.frame_of(ui.element(k)));299            if (area.is_empty()) {300                return false;301            }302        }303        at = node.parent;304    }305    return true;306}307308// Whether the rectangle holds the point.309exp fn holds(area: &Rect, p: Point) -> bool {310    return p.x >= area.x311        && p.y >= area.y312        && p.x < area.x + area.width313        && p.y < area.y + area.height;314}315316// The topmost modal layer, if any.317pub fn top_modal(self ui: &Ui) -> Option<u64> {318    var k = ui.layers.length();319    while (k > 0) {320        k -= 1;321        if (ui.layers.get(k).overlay.modal) {322            return ::Some(k);323        }324    }325    return ::None;326}327328// The panel's frame in the window.329exp fn panel_frame(self ui: &Ui, k: u64) -> Rect {330    return ui.frame_of(ui.element(ui.layers.get(k).panel));331}332333/* --- The pointer and the keyboard --- */334335// A press that opened a popup (a menu, a list), whose release on an item336// of it, away from where it was pressed, chooses that item.337pub type PopupPress = struct {338    pub layer: Layer,339    pub at: Point,340};341342// How far the pointer moves from a press opening a popup before a343// release chooses.344const DRAGGED: f32 = 4.0;345346// The layer opened in a press's handler, which a drag to one of its347// items and a release there chooses, as native menus and lists allow.348exp fn press_opened(self ui: &var Ui, layer: Layer) {349    if (ui.pointer_down is ::Some |at|) {350        ui.popup_press = ::Some(PopupPress { .layer = layer, .at = at });351    }352}353354// The button released at the point, over the element: an element of the355// popup the press opened is clicked there, once the pointer moved away356// from the press.357fn release_on_popup(self ui: &var Ui, at: Point, under: Option<u32>) {358    const press = if (ui.popup_press is ::Some |p|) p else {359        return;360    };361    ui.popup_press = ::None;362    const moved = abs(at.x - press.at.x) > DRAGGED || abs(at.y - press.at.y) > DRAGGED;363    if (364        moved365        && under is ::Some |index|366        && ui.layer_of(index) is ::Some |k|367        && ui.layers.get(k).id == press.layer.id368    ) {369        ui.dispatch(index, Input::Click(at));370    }371}372373// Closes, for a press at the point, the passive layers and those it374// falls outside of down to the first holding it or modal; whether one375// taking the pointer closed, which the press then goes no further than.376pub fn press_outside(self ui: &var Ui, at: Point) -> bool {377    var closed = false;378    var k = ui.layers.length();379    while (k > 0) {380        k -= 1;381        if (k >= ui.layers.length()) {382            continue;383        }384        const overlay = &ui.layers.get(k).overlay;385        if (overlay.passive) {386            ui.close_at(k);387            continue;388        }389        if (holds(&ui.panel_frame(k), at) || overlay.modal) {390            break;391        }392        if (overlay.outside) {393            ui.close_at(k);394            closed = true;395        }396    }397    return closed;398}399400// Escape no element took: a tooltip goes first, else the layer holding401// the focus when Escape closes it, else the topmost Escape closes;402// whether one did.403pub fn escape_layer(self ui: &var Ui) -> bool {404    var k = ui.layers.length();405    while (k > 0) {406        k -= 1;407        if (ui.layers.get(k).overlay.passive) {408            ui.close_at(k);409            return true;410        }411    }412    var target = Option<u64>::None;413    if (ui.focused is ::Some |f|) {414        target = ui.layer_of(f);415    }416    if (target is ::None) {417        // the topmost Escape closes418        var k = ui.layers.length();419        while (k > 0 && target is ::None) {420            k -= 1;421            if (ui.layers.get(k).overlay.escape) {422                target = ::Some(k);423            }424        }425    }426    if (target is ::Some |t| && ui.layers.get(t).overlay.escape) {427        ui.close_at(t);428        return true;429    }430    return false;431}432433// The roots Tab goes through, in order: those of a modal layer and the434// layers over it, else the content's and every layer's; tooltips never.435pub fn focus_roots(self ui: &Ui) -> Vector<u32> {436    var roots = Vector<u32>::empty();437    var first: u64 = 0;438    if (ui.top_modal() is ::Some |m|) {439        first = m;440    } else if (ui.root is ::Some |r|) {441        roots.push(r);442    }443    for (ui.layers.view()[first..]) |&slot| {444        if (!slot.overlay.passive) {445            roots.push(slot.host.index);446        }447    }448    return move roots;449}450451// The deepest element of the kind under the point in the layers, the452// topmost first; whether the search ended there, for a point inside a453// panel or a modal layer.454pub fn hit_layers(self ui: &Ui, at: Point, kind: Hit) -> Option<Option<u32>> {455    var k = ui.layers.length();456    while (k > 0) {457        k -= 1;458        const slot = &ui.layers.get(k);459        if (slot.overlay.passive) {460            continue;461        }462        const found = ui.hit_node(slot.panel, at.x, at.y, kind);463        if (found is ::Some) {464            return ::Some(found);465        }466        if (holds(&ui.panel_frame(k), at)) {467            return ::Some(::None);468        }469        if (slot.overlay.modal) {470            return ::Some(if (kind is ::Any) ::Some(slot.host.index) else ::None);471        }472    }473    return ::None;474}475476/* --- The host and the panel --- */477478pub fn layout(self h: &var LayerHost, arrange: &var Arrange, limits: Limits) -> Extent {479    const window = Extent { .width = limits.max_width, .height = limits.max_height };480    const size = arrange.lay_out(481        0,482        Limits::loose(max(window.width - 2.0 * MARGIN, 0.0), max(window.height - 2.0 * MARGIN, 0.0))483    );484    // placed as its anchor reads, else as the Ui does485    var direction = arrange.direction();486    var anchor = Option<Rect>::None;487    if (h.place.anchor() is ::Some |a| && arrange.ui.exists(a)) {488        anchor = ::Some(arrange.ui.frame_of(a));489        direction = arrange.ui.node(a.index).direction;490    }491    arrange.place(0, placed(&h.place, size, window, anchor, direction));492    return window;493}494495// What a layer's host places in window coordinates, mirroring by itself.496pub fn mirrors_children(self h: &LayerHost) -> bool => false;497498// Where a panel of the size goes in the window, by the place, the499// anchor's frame and the direction it reads in: on the other side when500// there is no room, and within the window less its margin. Right to left501// a panel below or above aligns its right edge with the anchor's, one502// after it goes to its left, one at a point reaches left of it, and a503// corner's start is on the right.504exp fn placed(505    place: &Place,506    size: Extent,507    window: Extent,508    anchor: Option<Rect>,509    direction: LayoutDirection510) -> Point {511    const rtl = direction is ::RightToLeft;512    const left = MARGIN;513    const top = MARGIN;514    const right = window.width - MARGIN - size.width; // the furthest x515    const bottom = window.height - MARGIN - size.height;516    var x = (window.width - size.width) / 2.0;517    var y = (window.height - size.height) / 2.0;518    match (place) {519        ::Center {}520        ::Below, ::Above {521            if (anchor is ::Some |a|) {522                x = if (rtl) a.x + a.width - size.width else a.x;523                const below = a.y + a.height + GAP;524                const above = a.y - GAP - size.height;525                const room_below = below <= bottom;526                const room_above = above >= top;527                const down = if (place is ::Below) room_below || !room_above else !room_above528                    && room_below;529                y = if (down) below else above;530            }531        }532        ::After {533            if (anchor is ::Some |a|) {534                y = a.y;535                if (rtl) {536                    x = a.x - size.width;537                    if (x < left && a.x + a.width <= right) {538                        x = a.x + a.width;539                    }540                } else {541                    x = a.x + a.width;542                    if (x > right && a.x - size.width >= left) {543                        x = a.x - size.width;544                    }545                }546            }547        }548        ::At |p| {549            y = p.y;550            if (rtl) {551                x = p.x - size.width;552                if (x < left && p.x <= right) {553                    x = p.x;554                }555            } else {556                x = p.x;557                if (x > right && p.x - size.width >= left) {558                    x = p.x - size.width;559                }560            }561            if (y > bottom && p.y - size.height >= top) {562                y = p.y - size.height;563            }564        }565        ::Corner |corner| {566            const start = corner is ::TopStart || corner is ::BottomStart;567            const upper = corner is ::TopStart || corner is ::TopEnd;568            x = if (start != rtl) left else right;569            y = if (upper) top else bottom;570        }571    }572    return Point { .x = max(min(x, right), left), .y = max(min(y, bottom), top) };573}574575exp fn paint(self h: &LayerHost, look: &Look, paint: &var Paint) {576    if (h.modal) {577        paint.rect(Rect::sized(look.size.width, look.size.height), Fill::Color(look.theme.scrim));578    }579}580581pub fn children(self h: &LayerHost) -> &[Element] => &h.children;582583exp fn renew(self h: &var LayerHost, next: LayerHost) -> Change => Change::Nothing;584585exp fn paint(self p: &Panel, look: &Look, paint: &var Paint) {586    if (!p.drawn) {587        return;588    }589    const theme = &look.theme;590    const area = Rect::sized(look.size.width, look.size.height);591    paint.shadow(area, Radii::all(theme.radius), theme.shadow);592    paint.rounded_rect(area, Radii::all(theme.radius), Fill::Color(theme.surface));593    paint.border(area, Radii::all(theme.radius), 1.0, theme.border);594}595596pub fn children(self p: &Panel) -> &[Element] => &p.children;597598exp fn renew(self p: &var Panel, next: Panel) -> Change => Change::Nothing;599600pub fn semantics(self p: &Panel) -> Semantics => Semantics {601    .role = match (p.role) {602        // a popup of no name, a Select's list, stands for nothing itself603        ::Plain if (p.label.length() > 0) Role::Group else Role::Unknown;604        ::Dialog Role::Dialog;605        ::Alert Role::Alert;606        ::Menu Role::Menu;607        ::Tooltip Role::Tooltip;608    },609    .label = copy p.label,610    .modal = p.modal611};