lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
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
//! Disclosures: `Accordion`, `AccordionItem`, `AccordionTrigger`, `AccordionContent`,
//! `Collapsible`, `CollapsibleTrigger`, and `CollapsibleContent`.
//!
//! Like `@santi020k/lumen-react`, the components render `<details>` and `<summary>`. Dioxus Native
//! does not toggle or hide `<details>` content by itself, so the open state lives in Rust: the
//! trigger toggles it on click, Enter, and Space (preventing the browser's own toggle on the web),
//! and the content wrapper is `hidden` while closed.

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::{Controllable, use_controllable};

/// Visual treatment of an [`Accordion`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum AccordionVariant {
    /// Separate bordered items.
    #[default]
    Default,
    /// Items joined by dividers, without surfaces.
    Flush,
    /// Thin dividers with a compact rhythm.
    Hairline,
}

impl AccordionVariant {
    /// The `data-variant` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Flush => "flush",
            Self::Hairline => "hairline",
        }
    }
}

/// Disclosure indicator of a [`Collapsible`] or every item of an [`Accordion`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CollapsibleIcon {
    /// A chevron that turns when open.
    #[default]
    Chevron,
    /// No indicator.
    None,
    /// A plus that becomes a minus when open.
    Plus,
}

impl CollapsibleIcon {
    /// The class suffix.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Chevron => "chevron",
            Self::None => "none",
            Self::Plus => "plus",
        }
    }
}

/// Disclosure indicator inherited by every [`Accordion`] item.
pub type AccordionIcon = CollapsibleIcon;

/// How many [`Accordion`] items may be open at once.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum AccordionType {
    /// At most one item.
    Single,
    /// Any number of items, like independent `<details>` elements.
    #[default]
    Multiple,
}

/// The open values after toggling `item`, following the accordion type.
pub(crate) fn accordion_next(
    current: &[String],
    item: &str,
    kind: AccordionType,
    collapsible: bool,
) -> Vec<String> {
    let open = current.iter().any(|value| value == item);

    match kind {
        AccordionType::Single if open && !collapsible => current.to_vec(),
        AccordionType::Single if open => Vec::new(),
        AccordionType::Single => vec![item.to_string()],
        AccordionType::Multiple if open => current
            .iter()
            .filter(|value| *value != item)
            .cloned()
            .collect(),
        AccordionType::Multiple => {
            let mut next = current.to_vec();
            next.push(item.to_string());
            next
        }
    }
}

#[derive(Clone, Copy)]
struct AccordionContext {
    /// The open values, mirrored for descendants after every render.
    value: Signal<Vec<String>>,
    state: Controllable<Vec<String>>,
    /// `(type, collapsible)`, mirrored after every render.
    mode: Signal<(AccordionType, bool)>,
}

impl AccordionContext {
    fn is_open(&self, item: &str) -> bool {
        self.value.read().iter().any(|value| value == item)
    }

    fn toggle(&self, item: &str) {
        let (kind, collapsible) = *self.mode.peek();
        let next = accordion_next(&self.state.peek(), item, kind, collapsible);
        self.state.set(next);
    }
}

#[derive(Clone, Copy)]
struct DisclosureContext {
    open: Signal<bool>,
    toggle: Callback<()>,
}

fn use_disclosure(component: &str) -> DisclosureContext {
    try_use_context::<DisclosureContext>().unwrap_or_else(|| {
        panic!("{component} must be used inside a Lumen Collapsible or AccordionItem.")
    })
}

/// Writes `next` into `signal` when it changed, so descendants re-render.
fn mirror<T: PartialEq + 'static>(mut signal: Signal<T>, next: T) {
    if *signal.peek() != next {
        signal.set(next);
    }
}

/// Props for [`Accordion`].
#[derive(Props, Clone, PartialEq)]
pub struct AccordionProps {
    /// Visual treatment.
    #[props(default)]
    pub variant: AccordionVariant,
    /// Indicator for every item that does not set its own.
    #[props(default)]
    pub icon: AccordionIcon,
    /// Whether one or several items may be open.
    #[props(default)]
    pub r#type: AccordionType,
    /// In single mode, whether the open item can be closed. Defaults to `true`.
    #[props(default = true)]
    pub collapsible: bool,
    /// Open item values. Setting it makes the accordion controlled.
    pub value: Option<Vec<String>>,
    /// Initially open item values when uncontrolled.
    #[props(default)]
    pub default_value: Vec<String>,
    /// Called with the next open values.
    pub on_value_change: Option<EventHandler<Vec<String>>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// [`AccordionItem`]s, [`Collapsible`]s, or plain `details` elements.
    pub children: Element,
}

