Skip to main content

freya_components/
accordion.rs

1use freya_animation::prelude::{
2    AnimNum,
3    Ease,
4    Function,
5    use_animation,
6};
7use freya_core::prelude::*;
8use torin::{
9    gaps::Gaps,
10    prelude::VisibleSize,
11};
12
13use crate::{
14    define_theme,
15    get_theme,
16};
17
18define_theme! {
19    %[component]
20    pub Accordion {
21        %[fields]
22        color: Color,
23        background: Color,
24        border_fill: Color,
25    }
26}
27
28/// A container that expands/collapses vertically when pressed.
29///
30/// # Example
31///
32/// ```rust
33/// # use freya::prelude::*;
34/// const LOREM_IPSUM: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.";
35///
36/// fn app() -> impl IntoElement {
37///     rect()
38///        .center()
39///        .expanded()
40///        .spacing(4.)
41///        .children((0..2).map(|_| {
42///            Accordion::new()
43///                .header("Click to expand!")
44///                .child(LOREM_IPSUM)
45///        }))
46/// }
47/// ```
48///
49/// See the [interactive components demo](https://freyaui.dev/demo).
50#[derive(Clone, PartialEq, Default)]
51pub struct Accordion {
52    pub(crate) theme: Option<AccordionThemePartial>,
53    header: Option<Element>,
54    children: Vec<Element>,
55    cursor_icon: Option<CursorIcon>,
56    key: DiffKey,
57}
58
59impl KeyExt for Accordion {
60    fn key_mut(&mut self) -> &mut DiffKey {
61        &mut self.key
62    }
63}
64
65impl Accordion {
66    pub fn new() -> Self {
67        Self::default()
68    }
69
70    pub fn header<C: Into<Element>>(mut self, header: C) -> Self {
71        self.header = Some(header.into());
72        self
73    }
74
75    /// Override the cursor icon shown when hovering over this component.
76    pub fn cursor(mut self, cursor_icon: impl Into<Option<CursorIcon>>) -> Self {
77        self.cursor_icon = cursor_icon.into();
78        self
79    }
80}
81
82impl ChildrenExt for Accordion {
83    fn children_mut(&mut self) -> &mut Vec<Element> {
84        &mut self.children
85    }
86}
87
88impl Component for Accordion {
89    fn render(self: &Accordion) -> impl IntoElement {
90        let header_a11y_id = use_a11y();
91        let accordion_theme = get_theme!(&self.theme, AccordionThemePreference, "accordion");
92        let mut open = use_state(|| false);
93        let mut animation = use_animation(move |_conf| {
94            AnimNum::new(0., 100.)
95                .time(300)
96                .function(Function::Expo)
97                .ease(Ease::Out)
98        });
99
100        let clip_percent = animation.get().value();
101
102        rect()
103            .a11y_id(header_a11y_id)
104            .a11y_role(AccessibilityRole::Header)
105            .a11y_focusable(true)
106            .corner_radius(CornerRadius::new_all(8.))
107            .padding(Gaps::new_all(8.))
108            .color(accordion_theme.color)
109            .background(accordion_theme.background)
110            .border(
111                Border::new()
112                    .fill(accordion_theme.border_fill)
113                    .width(1.)
114                    .alignment(BorderAlignment::Inner),
115            )
116            .cursor(self.cursor_icon)
117            .on_press(move |_| {
118                if open.toggled() {
119                    animation.start();
120                } else {
121                    animation.reverse();
122                }
123            })
124            .maybe_child(self.header.clone())
125            .child(
126                rect()
127                    .a11y_role(AccessibilityRole::Region)
128                    .a11y_builder(|b| {
129                        b.set_labelled_by([header_a11y_id]);
130                        if !open() {
131                            b.set_hidden();
132                        }
133                    })
134                    .overflow(Overflow::Clip)
135                    .visible_height(VisibleSize::inner_percent(clip_percent))
136                    .children(self.children.clone()),
137            )
138    }
139
140    fn render_key(&self) -> DiffKey {
141        self.key.clone().or(self.default_key())
142    }
143}