crcbl-ui 0.2.1

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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! A virtualized outliner: a tree of rows over the same fixed-row-height
//! window [`Ui::list`] builds, so a hundred thousand rows cost what a hundred
//! do.
//!
//! # The shape this follows, and why
//!
//! An outliner is a **flattened visible-row model** — one `Vec` of the rows an
//! expansion state leaves showing — virtualized at a fixed row height, which is
//! how Unity's `TreeView` and Blender's outliner are built. It is not Godot's
//! `Tree`, which keeps a retained item per node and lays every one of them out,
//! and so stalls past ten thousand rows; and it is not a variable-height
//! virtualizer, because a fixed height turns "which rows are in view" into
//! arithmetic instead of a measurement — the reason Unity's `ListView`
//! virtualizes only at a fixed height. Nesting is drawn as `padding-left`, so
//! depth costs a number rather than a block per level.
//!
//! # Who owns what
//!
//! [`OutlinerState`] is the application's: it holds which items are expanded,
//! which are selected, and the flattened rows. The **caller** flattens, through
//! the [`OutlinerBuilder`] the widget hands it, and a collapsed branch's
//! children are never walked — so the flatten costs what is visible, not what
//! the tree holds. The flatten runs only when [`OutlinerState::is_stale`], which
//! expanding, collapsing and [`OutlinerState::invalidate`] set, so a still frame
//! walks nothing at all and builds only the rows in its window.
//!
//! # What the widget answers
//!
//! * **The pointer**: a click on a row's `.outliner-toggle` expands or
//!   collapses it; a click anywhere else on the row selects it. The toggle is a
//!   button that cannot take focus, so the press latches on it rather than on
//!   the row, and navigation stops once per row rather than twice.
//! * **The keyboard and the pad**: rows are [`Behavior::BUTTON`]s, so focus
//!   walks them and accept selects. Left and right expand and collapse through
//!   the same WAI-ARIA tree view rule [`Ui::tree_node`] follows —
//!   [`Ui::tree_item_step`](Ui) reads the [`WidgetState::TreeItem`] each row
//!   keeps — and an expansion it makes is answered at the top of the next
//!   [`Ui::outliner`] call, before the model is flattened, so the children show
//!   in the same frame.
//! * **The selection** is single by default. [`SelectMode`] is the frame's
//!   modifier, mapped by the caller from its own input exactly as
//!   [`NavInput`](crate::tree::NavInput) is: `Toggle` adds or removes one row,
//!   `Range` takes every row between the anchor and the one acted on.
//!   With `Range`, up and down also extend the selection to the focused row
//!   inside this outliner; without an anchor the previous focused row starts
//!   the range. Plain navigation and horizontal expansion do not select.
//! * **A double-click** on a row — a second click on it within
//!   [`DOUBLE_CLICK_TIME`] and [`DRAG_THRESHOLD`] of the first, as a text
//!   input's word selection is timed — is [`OutlinerState::double_clicked`]
//!   for the frame it lands, which is the gesture a file manager renames or
//!   opens an item with. The tree reads no wall clock, so the time is the
//!   frames' own [`TextInput::dt`](crate::tree::TextInput), summed.

use std::collections::HashSet;
use std::panic::Location;

use super::list::{row_inline, row_span};
use super::text_input::DOUBLE_CLICK_TIME;
use super::{Ui, WidgetKind, WidgetState, typed};
use crate::style::{Declaration, PseudoClasses, Sides};
use crate::tree::{
    Behavior, DRAG_THRESHOLD, KeySource, Length, LengthAuto, NodeKey, Overflow, Response, Role,
    hash_of,
};

/// How far one level of depth indents a row, in pixels:
/// [`OutlinerOptions::indent`]'s default.
pub const OUTLINER_INDENT: f32 = 12.0;

/// How tall a row is, in pixels: [`OutlinerOptions::row_height`]'s default.
pub const OUTLINER_ROW_HEIGHT: f32 = 16.0;

/// An item's identity in an outliner: what expansion and selection are kept
/// by, and what keys its row, so both follow the item when the rows reorder.
///
/// The application mints these — a scene entity id, a hash of a path — and only
/// has to keep them stable and distinct within one [`OutlinerState`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct OutlinerId(pub u64);

/// One row of an outliner's flattened visible model.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct OutlinerRow {
    /// The item the row stands for.
    pub id: OutlinerId,
    /// The item this one is a child of; none at a root.
    pub parent: Option<OutlinerId>,
    /// How deep it sits, `0` at a root: what it is indented by.
    pub depth: u16,
    /// Whether it can be expanded at all.
    pub branch: bool,
    /// Whether it is expanded, so its children are in the model under it.
    pub open: bool,
}

