Skip to main content

egui_pop_core/
fold.rs

1//! Folds inside a panel: a group whose header row folds and opens its
2//! body ([`Fold`]), and a row of a hand-built tree with its disclosure
3//! toggle ([`TreeRow`]), for the folds that are neither a whole side bar
4//! of stacked sections ([`crate::sections::Sections`]) nor a data view's
5//! tree.
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! - A fold's header is a section band in the kit's look (its disclosure
11//!   mark, its title, an optional count), with optional actions at its
12//!   right end. A click on the band, or Space or Enter while it has the
13//!   keyboard, folds or opens it; Left folds it and Right opens it.
14//! - A tree row is the row the caller draws, after its toggle: a branch's
15//!   toggle folds and opens the rows below it (a click, Space or Enter,
16//!   Left and Right while it has the keyboard); a leaf's row takes the
17//!   same room, so that branches and leaves line up. Rows below a branch
18//!   are indented by one level. A flat tree's row says its own depth
19//!   ([`TreeRow::depth`]): indented by that many levels, and read aloud
20//!   at its level.
21//! - What is open is kept by id in egui's persisted memory, with the
22//!   window's layout, as egui's own collapsing regions keep it: a fold
23//!   has the id an egui `CollapsingHeader` given the same `id_salt` has,
24//!   and a tree row the id it is given, so either replaces egui's without
25//!   losing what the user opened. [`is_open`] reads it and [`set_open`]
26//!   changes it.
27//! - **Named and observable.** A fold's header is a button named by its
28//!   title and count ("Folders, 3"), a tree row's toggle a disclosure
29//!   triangle named after its row ("Show or hide Photos", the strings
30//!   provider's `egui-pop-fold-toggle`); both say whether they are
31//!   expanded and answer assistive technology's expand and collapse
32//!   actions.
33//!
34//! ```
35//! use egui_pop_core::fold::{Fold, TreeRow};
36//!
37//! let ctx = egui::Context::default();
38//! let mut out = ctx.run_ui(Default::default(), |ui| {
39//!     Fold::new("folders", "Folders").count(2).default_open(true).show(ui, |ui| {
40//!         let id = ui.make_persistent_id("photos");
41//!         TreeRow::new(id, "Photos")
42//!             .show(ui, |ui| ui.label("Photos"))
43//!             .body(ui, |ui| {
44//!                 TreeRow::new(ui.make_persistent_id("2024"), "2024")
45//!                     .leaf(true)
46//!                     .show(ui, |ui| ui.label("2024"));
47//!             });
48//!     });
49//! });
50//! out.textures_delta.clear();
51//! ```
52
53use egui::collapsing_header::CollapsingState;
54use egui::{
55    Context, EventFilter, Id, IdSalt, InnerResponse, Key, Response, Sense, Ui, WidgetInfo,
56    accesskit,
57};
58use egui_stack::PartState;
59
60use crate::kit::{Glyph, Kit};
61use crate::sections::row_height;
62use crate::strings::{self, FOLD_TOGGLE};
63
64/// Whether the fold or the tree row of id `id` is open, if it was ever
65/// shown or set.
66pub fn is_open(ctx: &Context, id: Id) -> Option<bool> {
67    CollapsingState::load(ctx, id).map(|s| s.is_open())
68}
69
70/// Opens or folds the fold or the tree row of id `id` (shown so from the
71/// next pass), and keeps it so.
72pub fn set_open(ctx: &Context, id: Id, open: bool) {
73    let mut state = CollapsingState::load_with_default_open(ctx, id, open);
74    state.set_open(open);
75    state.store(ctx);
76    ctx.request_repaint();
77}
78
79/// Whether the keyboard or assistive technology asks the open or folded
80/// widget `r` to change: Left folds it and Right opens it while it has
81/// the keyboard (the arrows then do not move the focus), and an expand or
82/// collapse action. Space and Enter come as a click.
83fn asked_to_toggle(ui: &Ui, r: &Response, open: bool) -> bool {
84    let mut asked = false;
85    if r.has_focus() {
86        ui.memory_mut(|m| {
87            m.set_focus_lock_filter(
88                r.id,
89                EventFilter {
90                    horizontal_arrows: true,
91                    ..Default::default()
92                },
93            );
94        });
95        let key = if open {
96            Key::ArrowLeft
97        } else {
98            Key::ArrowRight
99        };
100        asked |= ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key));
101    }
102    let action = if open {
103        accesskit::Action::Collapse
104    } else {
105        accesskit::Action::Expand
106    };
107    asked | ui.input(|i| i.has_accesskit_action_request(r.id, action))
108}
109
110/// Says to assistive technology whether `id` is open, and what it can
111/// ask of it.
112fn expanded_node(ctx: &Context, id: Id, open: bool) {
113    ctx.accesskit_node_builder(id, |node| {
114        node.set_expanded(open);
115        node.add_action(if open {
116            accesskit::Action::Collapse
117        } else {
118            accesskit::Action::Expand
119        });
120    });
121}
122
123/// Says a tree row's node is at level `depth + 1` (accesskit counts
124/// levels from 1).
125fn level_node(ctx: &Context, id: Id, depth: usize) {
126    ctx.accesskit_node_builder(id, |node| node.set_level(depth + 1));
127}
128
129/// What a fold did this pass.
130#[derive(Debug)]
131pub struct FoldResponse<R> {
132    /// The fold's id: where its open state is kept ([`is_open`]).
133    pub id: Id,
134    /// The header band's response.
135    pub header: Response,
136    /// Whether it is open after the pass.
137    pub open: bool,
138    /// Whether the user folded or opened it this pass.
139    pub toggled: bool,
140    /// What the body returned, when it was shown.
141    pub body: Option<InnerResponse<R>>,
142}
143
144/// What a fold's band shows at its right end.
145type Actions<'a> = Box<dyn FnOnce(&mut Ui) + 'a>;
146
147/// A group inside a panel whose header row folds and opens its body: a
148/// section band (disclosure mark, title, count) with optional actions at
149/// its right end, its body indented below it when open. Its open state
150/// is kept by id (see the module).
151///
152/// Need (layout): a group that folds and opens inside a panel (a disclosure, a collapsing header).
153pub struct Fold<'a> {
154    salt: IdSalt,
155    title: String,
156    count: Option<u64>,
157    default_open: bool,
158    indent: bool,
159    actions: Option<Actions<'a>>,
160}
161
162impl std::fmt::Debug for Fold<'_> {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        f.debug_struct("Fold")
165            .field("title", &self.title)
166            .field("count", &self.count)
167            .field("default_open", &self.default_open)
168            .field("indent", &self.indent)
169            .field("actions", &self.actions.is_some())
170            .finish_non_exhaustive()
171    }
172}
173
174impl<'a> Fold<'a> {
175    /// A fold titled `title`, its state kept under `id_salt` (unique in
176    /// the parent `Ui`; the id egui's `CollapsingHeader` gives the same
177    /// salt). Folded until opened, unless [`Fold::default_open`].
178    pub fn new(id_salt: impl egui::AsIdSalt, title: impl Into<String>) -> Self {
179        Fold {
180            salt: IdSalt::new(id_salt),
181            title: title.into(),
182            count: None,
183            default_open: false,
184            indent: true,
185            actions: None,
186        }
187    }
188
189    /// The count shown on the band, and in its name ("Folders, 3").
190    pub fn count(mut self, count: u64) -> Self {
191        self.count = Some(count);
192        self
193    }
194
195    /// Whether it is open the first time it is shown (no by default).
196    pub fn default_open(mut self, open: bool) -> Self {
197        self.default_open = open;
198        self
199    }
200
201    /// Whether the body is indented under the band (yes by default).
202    pub fn indent(mut self, indent: bool) -> Self {
203        self.indent = indent;
204        self
205    }
206
207    /// Actions at the band's right end (a button, a menu), laid out from
208    /// right to left; a click on them does not fold the group.
209    pub fn actions(mut self, add: impl FnOnce(&mut Ui) + 'a) -> Self {
210        self.actions = Some(Box::new(add));
211        self
212    }
213
214    /// Shows the band, and the body `add` gives when open.
215    pub fn show<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> FoldResponse<R> {
216        // A vertical scope, as egui's CollapsingHeader has: the same ids
217        // for the fold and for what its body holds.
218        ui.vertical(|ui| self.show_inside(ui, add)).inner
219    }
220
221    fn show_inside<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> FoldResponse<R> {
222        let id = ui.make_persistent_id(self.salt);
223        let ctx = ui.ctx().clone();
224        let kit = Kit::of(&ctx);
225        let mut state = CollapsingState::load_with_default_open(&ctx, id, self.default_open);
226        let height = if kit.section_band.data.height > 0.0 {
227            kit.section_band.data.height
228        } else {
229            row_height(ui)
230        };
231        let (row, _) = ui.allocate_exact_size(
232            egui::vec2(ui.available_width().max(height), height),
233            Sense::hover(),
234        );
235        // The actions first, from the right end: the band takes what
236        // they leave.
237        let mut band = row;
238        if let Some(actions) = self.actions {
239            let mut child = ui.new_child(
240                egui::UiBuilder::new()
241                    .id_salt(id.with("actions"))
242                    .max_rect(row)
243                    .layout(egui::Layout::right_to_left(egui::Align::Center)),
244            );
245            actions(&mut child);
246            let used = child.min_rect().width();
247            if used > 0.0 {
248                band.max.x = (row.right() - used - ui.spacing().item_spacing.x).max(row.left());
249            }
250        }
251        let header = ui.interact(band, id, Sense::click());
252        let mut open = state.is_open();
253        let toggled = header.clicked() || asked_to_toggle(ui, &header, open);
254        if toggled {
255            state.toggle(ui);
256            open = state.is_open();
257        }
258        let name = match self.count {
259            Some(n) => format!("{}, {n}", self.title),
260            None => self.title.clone(),
261        };
262        let enabled = ui.is_enabled();
263        header.widget_info(|| WidgetInfo::labeled(egui::Role::Button, enabled, &name));
264        expanded_node(&ctx, id, open);
265        if ui.is_rect_visible(band) {
266            let part = PartState::NONE
267                .with(PartState::HOVERED, header.hovered())
268                .with(PartState::PRESSED, header.is_pointer_button_down_on())
269                .with(PartState::FOCUSED, header.has_focus());
270            kit.paint_section_band(
271                ui.painter(),
272                &crate::kit::dock::Band {
273                    rect: band,
274                    id,
275                    title: &self.title,
276                    count: self.count,
277                    open,
278                    state: part,
279                },
280            );
281        }
282        let body = if self.indent {
283            state.show_body_indented(&header, ui, add)
284        } else {
285            state.show_body_unindented(ui, add)
286        };
287        FoldResponse {
288            id,
289            header,
290            open,
291            toggled,
292            body,
293        }
294    }
295}
296
297/// A row of a hand-built tree: a branch's toggle, or a leaf's room for
298/// one, then the row the caller draws; [`TreeRowResponse::body`] shows
299/// the rows below a branch, indented, when it is open. Its open state is
300/// kept under the id it is given (see the module).
301///
302/// Need (data): a row of a hand-built tree with its disclosure toggle (a folder tree in a side panel).
303#[derive(Clone, Debug)]
304pub struct TreeRow {
305    id: Id,
306    name: String,
307    toggle_name: Option<String>,
308    leaf: bool,
309    default_open: bool,
310    depth: Option<usize>,
311}
312
313/// A shown tree row: its toggle, its row, and the rows below it.
314#[derive(Debug)]
315pub struct TreeRowResponse<R> {
316    /// The row's id: where its open state is kept ([`is_open`]).
317    pub id: Id,
318    /// The toggle's response, a branch's only.
319    pub toggle: Option<Response>,
320    /// What the row returned, and the response of the whole row.
321    pub row: InnerResponse<R>,
322    /// Whether it is open after the pass (a leaf never is).
323    pub open: bool,
324    /// Whether the user folded or opened it this pass.
325    pub toggled: bool,
326    state: Option<CollapsingState>,
327}
328
329impl TreeRow {
330    /// A branch kept under `id` (`ui.make_persistent_id(..)`, the id
331    /// egui's `CollapsingState` would be given), its toggle named after
332    /// `name` (its row's text, as read aloud). Folded until opened,
333    /// unless [`TreeRow::default_open`].
334    pub fn new(id: Id, name: impl Into<String>) -> Self {
335        TreeRow {
336            id,
337            name: name.into(),
338            toggle_name: None,
339            leaf: false,
340            default_open: false,
341            depth: None,
342        }
343    }
344
345    /// A row of a flat tree drawn at `depth` (0 at the top): indented by
346    /// `depth` times the theme's `spacing.indent` before its toggle (or a
347    /// leaf's room for one), and said to be at level `depth + 1` to
348    /// assistive technology (its toggle and its row both carry the
349    /// level). For a tree kept as a flat list, whose rows are not nested
350    /// in their parents' [`TreeRowResponse::body`] (a folder list that
351    /// leaves out the folders between): what the caller draws in the row
352    /// (a selectable label, a drag source) is unchanged. Without it, a
353    /// row is indented only by the bodies it is shown in, and says no
354    /// level.
355    pub fn depth(mut self, depth: usize) -> Self {
356        self.depth = Some(depth);
357        self
358    }
359
360    /// The toggle's whole accessible name, in place of "Show or hide"
361    /// and the row's name ("Show or hide the albums of Travel").
362    pub fn toggle_name(mut self, name: impl Into<String>) -> Self {
363        self.toggle_name = Some(name.into());
364        self
365    }
366
367    /// A leaf: no toggle, its room kept so that rows line up.
368    pub fn leaf(mut self, leaf: bool) -> Self {
369        self.leaf = leaf;
370        self
371    }
372
373    /// Whether a branch is open the first time it is shown (no by
374    /// default).
375    pub fn default_open(mut self, open: bool) -> Self {
376        self.default_open = open;
377        self
378    }
379
380    /// Shows the toggle and the row `add` gives, in one horizontal line.
381    pub fn show<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> TreeRowResponse<R> {
382        let ctx = ui.ctx().clone();
383        let mut state = (!self.leaf)
384            .then(|| CollapsingState::load_with_default_open(&ctx, self.id, self.default_open));
385        let mut toggled = false;
386        let mut toggle = None;
387        let row = ui.horizontal(|ui| {
388            let spacing = ui.spacing().item_spacing;
389            // The toggle takes the whole indent, as egui's does.
390            ui.spacing_mut().item_spacing.x = 0.0;
391            if let Some(depth) = self.depth {
392                level_node(&ctx, ui.unique_id(), depth);
393                ui.add_space(ui.spacing().indent * depth as f32);
394            }
395            let size = egui::vec2(ui.spacing().indent, ui.spacing().icon_width);
396            match state.as_mut() {
397                None => {
398                    ui.allocate_space(size);
399                }
400                Some(state) => {
401                    let (_, rect) = ui.allocate_space(size);
402                    let r = ui.interact(rect, self.id, Sense::click());
403                    if r.clicked() || asked_to_toggle(ui, &r, state.is_open()) {
404                        state.toggle(ui);
405                        toggled = true;
406                    }
407                    let open = state.is_open();
408                    let name = self.toggle_name.clone().unwrap_or_else(|| {
409                        strings::tr_args(&ctx, &FOLD_TOGGLE, &[("item", &self.name)])
410                    });
411                    let enabled = ui.is_enabled();
412                    r.widget_info(|| {
413                        WidgetInfo::labeled(egui::Role::DisclosureTriangle, enabled, &name)
414                    });
415                    expanded_node(&ctx, self.id, open);
416                    if let Some(depth) = self.depth {
417                        level_node(&ctx, self.id, depth);
418                    }
419                    if ui.is_rect_visible(rect) {
420                        paint_toggle(ui, &r, open);
421                    }
422                    toggle = Some(r);
423                }
424            }
425            ui.spacing_mut().item_spacing = spacing;
426            add(ui)
427        });
428        let open = state.as_ref().is_some_and(CollapsingState::is_open);
429        TreeRowResponse {
430            id: self.id,
431            toggle,
432            row,
433            open,
434            toggled,
435            state,
436        }
437    }
438}
439
440impl<R> TreeRowResponse<R> {
441    /// Shows the rows below a branch, indented, when it is open (nothing
442    /// for a leaf), and keeps its state.
443    pub fn body<B>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> B) -> Option<InnerResponse<B>> {
444        let mut state = self.state?;
445        state.show_body_indented(&self.row.response, ui, add)
446    }
447
448    /// Keeps a branch's state without showing rows below it (the caller
449    /// draws them itself when [`TreeRowResponse::open`]).
450    pub fn keep(self, ctx: &Context) {
451        if let Some(state) = self.state {
452            state.store(ctx);
453        }
454    }
455}
456
457/// When a hand-built tree draws its indent guides: a thin line down each
458/// nesting level, as VS Code's explorer does (`renderIndentGuides`).
459/// Never by default, so that a tree looks as it always did.
460///
461/// Need (data): a tree of places whose levels are easy to follow (folders nested deep).
462#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
463pub enum IndentGuides {
464    /// No guides.
465    #[default]
466    Never,
467    /// Guides only while the pointer is over the tree (VS Code's
468    /// `onHover`).
469    OnHover,
470    /// Guides all the time.
471    Always,
472}
473
474/// One row of a tree, as [`IndentGuides::paint`] needs it: its depth (0
475/// at the top) and its rectangle, whose left edge is where the tree's
476/// first level starts (a [`TreeRow`]'s whole row).
477#[derive(Clone, Copy, Debug, PartialEq)]
478pub struct GuideRow {
479    pub depth: usize,
480    pub rect: egui::Rect,
481}
482
483impl IndentGuides {
484    /// Paints the guides of `rows` (in the order drawn, one tree) when
485    /// this mode says so, `area` the tree's whole room (the pointer over
486    /// it shows the guides in [`IndentGuides::OnHover`]). The guide of
487    /// level `k` runs down every row deeper than `k`, through the centre
488    /// of the disclosure column of its ancestor at level `k` (one
489    /// `spacing.indent` per level), unbroken across the gaps between
490    /// rows. With `highlight`, the guide of the hovered row's parent (the
491    /// run of its siblings) is drawn in the kit's `list-guide` `hover`
492    /// state, the others at `rest`. Says whether any guide was drawn.
493    pub fn paint(self, ui: &Ui, area: egui::Rect, rows: &[GuideRow], highlight: bool) -> bool {
494        let over = ui.rect_contains_pointer(area);
495        let shown = match self {
496            IndentGuides::Never => false,
497            IndentGuides::OnHover => over,
498            IndentGuides::Always => true,
499        };
500        if !shown || rows.iter().all(|r| r.depth == 0) {
501            return false;
502        }
503        let pointer = ui.ctx().pointer_hover_pos().filter(|_| over);
504        let hovered = pointer.and_then(|p| {
505            rows.iter()
506                .position(|r| r.rect.y_range().contains(p.y) && r.rect.x_range().contains(p.x))
507        });
508        let indent = ui.spacing().indent;
509        let kit = Kit::of(ui.ctx());
510        let cx = crate::kit::KitCx {
511            painter: ui.painter(),
512            ppp: ui.ctx().pixels_per_point(),
513        };
514        let deepest = rows.iter().map(|r| r.depth).max().unwrap_or(0);
515        for level in 0..deepest {
516            let mut at = 0;
517            while at < rows.len() {
518                if rows[at].depth <= level {
519                    at += 1;
520                    continue;
521                }
522                let start = at;
523                while at < rows.len() && rows[at].depth > level {
524                    at += 1;
525                }
526                let run = start..at;
527                let lit = highlight
528                    && hovered.is_some_and(|h| run.contains(&h) && rows[h].depth == level + 1);
529                let first = rows[start].rect;
530                let x = first.left() + indent * level as f32 + indent / 2.0;
531                let line = egui::Rect::from_min_max(
532                    egui::pos2(x, first.top()),
533                    egui::pos2(x, rows[at - 1].rect.bottom()),
534                );
535                kit.list_guide.paint(
536                    &cx,
537                    &crate::kit::Part {
538                        rect: line,
539                        room: line,
540                        state: if lit {
541                            crate::kit::State::HOVER
542                        } else {
543                            crate::kit::State::REST
544                        },
545                        label: None,
546                    },
547                );
548            }
549        }
550        true
551    }
552}
553
554/// A toggle's mark: the kit's disclosure glyph, in the colour of the
555/// toggle's state, its focus shown by the kit's ring.
556fn paint_toggle(ui: &Ui, r: &Response, open: bool) {
557    let kit = Kit::of(ui.ctx());
558    let glyph = if open {
559        Glyph::DisclosureOpen
560    } else {
561        Glyph::DisclosureClosed
562    };
563    let (mut icon, _) = ui.spacing().icon_rectangles(r.rect);
564    icon.set_center(r.rect.center());
565    let color = ui.style().interact(r).fg_stroke.color;
566    kit.glyph(glyph).paint(ui.painter(), icon, color);
567    if r.has_focus() {
568        crate::ring::own(ui.ctx(), r.id);
569    }
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575
576    fn pass(ctx: &Context, input: egui::RawInput, add: impl FnMut(&mut Ui)) {
577        let input = egui::RawInput {
578            screen_rect: Some(egui::Rect::from_min_size(
579                egui::Pos2::ZERO,
580                egui::vec2(300.0, 400.0),
581            )),
582            ..input
583        };
584        let mut out = ctx.run_ui(input, add);
585        out.textures_delta.clear();
586    }
587
588    #[test]
589    fn a_fold_has_the_id_egui_s_collapsing_header_has() {
590        let ctx = Context::default();
591        let mut fold = None;
592        let mut header = None;
593        pass(&ctx, Default::default(), |ui| {
594            ui.push_id("a", |ui| {
595                fold = Some(
596                    Fold::new("helios.library.folders", "Folders")
597                        .show(ui, |_| ())
598                        .id,
599                );
600            });
601            ui.push_id("a", |ui| {
602                header = Some(
603                    egui::CollapsingHeader::new("Folders")
604                        .id_salt("helios.library.folders")
605                        .show(ui, |_| ())
606                        .header_response
607                        .id,
608                );
609            });
610        });
611        assert_eq!(fold, header);
612    }
613
614    #[test]
615    fn a_fold_keeps_what_set_open_says() {
616        fn show(ctx: &Context) -> (Id, bool) {
617            let mut seen = (Id::NULL, false);
618            pass(ctx, Default::default(), |ui| {
619                let r = Fold::new("f", "F").show(ui, |_| ());
620                seen = (r.id, r.body.is_some());
621            });
622            seen
623        }
624        let ctx = Context::default();
625        let (id, shown) = show(&ctx);
626        assert!(!shown, "folded by default");
627        assert_eq!(is_open(&ctx, id), Some(false));
628        set_open(&ctx, id, true);
629        assert!(show(&ctx).1);
630        assert_eq!(is_open(&ctx, id), Some(true));
631    }
632
633    #[test]
634    fn a_leaf_row_has_no_toggle_and_is_never_open() {
635        let ctx = Context::default();
636        pass(&ctx, Default::default(), |ui| {
637            let r = TreeRow::new(Id::unique("leaf"), "Leaf")
638                .leaf(true)
639                .default_open(true)
640                .show(ui, |ui| ui.label("Leaf"));
641            assert!(r.toggle.is_none());
642            assert!(!r.open);
643            assert!(r.body(ui, |_| ()).is_none());
644        });
645    }
646}