1use 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
64pub fn is_open(ctx: &Context, id: Id) -> Option<bool> {
67 CollapsingState::load(ctx, id).map(|s| s.is_open())
68}
69
70pub 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
79fn 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
110fn 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
123fn level_node(ctx: &Context, id: Id, depth: usize) {
126 ctx.accesskit_node_builder(id, |node| node.set_level(depth + 1));
127}
128
129#[derive(Debug)]
131pub struct FoldResponse<R> {
132 pub id: Id,
134 pub header: Response,
136 pub open: bool,
138 pub toggled: bool,
140 pub body: Option<InnerResponse<R>>,
142}
143
144type Actions<'a> = Box<dyn FnOnce(&mut Ui) + 'a>;
146
147pub 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 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 pub fn count(mut self, count: u64) -> Self {
191 self.count = Some(count);
192 self
193 }
194
195 pub fn default_open(mut self, open: bool) -> Self {
197 self.default_open = open;
198 self
199 }
200
201 pub fn indent(mut self, indent: bool) -> Self {
203 self.indent = indent;
204 self
205 }
206
207 pub fn actions(mut self, add: impl FnOnce(&mut Ui) + 'a) -> Self {
210 self.actions = Some(Box::new(add));
211 self
212 }
213
214 pub fn show<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> FoldResponse<R> {
216 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 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#[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#[derive(Debug)]
315pub struct TreeRowResponse<R> {
316 pub id: Id,
318 pub toggle: Option<Response>,
320 pub row: InnerResponse<R>,
322 pub open: bool,
324 pub toggled: bool,
326 state: Option<CollapsingState>,
327}
328
329impl TreeRow {
330 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 pub fn depth(mut self, depth: usize) -> Self {
356 self.depth = Some(depth);
357 self
358 }
359
360 pub fn toggle_name(mut self, name: impl Into<String>) -> Self {
363 self.toggle_name = Some(name.into());
364 self
365 }
366
367 pub fn leaf(mut self, leaf: bool) -> Self {
369 self.leaf = leaf;
370 self
371 }
372
373 pub fn default_open(mut self, open: bool) -> Self {
376 self.default_open = open;
377 self
378 }
379
380 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 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 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 pub fn keep(self, ctx: &Context) {
451 if let Some(state) = self.state {
452 state.store(ctx);
453 }
454 }
455}
456
457#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
463pub enum IndentGuides {
464 #[default]
466 Never,
467 OnHover,
470 Always,
472}
473
474#[derive(Clone, Copy, Debug, PartialEq)]
478pub struct GuideRow {
479 pub depth: usize,
480 pub rect: egui::Rect,
481}
482
483impl IndentGuides {
484 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
554fn 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}