/// How a click or an accept on a row changes the selection this frame.
///
/// The tree reads no device, so the caller maps its own modifier keys to these
/// as it maps a [`NavInput`](crate::tree::NavInput) — control for [`Self::Toggle`],
/// shift for [`Self::Range`], in the convention every file manager shares.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SelectMode {
    /// The row becomes the only selected row, and the anchor.
    #[default]
    Replace,
    /// The row joins the selection, or leaves it, and becomes the anchor.
    Toggle,
    /// Every row between the anchor and this one is selected, and the anchor
    /// stays where it was. With no anchor this is [`Self::Replace`].
    Range,
}

/// What [`Ui::outliner_with`] takes beside its rows.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OutlinerOptions {
    /// How tall each row is, in pixels; under one pixel is taken as one.
    pub row_height: f32,
    /// How far one level of depth indents a row, in pixels.
    pub indent: f32,
    /// How a click or an accept this frame changes the selection. With
    /// [`SelectMode::Range`], up and down extend it from the anchor to the
    /// focused row; without an anchor the previous focused row starts it.
    pub select: SelectMode,
}

impl Default for OutlinerOptions {
    fn default() -> Self {
        Self {
            row_height: OUTLINER_ROW_HEIGHT,
            indent: OUTLINER_INDENT,
            select: SelectMode::Replace,
        }
    }
}

mod state;

pub use state::OutlinerState;

/// Flattens an outliner's visible rows; see [`OutlinerState::flatten`].
#[derive(Debug)]
pub struct OutlinerBuilder<'a> {
    rows: &'a mut Vec<OutlinerRow>,
    expanded: &'a HashSet<OutlinerId>,
    depth: u16,
    parent: Option<OutlinerId>,
}

impl OutlinerBuilder<'_> {
    /// Pushes an item with children, and runs `children` one level deeper —
    /// **only while the item is expanded**, so a collapsed subtree is never
    /// walked. Returns whether it is expanded.
    pub fn branch(&mut self, id: OutlinerId, children: impl FnOnce(&mut Self)) -> bool {
        let open = self.expanded.contains(&id);
        self.rows.push(OutlinerRow {
            id,
            parent: self.parent,
            depth: self.depth,
            branch: true,
            open,
        });
        if open {
            let (depth, parent) = (self.depth, self.parent);
            self.depth = depth.saturating_add(1);
            self.parent = Some(id);
            children(self);
            self.depth = depth;
            self.parent = parent;
        }
        open
    }

    /// Pushes an item with no children, which neither a click on its toggle nor
    /// right opens.
    pub fn leaf(&mut self, id: OutlinerId) {
        self.rows.push(OutlinerRow {
            id,
            parent: self.parent,
            depth: self.depth,
            branch: false,
            open: false,
        });
    }

    /// How deep the rows pushed now sit.
    #[must_use]
    pub const fn depth(&self) -> u16 {
        self.depth
    }
}