/// A stack of disclosures with single or multiple open items.
///
/// [`AccordionItem`]s and [`Collapsible`]s with a `value` share the accordion's open state. Plain
/// `details` children keep the browser's own behavior.
#[component]
pub fn Accordion(props: AccordionProps) -> Element {
    let state = use_controllable(
        props.value.clone(),
        || props.default_value.clone(),
        props.on_value_change,
    );
    let current = state.get();
    let value = use_signal(|| current.clone());
    let mode = use_signal(|| (props.r#type, props.collapsible));

    use_context_provider(|| AccordionContext { value, state, mode });
    mirror(value, current);
    mirror(mode, (props.r#type, props.collapsible));

    let icon_class = (props.icon != CollapsibleIcon::Chevron)
        .then(|| format!("ui-accordion--icon-{}", props.icon.as_str()));
    let class = compose([
        Some("ui-accordion"),
        (props.variant == AccordionVariant::Flush).then_some("ui-accordion--flush"),
        (props.variant == AccordionVariant::Hairline).then_some("ui-accordion--hairline"),
        icon_class.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        div { class, "data-variant": props.variant.as_str(), ..props.attributes, {props.children} }
    }
}

/// Props for [`AccordionItem`].
#[derive(Props, Clone, PartialEq)]
pub struct AccordionItemProps {
    /// Identifies the item in the accordion's open values.
    #[props(into)]
    pub value: String,
    /// Classes for the `details` element. It has none by default, like a plain `details` child.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<details>` or global attribute.
    #[props(extends = GlobalAttributes, extends = details)]
    pub attributes: Vec<Attribute>,
    /// An [`AccordionTrigger`] and an [`AccordionContent`].
    pub children: Element,
}

/// One `details` item of an [`Accordion`], open while its value is in the accordion's value.
#[component]
pub fn AccordionItem(props: AccordionItemProps) -> Element {
    let accordion = try_use_context::<AccordionContext>()
        .unwrap_or_else(|| panic!("AccordionItem must be used inside a Lumen Accordion."));
    let open = accordion.is_open(&props.value);
    let signal = use_signal(|| open);
    mirror(signal, open);

    let value = props.value.clone();
    let toggle = use_callback(move |()| accordion.toggle(&value));
    use_context_provider(|| DisclosureContext {
        open: signal,
        toggle,
    });

    rsx! {
        details { class: props.class, open, ..props.attributes, {props.children} }
    }
}

/// Props for [`Collapsible`].
#[derive(Props, Clone, PartialEq)]
pub struct CollapsibleProps {
    /// Open state. Setting it makes the collapsible controlled.
    pub open: Option<bool>,
    /// Initial open state when uncontrolled.
    #[props(default)]
    pub default_open: bool,
    /// Called with the next open state.
    pub on_open_change: Option<EventHandler<bool>>,
    /// Joins the open state of the surrounding [`Accordion`] under this value. Ignored outside an
    /// accordion; `open` and `default_open` are ignored while joined.
    #[props(into)]
    pub value: Option<String>,
    /// Indicator. Unset inherits the accordion icon, or the chevron.
    pub icon: Option<CollapsibleIcon>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<details>` or global attribute.
    #[props(extends = GlobalAttributes, extends = details)]
    pub attributes: Vec<Attribute>,
    /// A [`CollapsibleTrigger`] and a [`CollapsibleContent`], or a plain `summary` and content.
    pub children: Element,
}

/// A single `details` disclosure with controlled or uncontrolled open state.
///
/// With [`CollapsibleTrigger`] and [`CollapsibleContent`], the state works on every renderer.
/// Plain `summary` children keep the browser's native toggle on the web only.
#[component]
pub fn Collapsible(props: CollapsibleProps) -> Element {
    let accordion = try_use_context::<AccordionContext>().filter(|_| props.value.is_some());
    let state = use_controllable(props.open, || props.default_open, props.on_open_change);
    let open = match (accordion, props.value.as_deref()) {
        (Some(accordion), Some(value)) => accordion.is_open(value),
        _ => state.get(),
    };
    let signal = use_signal(|| open);
    mirror(signal, open);

    let value = props.value.clone();
    let toggle = use_callback(move |()| match (accordion, value.as_deref()) {
        (Some(accordion), Some(value)) => accordion.toggle(value),
        _ => state.set(!state.peek()),
    });
    use_context_provider(|| DisclosureContext {
        open: signal,
        toggle,
    });

    let icon_class = props
        .icon
        .map(|icon| format!("ui-collapsible--icon-{}", icon.as_str()));
    let class = compose([
        Some("ui-collapsible"),
        icon_class.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        details {
            class,
            "data-ui-collapsible": "true",
            open,
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`CollapsibleTrigger`] and [`AccordionTrigger`].
#[derive(Props, Clone, PartialEq)]
pub struct CollapsibleTriggerProps {
    /// Classes for the `summary` element.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute.
    #[props(extends = GlobalAttributes)]
    pub attributes: Vec<Attribute>,
    /// The always-visible label.
    pub children: Element,
}

/// The `summary` that toggles the surrounding [`Collapsible`] or [`AccordionItem`].
///
/// Click, Enter, and Space toggle the state. It has `tabindex="0"` because Dioxus Native does not
/// make `summary` focusable by itself; browsers already do.
#[component]
pub fn CollapsibleTrigger(props: CollapsibleTriggerProps) -> Element {
    let disclosure = use_disclosure("CollapsibleTrigger");
    let toggle = disclosure.toggle;

    rsx! {
        summary {
            class: props.class,
            tabindex: "0",
            onclick: move |event| {
                // The browser would toggle `details` itself; the Rust state owns it instead.
                event.prevent_default();
                toggle.call(());
            },
            onkeydown: move |event| match event.key() {
                Key::Enter => {
                    event.prevent_default();
                    toggle.call(());
                }
                Key::Character(character) if character == " " => event.prevent_default(),
                _ => {}
            },
            onkeyup: move |event| {
                if matches!(event.key(), Key::Character(character) if character == " ") {
                    event.prevent_default();
                    toggle.call(());
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// The trigger of an [`AccordionItem`]. Same as [`CollapsibleTrigger`].
#[component]
pub fn AccordionTrigger(props: CollapsibleTriggerProps) -> Element {
    rsx! {
        CollapsibleTrigger { ..props }
    }
}

/// Props for [`CollapsibleContent`] and [`AccordionContent`].
#[derive(Props, Clone, PartialEq)]
pub struct CollapsibleContentProps {
    /// Classes for the content wrapper.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The disclosed content.
    pub children: Element,
}

/// The content of the surrounding [`Collapsible`] or [`AccordionItem`], `hidden` while closed.
#[component]
pub fn CollapsibleContent(props: CollapsibleContentProps) -> Element {
    let disclosure = use_disclosure("CollapsibleContent");
    let open = (disclosure.open)();

    rsx! {
        div {
            class: props.class,
            "data-slot": "collapsible-content",
            hidden: !open,
            ..props.attributes,
            {props.children}
        }
    }
}

/// The content of an [`AccordionItem`]. Same as [`CollapsibleContent`].
#[component]
pub fn AccordionContent(props: CollapsibleContentProps) -> Element {
    rsx! {
        CollapsibleContent { ..props }
    }
}

#[cfg(test)]
mod tests {
    use super::{AccordionType, accordion_next};

    fn values(items: &[&str]) -> Vec<String> {
        items.iter().map(|item| (*item).to_string()).collect()
    }

    #[test]
    fn single_mode_opens_one_item() {
        let single = AccordionType::Single;
        assert_eq!(accordion_next(&[], "a", single, true), values(&["a"]));
        assert_eq!(
            accordion_next(&values(&["a"]), "b", single, true),
            values(&["b"])
        );
        assert_eq!(
            accordion_next(&values(&["a"]), "a", single, true),
            values(&[])
        );
        assert_eq!(
            accordion_next(&values(&["a"]), "a", single, false),
            values(&["a"])
        );
    }

    #[test]
    fn multiple_mode_toggles_membership() {
        let multiple = AccordionType::Multiple;
        assert_eq!(
            accordion_next(&values(&["a"]), "b", multiple, true),
            values(&["a", "b"])
        );
        assert_eq!(
            accordion_next(&values(&["a", "b"]), "a", multiple, false),
            values(&["b"])
        );
    }
}