crcbl-ui 0.2.0

Crucible immediate-mode GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! The pop-up layer: a block anchored to a node, drawn over the whole tree.
//!
//! # Opening one
//!
//! Any widget opens a pop-up by naming the node it hangs from:
//! [`Ui::open_popup`] with that node's key — or [`Ui::open_popup_at`], which
//! says where it goes against that node — then, that frame and every frame it
//! stays open, [`Ui::popup`] with the same key and a closure that builds what
//! it holds. [`Ui::popup`] builds nothing and answers `None` while the pop-up
//! is closed, so the call can sit in a widget unconditionally. The open
//! pop-ups are a stack: one opened while another is open (from a node inside
//! it, as a submenu is) goes on top.
//!
//! **An open pop-up the frame did not build is closed at [`Ui::layout`]**, and
//! so is one whose anchor the frame did not build, with every pop-up above
//! either. A pop-up is the tree's rule applied to a layer: what a frame does
//! not build, it does not keep.
//!
//! # Where it is drawn
//!
//! A pop-up is a **root of its own**: [`Ui::popup`] builds it outside every
//! block that is open, keyed by its anchor ([`Ui::popup_key`]), and laid out
//! in the space the tree was given. Its border box goes where its
//! [`Placement`] says, flipping at the viewport's edge:
//!
//! * [`Placement::Below`], a drop-down's: below its anchor, lined up with the
//!   anchor's left edge, flipped to sit above the anchor when it would run
//!   past the bottom of the viewport and there is more room above.
//! * [`Placement::Beside`], a submenu's: right of its anchor, lined up with
//!   the anchor's top edge, flipped to its left when it would run past the
//!   right edge and there is more room on the left.
//! * [`Placement::At`], a context menu's: its top-left corner at a point,
//!   flipped to end at the point on each axis where it would run past the far
//!   edge and there is more room before the point — so a menu opened at the
//!   bottom right hangs up and to the left of the pointer.
//!
//! It is then shifted the least that keeps it inside the viewport on both
//! axes — its top-left corner wins when it is larger than the viewport, as
//! one built before the first layout can be.
//! The viewport is the space [`Ui::layout`] was given, from its origin; an
//! axis laid out under content-sized space bounds nothing. A pop-up's own
//! margin and offsets do not move it.
//!
//! **A pop-up is never taller or wider than the viewport less
//! [`POPUP_MARGIN`]**: its root's `max-height` and `max-width` are that, and
//! `default.css` makes every `popup` `overflow: scroll`, so a list longer or
//! wider than the viewport scrolls — under the wheel ([`Ui::scroll_wheel`]),
//! and to keep the focused item in view — rather than running off the
//! viewport's edge. The cap is the viewport the last layout was given, as a
//! drop-down's width is its button's as last laid out, so it is a frame late
//! to follow a resize and absent in a tree's first frame; a caller's `inline`
//! `max-height` or `max-width` overrides it, and a `min-width` — a
//! drop-down's button's — wins over the width cap, as CSS has it.
//!
//! **It is clipped to the viewport, and to nothing its anchor is under**: a
//! list hanging out of a scrolled, clipped panel draws whole over it. Each
//! open pop-up is a **layer**, drawn after every lower one — the tree is layer
//! 0 — with its outlines after it, so neither a sibling built later nor a
//! focus ring below shows through. A layer is hit-tested before every layer
//! under it, whatever their build order.
//!
//! # Closing one
//!
//! [`Ui::close_popup`] closes a pop-up and every pop-up above it. The layer
//! also closes itself:
//!
//! * **A press outside it closes it**, and every pop-up above the layer the
//!   press landed in — a secondary press as well as a primary one, though
//!   only a primary press is captured (`widgets/context_menu.rs` has what a
//!   secondary press does next). A primary press outside every pop-up is
//!   **spent closing them**:
//!   it is captured by no node, so nothing under it is pressed, hovered or
//!   clicked until it is released. This is the long-term rule, decided
//!   2026-10-03: a click meant to dismiss a list must not also fire whatever
//!   the list was covering, and a click on the anchor itself closes the list
//!   rather than closing and reopening it.
//! * **Back closes the topmost**, when nothing is engaged — an engaged widget
//!   inside the pop-up cancels first, as back always does — and the back is
//!   spent there: [`Ui::back_requested`] does not report it.
//!
//! # Focus
//!
//! A pop-up's root is a [`Scope::Modal`](super::Scope::Modal), and the topmost
//! modal by layer, so focus moves into it the frame after it is built — onto
//! the node [`Ui::set_focus`] asked for, else by the landing rule in
//! `focus/mod.rs` — and no move or tree-order step leaves it. Inside, the
//! frame's [`NavInput`](super::NavInput) moves focus as anywhere else, and its
//! [`Jump`](super::Jump) — Home, End, Page Up and Page Down — and a list's
//! typeahead move it as `popup_nav.rs` says.
//! **Closing a pop-up, by any of the ways above, gives focus back to its
//! anchor** when the next frame begins, or at once for back.

