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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! `DatePicker` (a trigger, a hidden native date input, and a [`Calendar`] dialog) and
//! `DateRangePicker` (a start and an end `DatePicker` that constrain each other).

// cspell:words autofocus

use std::rc::Rc;

use dioxus::core::AttributeValue;
use dioxus::prelude::*;

use super::calendar::{Calendar, CalendarLabels, ResolvedDateLabels};
use super::dates::CivilDate;
use crate::class::{Glass, compose};
use crate::hooks::{use_controllable, use_id_or};
use crate::icons::{icon_svg, lucide};
use crate::overlay::{DismissLayer, focus_element, is_escape};

/// The text value of an attribute the app spread on a component, if it has one.
fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
    attributes
        .iter()
        .rev()
        .find(|attribute| attribute.name == name)
        .and_then(|attribute| match &attribute.value {
            AttributeValue::Text(text) => Some(text.clone()),
            AttributeValue::Bool(value) => Some(value.to_string()),
            AttributeValue::Int(value) => Some(value.to_string()),
            AttributeValue::Float(value) => Some(value.to_string()),
            _ => None,
        })
}

/// Shared state of the pickers inside a [`DateRangePicker`].
#[derive(Clone, Copy)]
struct DateRangeContext {
    /// The order the next picker gets, in mount order. Not reactive: pickers take one while
    /// rendering for the first time.
    next_order: CopyValue<usize>,
    /// `(order, value)` of every mounted picker. Pickers register from an effect and unregister
    /// when they unmount, so the first and last entries are always mounted pickers.
    values: Signal<Vec<(usize, String)>>,
    /// Set after the first render, like the React effect that marks range parts after mounting.
    mounted: Signal<bool>,
    on_change: CopyValue<Option<EventHandler<DateRangePickerValue>>>,
}

impl DateRangeContext {
    /// The orders of the first and last registered pickers, when at least two are registered.
    fn ends(list: &[(usize, String)]) -> Option<(usize, usize)> {
        if list.len() < 2 {
            return None;
        }

        let orders = || list.iter().map(|(order, _)| *order);

        orders().min().zip(orders().max())
    }

    fn range(self) -> DateRangePickerValue {
        let list = self.values.read();
        let Some((start, end)) = Self::ends(&list) else {
            return DateRangePickerValue::default();
        };
        let value = |order: usize| {
            list.iter()
                .find(|(entry, _)| *entry == order)
                .map(|(_, value)| value.clone())
                .filter(|value| !value.is_empty())
        };

        DateRangePickerValue {
            start: value(start),
            end: value(end),
        }
    }

    /// Where the picker at `order` sits, once the range has mounted.
    fn part(self, order: usize) -> Option<RangePart> {
        if !*self.mounted.read() {
            return None;
        }

        let (first, last) = Self::ends(&self.values.read())?;

        if order == first {
            Some(RangePart::Start)
        } else if order == last {
            Some(RangePart::End)
        } else {
            None
        }
    }

    /// Stores the value of the picker at `order`, registering it when it is new.
    fn store(self, order: usize, next: &str) {
        let mut values = self.values;
        let mut list = values.write();

        if let Some(entry) = list.iter_mut().find(|(entry, _)| *entry == order) {
            next.clone_into(&mut entry.1);
        } else {
            list.push((order, next.to_string()));
        }
    }

    /// Removes the picker at `order` when it unmounts.
    fn unregister(self, order: usize) {
        let mut values = self.values;

        // The range itself may already be gone when the whole tree unmounts.
        if let Ok(mut list) = values.try_write() {
            list.retain(|(entry, _)| *entry != order);
        }
    }

    /// Records a user change of the picker at `order` and reports the new range.
    fn commit(self, order: usize, next: &str) {
        self.store(order, next);

        if let Some(handler) = *self.on_change.peek() {
            handler.call(self.range());
        }
    }
}

/// Where a `DatePicker` sits inside a [`DateRangePicker`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RangePart {
    Start,
    End,
}