impl Ui {
    /// A virtualized outliner over `state`'s rows, each [`OUTLINER_ROW_HEIGHT`]
    /// tall and indented [`OUTLINER_INDENT`] a level, selecting one row at a
    /// time. [`Ui::outliner_with`] for the rest.
    #[track_caller]
    pub fn outliner(
        &mut self,
        selector: &str,
        state: &mut OutlinerState,
        tree: impl FnOnce(&mut OutlinerBuilder<'_>),
        row: impl FnMut(&mut Self, &OutlinerRow),
    ) -> Response {
        self.outliner_with(selector, state, &OutlinerOptions::default(), tree, row)
    }

    /// A virtualized outliner: an `outliner` block — `overflow: scroll`, sized
    /// by its stylesheet — holding an `.outliner-content` block as tall as
    /// every row, holding a focusable `.outliner-row` block per row in the
    /// window, each an `.outliner-toggle` block showing `+`, `-` or a space and
    /// then whatever `row` builds.
    ///
    /// `tree` flattens the caller's tree into `state`, and is run only when
    /// [`OutlinerState::is_stale`] — after this frame's expand and collapse are
    /// applied, so a row opened this frame shows its children this frame. A row
    /// is `:open` while expanded and `:checked` while selected. Returns the
    /// block's [`Response`], with [`Response::changed`] set the frame the
    /// expansion or the selection moved.
    #[track_caller]
    pub fn outliner_with(
        &mut self,
        selector: &str,
        state: &mut OutlinerState,
        options: &OutlinerOptions,
        tree: impl FnOnce(&mut OutlinerBuilder<'_>),
        mut row: impl FnMut(&mut Self, &OutlinerRow),
    ) -> Response {
        let selector = typed("outliner", selector);
        let parsed = self.node_selector(&selector);
        let key = self.widget_key(parsed, Location::caller());

        let expansion = self.apply_expansion(key, state);
        if state.is_stale() {
            state.flatten(tree);
        }
        let mut changed = false;
        for (id, was_open) in expansion.into_iter().rev() {
            if state.rows().iter().any(|row| row.id == id && row.branch) {
                changed = true;
            } else {
                // Input resolves against the previous frame. A branch that
                // disappeared must not regain expansion state from that input.
                state.set_expanded(id, was_open);
            }
        }

        if options.select == SelectMode::Range
            && !self.building_disabled()
            && let Some((from, to)) = self.vertical_focus_move
            && self.inside(from, Some(key))
            && self.inside(to, Some(key))
            && let (
                WidgetState::TreeItem {
                    item: Some(from), ..
                },
                WidgetState::TreeItem { item: Some(to), .. },
            ) = (self.widget_state(from), self.widget_state(to))
            && state.rows().iter().any(|row| row.id == from)
            && state.rows().iter().any(|row| row.id == to)
        {
            if state.anchor().is_none() {
                changed |= state.select(from, SelectMode::Replace);
            }
            changed |= state.select(to, SelectMode::Range);
        }

        let height = row_span(options.row_height);
        let mut focused = None;
        let mut response = self.open_block(
            key,
            parsed,
            &[Declaration::Overflow(Overflow::Scroll)],
            Behavior::NONE,
            PseudoClasses::NONE,
            |ui| {
                let (built, moved) = ui.outliner_rows(key, state, options, height, &mut row);
                focused = built;
                changed |= moved;
            },
        );
        self.set_widget_state(key, WidgetState::Rows(focused));
        self.mark(key, WidgetKind::Outliner);
        response.changed = changed;
        response
    }

    /// Answers the expand and collapse this frame's input asked of the outliner
    /// on `key` — a click on a row's toggle, and the left or right a focused
    /// row took through the tree view rule — before the rows are flattened.
    /// Returns each change's previous state for validation against the new model.
    fn apply_expansion(
        &mut self,
        key: NodeKey,
        state: &mut OutlinerState,
    ) -> Vec<(OutlinerId, bool)> {
        if self.building_disabled() {
            return Vec::new();
        }
        let mut changed = Vec::new();
        // Only the row the tree view rule actually toggled this frame, never
        // whatever the focused row's last build left in the store: the caller
        // may have collapsed it from outside since, and reading the store back
        // unconditionally would undo that.
        if let Some(toggled) = self.tree_toggled
            && self.inside(toggled, Some(key))
            && let WidgetState::TreeItem {
                open,
                item: Some(id),
                ..
            } = self.widget_state(toggled)
        {
            let was_open = state.is_expanded(id);
            if state.set_expanded(id, open) {
                changed.push((id, was_open));
            }
        }
        if let Some(clicked) = self.clicked_key()
            && self.inside(clicked, Some(key))
            && let WidgetState::OutlinerToggle(id) = self.widget_state(clicked)
        {
            let was_open = state.is_expanded(id);
            state.toggle_expanded(id);
            changed.push((id, was_open));
        }
        changed
    }

    /// The inside of an open outliner block: its content and the rows in the
    /// window. Returns the index of the row that holds focus, and whether the
    /// selection moved.
    fn outliner_rows(
        &mut self,
        key: NodeKey,
        state: &mut OutlinerState,
        options: &OutlinerOptions,
        height: f32,
        row: &mut impl FnMut(&mut Self, &OutlinerRow),
    ) -> (Option<usize>, bool) {
        let rows = state.rows().len();
        let window = self.row_window(rows, height);
        let content = [
            Declaration::Height(LengthAuto::Px(rows as f32 * height)),
            Declaration::FlexShrink(0.0),
        ];
        let disabled = self.building_disabled();
        let (mut focused, mut changed) = (None, false);
        state.double_clicked = None;
        self.block(".outliner-content", &content, |ui| {
            // The focused row outside the window, built in its place in tree
            // order so that next and previous still walk the rows in order.
            // The model is read by index, never walked: a hundred thousand
            // rows must cost this loop what a hundred do.
            let model: &[OutlinerRow] = state.rows();
            let outside = ui
                .kept_row(key, rows, |ui, index| {
                    ui.key(KeySource::Keyed(hash_of(model[index].id)))
                })
                .filter(|&index| index < window.first || index >= window.end);
            let indices = outside
                .filter(|&index| index < window.first)
                .into_iter()
                .chain(window.first..window.end)
                .chain(outside.filter(|&index| index >= window.end));
            for index in indices {
                let item = state.rows()[index];
                let (row_key, clicked) = ui.outliner_row(index, item, state, options, height, row);
                if clicked && !disabled {
                    changed |= state.select(item.id, options.select);
                    ui.note_click(state, item.id);
                }
                if ui.focused() == Some(row_key) {
                    focused = Some(index);
                }
            }
        });
        (focused, changed)
    }

    /// Records a click on the row `id`, and makes it
    /// [`OutlinerState::double_clicked`] when it is the second of a pair.
    fn note_click(&self, state: &mut OutlinerState, id: OutlinerId) {
        let (now, at) = (self.text_clock, self.pointer.pos);
        let second = state.last_click.is_some_and(|(row, when, from)| {
            row == id
                && now.saturating_sub(when) <= DOUBLE_CLICK_TIME
                && (at - from).length_squared() <= DRAG_THRESHOLD * DRAG_THRESHOLD
        });
        if second {
            state.double_clicked = Some(id);
            state.last_click = None;
        } else {
            state.last_click = Some((id, now, at));
        }
    }

    /// One row of an outliner, inside its content block: the row block, its
    /// toggle and whatever `row` builds. Returns the row's key and whether it
    /// was clicked.
    fn outliner_row(
        &mut self,
        index: usize,
        item: OutlinerRow,
        state: &OutlinerState,
        options: &OutlinerOptions,
        height: f32,
        row: &mut impl FnMut(&mut Self, &OutlinerRow),
    ) -> (NodeKey, bool) {
        let step = if options.indent.is_finite() {
            options.indent.max(0.0)
        } else {
            0.0
        };
        let [position, top, left, right, height] = row_inline(index, height);
        let inline = [
            position,
            top,
            left,
            right,
            height,
            Declaration::Padding(Sides::Left, Length::Px(f32::from(item.depth) * step)),
        ];

        let open = if item.open {
            PseudoClasses::OPEN
        } else {
            PseudoClasses::NONE
        };
        let selected = if state.is_selected(item.id) {
            PseudoClasses::CHECKED
        } else {
            PseudoClasses::NONE
        };

        // The tree view rule reads these off the focused row: its parent is
        // whichever row the flatten recorded, and its first child is the next
        // row, when that row is its child. Every row of one outliner is keyed
        // by its item under the same content block, so both keys are known
        // before either row is built.
        let keyed = |ui: &Self, id: OutlinerId| ui.key(KeySource::Keyed(hash_of(id)));
        let parent = item.parent.map(|id| keyed(self, id));
        let first_child = state
            .rows()
            .get(index + 1)
            .filter(|next| next.parent == Some(item.id))
            .map(|next| keyed(self, next.id));

        let parsed = self.node_selector(".outliner-row");
        let key = keyed(self, item.id);
        let key = self.unique(key);
        let response = self.open_block(
            key,
            parsed,
            &inline,
            Behavior::BUTTON,
            open | selected,
            |ui| {
                ui.outliner_toggle(item);
                row(ui, &item);
            },
        );
        self.set_widget_state(
            key,
            WidgetState::TreeItem {
                open: item.open,
                branch: item.branch,
                parent,
                first_child,
                item: Some(item.id),
            },
        );
        self.mark(key, WidgetKind::OutlinerRow);
        (key, response.clicked)
    }

    /// A row's toggle: a `.outliner-toggle` block holding a
    /// `.outliner-toggle-glyph` span of `+`, `-` or a space. A branch's toggle
    /// is a button that cannot take focus, so a click on it expands the row
    /// rather than selecting it, and a leaf's takes no press at all.
    fn outliner_toggle(&mut self, item: OutlinerRow) {
        let glyph = match (item.branch, item.open) {
            (false, _) => " ",
            (true, true) => "-",
            (true, false) => "+",
        };
        let behavior = if item.branch {
            Behavior {
                role: Role::Button,
                focusable: Some(false),
                ..Behavior::NONE
            }
        } else {
            Behavior::NONE
        };
        let toggle = self.block_with(".outliner-toggle", &[], behavior, |ui| {
            let glyph = ui.span(".outliner-toggle-glyph", glyph, &[]);
            ui.mark(glyph.key, WidgetKind::Decoration);
        });
        if item.branch {
            self.set_widget_state(toggle.key, WidgetState::OutlinerToggle(item.id));
            self.mark(toggle.key, WidgetKind::OutlinerToggle);
        } else {
            // A leaf's toggle is a space that takes no press.
            self.mark(toggle.key, WidgetKind::Decoration);
        }
    }
}