use glam::Vec2;

use super::store::NodeKey;
use super::tooltip::TOOLTIP_LAYER;
use super::widgets::{WidgetKind, typed};
use super::{Behavior, KeySource, LengthAuto, ROOT_KEY, Response, Ui};
use crate::draw_list::ClipRect;
use crate::style::{Declaration, PseudoClasses};
use crate::widget::PointerInput;

/// The layer a node is given when it was built in a pop-up that closed
/// before layout: never hit, focused or drawn.
pub(super) const CLOSED_LAYER: usize = usize::MAX;

/// How much of the viewport's height or width a pop-up larger than it leaves
/// uncovered: its `max-height` and `max-width` are the viewport's less this,
/// in pixels, so some of what it hangs over always shows round it.
pub const POPUP_MARGIN: f32 = 16.0;

/// What a press spent closing pop-ups is captured by: a key no node has, so
/// nothing is pressed, hovered or clicked until the press is released.
const SPENT_PRESS: NodeKey = NodeKey(0x7370_656e_742d_7072);

/// Where an open pop-up goes against the node it hangs from; the module docs
/// have each rule.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Placement {
    /// Below the anchor, flipped above it at the viewport's bottom: a
    /// drop-down's list.
    Below,
    /// Right of the anchor, flipped left of it at the viewport's right edge:
    /// a submenu.
    Beside,
    /// At a point in the tree's space, flipped up or left of it at the
    /// viewport's far edges: a context menu at the pointer.
    At(Vec2),
}

/// One open pop-up: what it hangs from, and how.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct OpenPopup {
    pub anchor: NodeKey,
    pub placement: Placement,
}

impl Ui {
    /// Opens the pop-up hanging from `anchor` below it, on top of every open
    /// one, for [`Ui::popup`] to build: [`Ui::open_popup_at`] with
    /// [`Placement::Below`].
    pub fn open_popup(&mut self, anchor: NodeKey) {
        self.open_popup_at(anchor, Placement::Below);
    }

    /// Opens the pop-up hanging from `anchor`, placed as `placement` says, on
    /// top of every open one, for [`Ui::popup`] to build. Does nothing when it
    /// is already open, wherever it was placed.
    pub fn open_popup_at(&mut self, anchor: NodeKey, placement: Placement) {
        if !self.is_popup_open(anchor) {
            self.popups.push(OpenPopup { anchor, placement });
        }
    }

    /// Closes the pop-up hanging from `anchor`, and every pop-up above it, and
    /// gives focus back to `anchor` when the next frame begins. Does nothing
    /// when it is not open.
    pub fn close_popup(&mut self, anchor: NodeKey) {
        if let Some(depth) = self.popup_depth(anchor) {
            self.close_popups_from(depth);
        }
    }

    /// Whether the pop-up hanging from `anchor` is open.
    #[must_use]
    pub fn is_popup_open(&self, anchor: NodeKey) -> bool {
        self.popup_depth(anchor).is_some()
    }

    /// Where the pop-up hanging from `anchor` is in the stack, counting from 0
    /// at the bottom, while it is open.
    fn popup_depth(&self, anchor: NodeKey) -> Option<usize> {
        self.popups.iter().position(|open| open.anchor == anchor)
    }

    /// The key of the root [`Ui::popup`] builds for `anchor`, which is the
    /// same wherever the call is made: what a caller or a test walks a
    /// pop-up's nodes from with [`Ui::child_keys`].
    #[must_use]
    pub fn popup_key(anchor: NodeKey) -> NodeKey {
        Self::key_under(ROOT_KEY, KeySource::Popup(anchor.0))
    }