/// Registers a picker with an enclosing [`DateRangePicker`] and returns its part once mounted.
fn use_range_part(value: &str) -> (Option<RangePart>, Option<(DateRangeContext, usize)>) {
    let context = try_use_context::<DateRangeContext>();
    let order = use_hook(|| {
        context.map(|context| {
            let mut next_order = context.next_order;
            let order = *next_order.peek();
            next_order.set(order + 1);
            order
        })
    });
    let range = context.zip(order);

    // Register, and keep the stored value in sync, after rendering rather than while rendering.
    let synced = value.to_string();
    use_effect(use_reactive((&synced,), move |(synced,)| {
        if let Some((context, order)) = range {
            context.store(order, &synced);
        }
    }));
    use_drop(move || {
        if let Some((context, order)) = range {
            context.unregister(order);
        }
    });

    let part = range.and_then(|(context, order)| context.part(order));

    (part, range)
}

/// Props for [`DatePicker`].
#[derive(Props, Clone, PartialEq)]
pub struct DatePickerProps {
    /// Controlled value (`YYYY-MM-DD`, or empty for no date).
    #[props(into)]
    pub value: Option<String>,
    /// Initial value when uncontrolled.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with the selected date.
    pub on_value_change: Option<EventHandler<String>>,
    /// Formats the selected date for the trigger. Defaults to the en-US medium date (`Mar 1, 2024`).
    pub format_date: Option<Callback<String, String>>,
    /// Label overrides, shared with the calendar.
    pub labels: Option<CalendarLabels>,
    /// Language of the built-in labels: `en`, `es`, `fr`, `pt`, or `ar`.
    #[props(into)]
    pub locale: Option<String>,
    /// Trigger text while no date is selected. Defaults to the "Choose date" label.
    #[props(into)]
    pub placeholder: Option<String>,
    /// Id of the trigger button; the native input and dialog derive their ids from it.
    #[props(into)]
    pub id: Option<String>,
    /// Form field name of the native date input.
    #[props(into)]
    pub name: Option<String>,
    /// Earliest selectable date (`YYYY-MM-DD`).
    #[props(into)]
    pub min: Option<String>,
    /// Latest selectable date (`YYYY-MM-DD`).
    #[props(into)]
    pub max: Option<String>,
    /// Disables the picker.
    #[props(default)]
    pub disabled: bool,
    /// Shows the value without letting the user change it.
    #[props(default)]
    pub read_only: bool,
    /// Marks the native input as required.
    pub required: Option<bool>,
    /// Overrides today's date (`YYYY-MM-DD`) in the calendar.
    #[props(into)]
    pub today: Option<String>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Fires when the hidden native date input changes.
    pub onchange: Option<EventHandler<FormEvent>>,
    /// Extra classes appended after the Lumen classes on the field wrapper.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute. Like lumen-react they land on the hidden native
    /// input; `aria_label`, `aria_labelledby`, `aria_describedby`, `aria_errormessage`, and
    /// `aria_invalid` are also copied to the trigger button.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// A date field: a button that shows the value and opens a [`Calendar`] in a dialog, plus a
/// hidden native `<input type="date">` that submits the value with forms.
///
/// Click or Arrow Down opens the dialog, Escape closes it and returns focus to the trigger, and
/// picking a day closes it.
#[component]
pub fn DatePicker(props: DatePickerProps) -> Element {
    let id = use_id_or(props.id.as_deref());
    let native_id = format!("{id}-native");
    let popover_id = format!("{id}-popover");
    let unavailable = props.disabled || props.read_only;
    let value = use_controllable(
        props.value.clone(),
        || props.default_value.clone().unwrap_or_default(),
        props.on_value_change,
    );
    let selected = value.get();
    let (range_part, range) = use_range_part(&selected);
    let mut requested_open = use_signal(|| false);
    let open = requested_open() && !unavailable;
    let mut trigger = use_signal(|| None::<Rc<MountedData>>);

    let labels = ResolvedDateLabels::new(props.locale.as_deref(), props.labels.as_ref());
    let placeholder = props
        .placeholder
        .clone()
        .unwrap_or_else(|| labels.choose_date.clone());
    let display = match CivilDate::parse(&selected) {
        Some(_) if props.format_date.is_some() => props
            .format_date
            .map_or_else(String::new, |format| format.call(selected.clone())),
        Some(date) => labels.short_date(date),
        None => placeholder,
    };

    // Inside a range, the start cannot pass the end and the end cannot precede the start.
    let range_value = range.map_or_else(DateRangePickerValue::default, |(context, _)| {
        context.range()
    });
    let calendar_min = match range_part {
        Some(RangePart::End) => range_value.start.clone().or_else(|| props.min.clone()),
        _ => props.min.clone(),
    };
    let calendar_max = match range_part {
        Some(RangePart::Start) => range_value.end.clone().or_else(|| props.max.clone()),
        _ => props.max.clone(),
    };

    let attributes = props.attributes.clone();
    let aria_label = attribute_text(&attributes, "aria-label");
    let aria_labelledby = attribute_text(&attributes, "aria-labelledby");
    let aria_describedby = attribute_text(&attributes, "aria-describedby");
    let aria_errormessage = attribute_text(&attributes, "aria-errormessage");
    let aria_invalid = attribute_text(&attributes, "aria-invalid");

    let glass = props.glass.class("ui-date-picker-field");
    let class = compose([
        Some("ui-date-picker-field"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);
    let glass_on = props.glass != Glass::Off;
    let read_only = props.read_only;
    let disabled = props.disabled;
    let onchange = props.onchange;

    let placeholder_shown = selected.is_empty();
    let (native_min, native_max) = (calendar_min.clone(), calendar_max.clone());

    let mut close_and_focus = move || {
        requested_open.set(false);
        focus_element(trigger.peek().clone());
    };

    rsx! {
        div {
            class,
            "data-placeholder": placeholder_shown.then_some("true"),
            "data-range-part": range_part.map(|part| match part {
                RangePart::Start => "start",
                RangePart::End => "end",
            }),
            "data-ui-date-picker": "true",
            "data-ui-owner": "dioxus",
            "data-ui-glass-track": glass_on.then_some("true"),
            onkeydown: move |event: KeyboardEvent| {
                if open && is_escape(&event) && !event.is_composing() {
                    event.prevent_default();
                    event.stop_propagation();
                    close_and_focus();
                }
            },
            input {
                aria_hidden: "true",
                class: "ui-date-picker ui-date-picker__native",
                "data-ui-date-picker-native": "true",
                "data-ui-enhanced": "true",
                disabled: props.disabled,
                id: native_id,
                max: native_max,
                min: native_min,
                name: props.name,
                required: props.required.unwrap_or(false),
                readonly: props.read_only,
                tabindex: "-1",
                r#type: "date",
                value: selected.clone(),
                onchange: move |event: FormEvent| {
                    if !value.is_controlled() {
                        value.set(event.value());
                    }

                    if let Some((context, order)) = range {
                        context.commit(order, &event.value());
                    }

                    if let Some(handler) = onchange {
                        handler.call(event);
                    }
                },
                ..attributes,
            }
            div { class: "ui-date-picker__control", "data-ui-date-picker-control": "true",
                button {
                    aria_controls: popover_id.clone(),
                    aria_expanded: if open { "true" } else { "false" },
                    aria_haspopup: "dialog",
                    aria_label,
                    aria_labelledby,
                    aria_describedby,
                    aria_errormessage,
                    aria_invalid,
                    aria_disabled: read_only.then_some("true"),
                    aria_required: props.required.map(|required| if required { "true" } else { "false" }),
                    class: "ui-input ui-date-picker ui-date-picker__trigger",
                    "data-ui-date-picker-trigger": "true",
                    disabled,
                    id: id.clone(),
                    r#type: "button",
                    onclick: move |_| {
                        if !unavailable {
                            requested_open.toggle();
                        }
                    },
                    onkeydown: move |event: KeyboardEvent| {
                        if event.key() == Key::ArrowDown && !unavailable {
                            event.prevent_default();
                            requested_open.set(true);
                        }
                    },
                    onmounted: move |event: MountedEvent| trigger.set(Some(event.data())),
                    span { "data-ui-date-picker-value": "true", "{display}" }
                    {icon_svg(&lucide::CALENDAR, "ui-icon__svg lucide-calendar ui-date-picker__icon")}
                }
                if open {
                    DismissLayer { on_dismiss: move |()| requested_open.set(false) }
                }
                div {
                    aria_label: labels.choose_date.clone(),
                    class: "ui-date-picker__popover",
                    "data-state": if open { "open" } else { "closed" },
                    "data-ui-date-picker-popover": "true",
                    hidden: !open,
                    id: popover_id,
                    role: "dialog",
                    Calendar {
                        key: if open { "open" } else { "closed" },
                        autofocus: open,
                        disabled: props.disabled,
                        read_only: props.read_only,
                        labels: props.labels.clone(),
                        locale: props.locale.clone(),
                        max: calendar_max,
                        min: calendar_min,
                        today: props.today.clone(),
                        value: selected.clone(),
                        on_value_change: move |next: String| {
                            if unavailable {
                                return;
                            }

                            if let Some((context, order)) = range {
                                context.commit(order, &next);
                            }

                            // Like lumen-react, every pick reports the date, even the selected one.
                            value.select(next);
                            close_and_focus();
                        },
                    }
                }
            }
        }
    }
}

/// The start and end dates of a [`DateRangePicker`]; unset ends are `None`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DateRangePickerValue {
    /// The start date (`YYYY-MM-DD`).
    pub start: Option<String>,
    /// The end date (`YYYY-MM-DD`).
    pub end: Option<String>,
}

impl DateRangePickerValue {
    /// `empty`, `selecting-end`, or `complete`, like `data-range-state`.
    pub fn state(&self) -> &'static str {
        match (&self.start, &self.end) {
            (None, _) => "empty",
            (Some(_), None) => "selecting-end",
            (Some(_), Some(_)) => "complete",
        }
    }
}

/// Props for [`DateRangePicker`].
#[derive(Props, Clone, PartialEq)]
pub struct DateRangePickerProps {
    /// Called when either date changes.
    pub on_range_change: Option<EventHandler<DateRangePickerValue>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The start and end [`DatePicker`]s, plus any labels or separators.
    pub children: Element,
}

/// Groups a start and an end [`DatePicker`]. After mounting, the first picker is marked as the
/// start and the last as the end, the start cannot be later than the end (and the reverse), and
/// the root reports `data-range-state`.
#[component]
pub fn DateRangePicker(props: DateRangePickerProps) -> Element {
    let context = use_context_provider(|| DateRangeContext {
        next_order: CopyValue::new(0),
        values: Signal::new(Vec::new()),
        mounted: Signal::new(false),
        on_change: CopyValue::new(None),
    });
    let mut mounted = context.mounted;
    let mut on_change = context.on_change;
    on_change.set(props.on_range_change);

    use_effect(move || {
        if !*mounted.peek() {
            mounted.set(true);
        }
    });

    let range = context.range();
    let class = compose([Some("ui-date-range-picker"), props.class.as_deref()]);
    let state = mounted().then(|| range.state());

    rsx! {
        div {
            class,
            "data-range-state": state,
            "data-ui-date-range-picker": "true",
            ..props.attributes,
            {props.children}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::DateRangePickerValue;

    #[test]
    fn range_state_follows_the_filled_ends() {
        let mut range = DateRangePickerValue::default();
        assert_eq!(range.state(), "empty");
        range.start = Some("2024-03-01".into());
        assert_eq!(range.state(), "selecting-end");
        range.end = Some("2024-03-09".into());
        assert_eq!(range.state(), "complete");
    }
}