rust_glass/widgets/
collapsing.rs1use std::f32::consts::TAU;
4
5use crate::accessibility::Role;
6use crate::animation::Tuning;
7use crate::context::{Cursor, Sense};
8use crate::geometry::{Rect, Vec2, vec2};
9use crate::text::{TextStyle, Weight};
10use crate::ui::Ui;
11
12pub struct Collapsing<'a> {
14 title: &'a str,
15 open: bool,
16}
17
18impl<'a> Collapsing<'a> {
19 pub fn new(title: &'a str) -> Self {
21 Self { title, open: false }
22 }
23 pub fn default_open(mut self, open: bool) -> Self {
25 self.open = open;
26 self
27 }
28
29 pub fn show(self, ui: &mut Ui, f: impl FnOnce(&mut Ui)) {
31 let id = ui.make_id(("collapsing", self.title));
32 #[derive(Clone, Copy)]
33 struct State {
34 open: bool,
35 h: f32,
36 }
37 let mut s: State = ui.ctx.try_get(id).unwrap_or(State { open: self.open, h: 0.0 });
38 let w = ui.available_width();
39 let rect = ui.allocate(vec2(w, 30.0));
40 let r = ui.interact(id, rect, Sense::Click);
41 ui.ctx.focusable(id);
42 if r.clicked {
43 s.open = !s.open;
44 }
45 if let Some(n) = ui.access(id, Role::Button, rect) {
46 n.label(self.title).expanded(s.open);
47 }
48 if r.hovered {
49 ui.ctx.cursor = Cursor::Pointer;
50 }
51 let t = ui.ctx.animate_bool(id.with("t"), s.open, Tuning::new(0.40, 0.84));
52 let st = TextStyle::new(ui.ctx.theme.body_size).weight(Weight::Semibold);
53 let l = ui.layout_text(self.title, &st);
54 let c = ui.surface.text_color();
55 let cc = ui.surface.secondary_color();
56 let m = vec2(rect.min.x + 8.0, rect.center().y);
57 let a = t * TAU / 4.0;
58 let rot = |v: Vec2| vec2(v.x * a.cos() - v.y * a.sin(), v.x * a.sin() + v.y * a.cos());
59 let mut p = ui.painter();
60 p.line(m + rot(vec2(-2.4, -5.0)), m + rot(vec2(2.8, 0.0)), 2.1, cc);
61 p.line(m + rot(vec2(2.8, 0.0)), m + rot(vec2(-2.4, 5.0)), 2.1, cc);
62 p.text(vec2(rect.min.x + 22.0, rect.center().y - l.size.y * 0.5), &l, c);
63 ui.focus_ring(id, rect, 8.0);
64
65 if t > 0.002 || s.h == 0.0 {
66 let shown = s.h * t.max(0.0);
67 let body =
68 Rect::from_min_size(vec2(rect.min.x + 22.0, rect.max.y + 4.0), vec2(w - 22.0, 10_000.0));
69 let (old_clip, old_op) = (ui.clip, ui.opacity);
70 ui.clip = ui.clip.intersect(Rect {
71 min: vec2(-1e6, rect.max.y),
72 max: vec2(1e6, rect.max.y + 4.0 + shown + if t > 0.98 { 40.0 } else { 0.0 }),
73 });
74 ui.opacity *= ((t - 0.15) / 0.85).clamp(0.0, 1.0);
75 let (_, size) = ui.in_rect_sized("body", body, f);
76 ui.clip = old_clip;
77 ui.opacity = old_op;
78 if s.h == 0.0 {
79 ui.ctx.request_relayout();
80 }
81 s.h = size.y + 4.0;
82 ui.space(shown);
86 }
87 ui.ctx.set(id, s);
88 }
89}
90
91impl Ui<'_> {
92 pub fn collapsing(&mut self, title: &str, f: impl FnOnce(&mut Ui)) {
94 Collapsing::new(title).show(self, f);
95 }
96}