    /// The pop-up hanging from `anchor`, while it is open: a `popup` block —
    /// `selector` is its `#id.class`, as a widget's is, though an `#id` does
    /// not key it: its anchor does — whose children `build` adds, placed,
    /// capped and drawn as the module docs say. `inline` overrides every rule,
    /// as [`Ui::block`]'s does, and the cap on its height.
    ///
    /// Returns the root's [`Response`], or `None` without building anything
    /// while the pop-up is closed.
    pub fn popup(
        &mut self,
        anchor: NodeKey,
        selector: &str,
        inline: &[Declaration],
        build: impl FnOnce(&mut Self),
    ) -> Option<Response> {
        if !self.is_popup_open(anchor) {
            return None;
        }
        let selector = typed("popup", selector);
        let viewport = self.viewport();
        let room = viewport.max - viewport.min;
        // An axis laid out under content-sized space is unbounded: no cap.
        let cap = |room: f32| {
            room.is_finite()
                .then(|| LengthAuto::Px((room - POPUP_MARGIN).max(0.0)))
        };
        let caps = [
            cap(room.y).map(Declaration::MaxHeight),
            cap(room.x).map(Declaration::MaxWidth),
        ];
        let inline: Vec<Declaration> = caps
            .into_iter()
            .flatten()
            .chain(inline.iter().copied())
            .collect();
        let (index, response) = self.open_root(
            Self::popup_key(anchor),
            &selector,
            &inline,
            Behavior::MODAL,
            build,
        );
        self.popup_roots.push((index, anchor));
        self.mark(response.key, WidgetKind::Popup);
        Some(response)
    }

    /// A block keyed `key` built outside every open block, so it is a root of
    /// its own and nothing it hangs out of clips or scrolls it — a tree row's
    /// children are not its either. Returns its index in this frame's nodes
    /// and its [`Response`]: what a pop-up and a tooltip are built as.
    pub(super) fn open_root(
        &mut self,
        key: NodeKey,
        selector: &str,
        inline: &[Declaration],
        behavior: Behavior,
        build: impl FnOnce(&mut Self),
    ) -> (usize, Response) {
        let parsed = self.node_selector(selector);
        let open = std::mem::take(&mut self.open);
        let rows = std::mem::take(&mut self.tree_rows);
        let index = self.nodes.len();
        let response = self.open_block(key, parsed, inline, behavior, PseudoClasses::NONE, build);
        self.open = open;
        self.tree_rows = rows;
        (index, response)
    }

    /// Closes every pop-up from `depth` up the stack: what last frame drew of
    /// them stops being hit, focused or trapping focus at once, rather than at
    /// the next layout, and focus goes back to the lowest one's anchor.
    pub(super) fn close_popups_from(&mut self, depth: usize) {
        let Some(&OpenPopup { anchor, .. }) = self.popups.get(depth) else {
            return;
        };
        self.popups.truncate(depth);
        for node in self.store.iter_mut() {
            if node.layer > depth {
                node.hittable = false;
            }
        }
        self.set_focus(anchor);
    }

    /// A press that began outside the topmost pop-up closes it, and every
    /// pop-up above the layer it landed in; see the module docs. `over` is
    /// the press's hit chain, and what is returned is the chain the rest of
    /// the frame sees: empty when the press landed outside every pop-up and
    /// was spent closing them.
    pub(super) fn press_outside_popups(
        &mut self,
        pointer: PointerInput,
        over: Vec<NodeKey>,
    ) -> Vec<NodeKey> {
        if !pointer.down || self.capture.active().is_some() {
            return over;
        }
        let Some(layer) = self.close_above_press(&over) else {
            return over;
        };
        if layer > 0 {
            // Inside a lower pop-up: the press is that pop-up's.
            return over;
        }
        self.capture
            .interact(SPENT_PRESS.0, true, pointer.down, pointer.released);
        Vec::new()
    }

    /// Closes every pop-up above the layer a press whose hit chain is `over`
    /// landed in — the tree's, 0, for a press on nothing — and answers that
    /// layer; `None`, closing nothing, when the press landed in the topmost
    /// pop-up or none is open.
    pub(super) fn close_above_press(&mut self, over: &[NodeKey]) -> Option<usize> {
        let layer = over
            .first()
            .and_then(|&key| self.store.by_key(key))
            .map_or(0, |node| node.layer);
        if layer >= self.popups.len() {
            return None;
        }
        self.close_popups_from(layer);
        Some(layer)
    }

    /// Back closes the topmost pop-up when nothing is engaged to cancel, and is
    /// spent doing it: returns `nav` without its back when it was.
    pub(super) fn back_out_of_popup(&mut self, nav: super::NavInput) -> super::NavInput {
        if !nav.back || self.engaged().is_some() || self.popups.is_empty() {
            return nav;
        }
        self.close_popups_from(self.popups.len() - 1);
        super::NavInput { back: false, ..nav }
    }

    /// Closes what the frame did not build — see the module docs — then gives
    /// each of this frame's nodes its layer: 0 for the tree, `n` under the
    /// `n`th open pop-up, [`TOOLTIP_LAYER`] under the tooltip, and
    /// [`CLOSED_LAYER`] under a pop-up that closed while the frame was being
    /// built and under a tooltip whose anchor is in one.
    pub(super) fn layers(&mut self) -> Vec<usize> {
        let unbuilt = self.popups.iter().position(|open| {
            !self
                .popup_roots
                .iter()
                .any(|&(_, built)| built == open.anchor)
                || self.store.find(open.anchor).is_none()
        });
        if let Some(depth) = unbuilt {
            self.close_popups_from(depth);
        }
        let mut layers = vec![0; self.nodes.len()];
        for &(root, anchor) in &self.popup_roots {
            layers[root] = self
                .popup_depth(anchor)
                .map_or(CLOSED_LAYER, |depth| depth + 1);
        }
        // A parent is always built before its children, and a tooltip after
        // its anchor.
        let tooltip = self.tooltip.built;
        for index in 0..self.nodes.len() {
            if let Some(parent) = self.nodes[index].parent {
                layers[index] = layers[parent];
            } else if let Some((root, anchor)) = tooltip
                && root == index
            {
                layers[index] = if layers[anchor] == CLOSED_LAYER {
                    CLOSED_LAYER
                } else {
                    TOOLTIP_LAYER
                };
            }
        }
        layers
    }

    /// The viewport [`Ui::layout`] was last given: what a pop-up is kept
    /// inside and clipped to.
    pub(super) fn viewport(&self) -> ClipRect {
        self.viewport.unwrap_or(ClipRect::NONE)
    }

    /// The border-box top-left of the pop-up root `index` of `popup`, whose
    /// anchor is placed by now.
    pub(super) fn popup_origin(&self, index: usize, popup: OpenPopup) -> Vec2 {
        let anchor = self
            .store
            .by_key(popup.anchor)
            .map_or((Vec2::ZERO, Vec2::ZERO), |node| node.rect);
        let size = self.nodes[index].layout.size;
        hang(
            anchor,
            Vec2::new(size.width, size.height),
            self.viewport(),
            popup.placement,
        )
    }
}

/// The viewport of a tree laid out at `origin` in `available`: the space
/// itself on a definite axis, and no bound on a content-sized one.
pub(super) fn viewport_of(origin: Vec2, available: super::AvailableSpace) -> ClipRect {
    let axis = |start: f32, extent: super::Available| match extent {
        super::Available::Definite(length) => (start, start + length),
        super::Available::MinContent | super::Available::MaxContent => (f32::MIN, f32::MAX),
    };
    let (min_x, max_x) = axis(origin.x, available.width);
    let (min_y, max_y) = axis(origin.y, available.height);
    ClipRect {
        min: Vec2::new(min_x, min_y),
        max: Vec2::new(max_x, max_y),
    }
}

/// Where a pop-up of `size` hangs from the border box `anchor` inside
/// `viewport`, placed as `placement` says — see the module docs — then
/// shifted the least that keeps it inside, its top-left corner kept when it is
/// larger than the viewport.
pub(super) fn hang(
    anchor: (Vec2, Vec2),
    size: Vec2,
    viewport: ClipRect,
    placement: Placement,
) -> Vec2 {
    let (anchor_min, anchor_max) = anchor;
    let flip = |axis: usize, before: f32, after: f32| {
        flipped(
            (before, after),
            size[axis],
            (viewport.min[axis], viewport.max[axis]),
        )
    };
    let min = match placement {
        Placement::Below => Vec2::new(anchor_min.x, flip(1, anchor_min.y, anchor_max.y)),
        Placement::Beside => Vec2::new(flip(0, anchor_min.x, anchor_max.x), anchor_min.y),
        Placement::At(point) => Vec2::new(flip(0, point.x, point.x), flip(1, point.y, point.y)),
    };
    // The far edge first, so the near one wins when both cannot hold.
    min.min(viewport.max - size).max(viewport.min)
}

/// Where a pop-up `length` long starts on one axis: at `after`, the far side
/// of what it hangs from, or — when it would run past the viewport's end and
/// there is more room back from `before` to the viewport's start — ending at
/// `before`.
fn flipped((before, after): (f32, f32), length: f32, (start, end): (f32, f32)) -> f32 {
    let room_after = end - after;
    let room_before = before - start;
    if length > room_after && room_before > room_after {
        before - length
    } else {
        after
    }
}