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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! `LoadMore` and the state logic ported from `lumen-core/load-more`.

use std::rc::Rc;
use std::time::Duration;

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::overlay::focus_element;
use crate::time::sleep;

use super::selection_bar::{Announcer, SelectionBarCountLabel};
use super::util::{optional_text, resolve_safe_href};
use super::web::{Watcher, focus_element_by_id, set_busy_by_id, watch_visible};

/// Visible state of a [`LoadMore`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum LoadMoreState {
    /// Ready to request the next page.
    #[default]
    Idle,
    /// The app is fetching the next page.
    Loading,
    /// The last load failed; the button retries.
    Error,
    /// Nothing is left to load; the button hides.
    Done,
}

impl LoadMoreState {
    /// The `data-state` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Loading => "loading",
            Self::Error => "error",
            Self::Done => "done",
        }
    }

    /// Resolves the state like `resolveLumenLoadMoreState`: loading, then error, then done,
    /// then idle.
    pub fn resolve(loading: bool, error: bool, has_more: bool) -> Self {
        if loading {
            Self::Loading
        } else if error {
            Self::Error
        } else if has_more {
            Self::Idle
        } else {
            Self::Done
        }
    }
}

/// A request for the next page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LoadMoreRequest {
    /// True when the request retries a failed load.
    pub retry: bool,
}

/// The polite announcement after a load finishes, like `resolveLumenLoadMoreAnnouncement`:
/// the pluralized added count (or `loaded_label` when the feed is not counted), followed by
/// `done_label` once the feed is exhausted.
pub fn load_more_announcement(
    state: LoadMoreState,
    added: Option<u64>,
    added_label: &SelectionBarCountLabel,
    loaded_label: &str,
    done_label: &str,
    error_message: &str,
    locale: &str,
) -> Option<String> {
    match state {
        LoadMoreState::Loading => None,
        LoadMoreState::Error => Some(error_message.to_string()),
        LoadMoreState::Idle | LoadMoreState::Done => {
            let added_text = match added {
                None => Some(loaded_label.to_string()),
                Some(0) => None,
                Some(count) => Some(added_label.format(count, locale)),
            };
            let parts: Vec<String> = added_text
                .into_iter()
                .chain((state == LoadMoreState::Done).then(|| done_label.to_string()))
                .collect();

            (!parts.is_empty()).then(|| parts.join(" "))
        }
    }
}

/// Props a [`LoadMore`] reads from handlers and effects created on earlier renders.
#[derive(Clone, Default)]
struct LoadMoreLatest {
    state: LoadMoreState,
    item_count: Option<u64>,
    on_load_more: Option<EventHandler<LoadMoreRequest>>,
    added_label: SelectionBarCountLabel,
    loaded_label: String,
    done_label: String,
    error_message: String,
    locale: String,
    target: Option<String>,
    focus_new_items: bool,
    delay: Duration,
}

fn copy_or(value: Option<&String>, fallback: &str) -> String {
    match value {
        Some(text) if !text.trim().is_empty() => text.clone(),
        _ => fallback.to_string(),
    }
}

/// Props for [`LoadMore`].
// The flags mirror lumen-react's `loading`, `hasMore`, `error`, `auto`, and `focusNewItems` props.
#[allow(clippy::struct_excessive_bools)]
#[derive(Props, Clone, PartialEq)]
pub struct LoadMoreProps {
    /// Requests the next page. The app fetches, appends items, and updates `loading`,
    /// `has_more`, and `error`.
    pub on_load_more: Option<EventHandler<LoadMoreRequest>>,
    /// True while the app fetches the next page.
    #[props(default)]
    pub loading: bool,
    /// Set to false once the feed has no more items. Defaults to true.
    #[props(default = true)]
    pub has_more: bool,
    /// Marks the last load as failed.
    #[props(default)]
    pub error: bool,
    /// Custom error copy. A non-blank message also marks the last load as failed.
    #[props(into)]
    pub error_message: Option<String>,
    /// Number of items currently in the feed. Lumen counts the items added by each load from it
    /// (lumen-react counts the feed's DOM children instead).
    pub item_count: Option<u64>,
    /// Id of the feed container. On web and desktop it is marked busy while loading, and
    /// `focus_new_items` focuses its first new child.
    #[props(into)]
    pub target: Option<String>,
    /// Moves focus to the first new item after a load (web and desktop; needs `target` and
    /// `item_count`).
    #[props(default)]
    pub focus_new_items: bool,
    /// Requests the next page when the end of the feed scrolls into view (web and desktop). The
    /// button stays as a fallback.
    #[props(default)]
    pub auto: bool,
    /// Observer margin for `auto`. Defaults to `0px 0px 200px 0px`.
    #[props(into)]
    pub root_margin: Option<String>,
    /// Renders the control as a link to the next page, for server-rendered pages without
    /// JavaScript. Activating it still calls `on_load_more`.
    #[props(into)]
    pub href: Option<String>,
    /// Button text. Defaults to `Load more`.
    #[props(into)]
    pub label: Option<String>,
    /// Button text while loading. Defaults to `Loading…`.
    #[props(into)]
    pub loading_label: Option<String>,
    /// Button text after an error. Defaults to `Try again`.
    #[props(into)]
    pub retry_label: Option<String>,
    /// Shown and announced once `has_more` is false. Defaults to `No more items`.
    #[props(into)]
    pub done_label: Option<String>,
    /// Default error copy. Defaults to `Could not load more items.`.
    #[props(into)]
    pub error_label: Option<String>,
    /// Announced after a load when `item_count` is unset. Defaults to `More items loaded`.
    #[props(into)]
    pub loaded_label: Option<String>,
    /// Announced after a load. Defaults to `{count} item added` / `{count} items added`.
    #[props(default = SelectionBarCountLabel::plural("{count} item added", "{count} items added"), into)]
    pub added_label: SelectionBarCountLabel,
    /// Locale for plural rules and number formatting. Defaults to `en`.
    #[props(default = "en".to_string(), into)]
    pub locale: String,
    /// Milliseconds between announcements. Defaults to 150.
    #[props(default = 150)]
    pub announce_delay: u64,
    /// 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>,
}

/// A "Load more" control for a feed. It never fetches: activating it (or, with `auto`, the end
/// of the feed scrolling into view) calls `on_load_more`, and the app updates `loading`,
/// `has_more`, and `error`. Finished loads are announced politely.
#[component]
#[allow(clippy::too_many_lines)]
pub fn LoadMore(props: LoadMoreProps) -> Element {
    let custom_error = optional_text(props.error_message.as_deref());
    let state = LoadMoreState::resolve(
        props.loading,
        props.error || custom_error.is_some(),
        props.has_more,
    );
    let label = copy_or(props.label.as_ref(), "Load more");
    let loading_label = copy_or(props.loading_label.as_ref(), "Loading…");
    let retry_label = copy_or(props.retry_label.as_ref(), "Try again");
    let done_label = copy_or(props.done_label.as_ref(), "No more items");
    let error_label = copy_or(props.error_label.as_ref(), "Could not load more items.");
    let loaded_label = copy_or(props.loaded_label.as_ref(), "More items loaded");
    let error_message = custom_error.unwrap_or(error_label);
    let message = match state {
        LoadMoreState::Done => done_label.clone(),
        LoadMoreState::Error => error_message.clone(),
        LoadMoreState::Idle | LoadMoreState::Loading => String::new(),
    };
    let button_text = match state {
        LoadMoreState::Loading => loading_label,
        LoadMoreState::Error => retry_label,
        LoadMoreState::Idle | LoadMoreState::Done => label,
    };
    let href = props.href.as_deref().and_then(resolve_safe_href);
    let target = props
        .target
        .as_deref()
        .map(str::trim)
        .filter(|id| !id.is_empty())
        .map(str::to_string);
    let sentinel_id = format!("ui-load-more-{}-sentinel", use_unique_id());
    let announcer = Announcer::use_new();
    let mut previous = use_hook(|| CopyValue::new(None::<LoadMoreState>));
    let mut pending = use_hook(|| CopyValue::new(false));
    let mut count_at_request = use_hook(|| CopyValue::new(None::<u64>));
    let mut button_focused = use_hook(|| CopyValue::new(false));
    let mut message_node = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
    let mut message_focusable = use_signal(|| false);
    let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));
    // The latest props, read by handlers and effects that were created on an earlier render.
    let mut latest = use_hook(|| CopyValue::new(LoadMoreLatest::default()));
    let item_count = props.item_count;

    latest.set(LoadMoreLatest {
        state,
        item_count,
        on_load_more: props.on_load_more,
        added_label: props.added_label.clone(),
        loaded_label,
        done_label: done_label.clone(),
        error_message: error_message.clone(),
        locale: props.locale.clone(),
        target: target.clone(),
        focus_new_items: props.focus_new_items,
        delay: Duration::from_millis(props.announce_delay),
    });

    let mut request = move |retry: bool| {
        let current = latest.peek().state;

        if *pending.peek() || current == LoadMoreState::Loading || current == LoadMoreState::Done {
            return;
        }

        let item_count = latest.peek().item_count;
        count_at_request.set(item_count);
        pending.set(true);

        // Release the guard even when the app ignores the request and never re-renders.
        spawn(async move {
            sleep(Duration::ZERO).await;
            pending.set(false);
        });

        if let Some(handler) = latest.peek().on_load_more {
            handler.call(LoadMoreRequest { retry });
        }
    };

    // Busy feed while loading (web and desktop).
    let busy_target = target.clone();
    use_effect(use_reactive(
        (&busy_target, &(state == LoadMoreState::Loading)),
        move |(target, busy)| {
            if let Some(target) = target {
                set_busy_by_id(target, busy);
            }
        },
    ));

    // Announcements and focus after each state change.
    use_effect(use_reactive(
        (&state, &item_count),
        move |(state, item_count)| {
            let before = *previous.peek();
            pending.set(false);

            if before == Some(state) {
                return;
            }

            previous.set(Some(state));
            let props = latest.peek().clone();
            let mut focus_moved = false;

            if before == Some(LoadMoreState::Loading) {
                let at_request = count_at_request.write().take();
                let added = at_request
                    .zip(item_count)
                    .map(|(before, now)| now.saturating_sub(before));

                if let Some(text) = load_more_announcement(
                    state,
                    added,
                    &props.added_label,
                    &props.loaded_label,
                    &props.done_label,
                    &props.error_message,
                    &props.locale,
                ) {
                    announcer.announce(text, props.delay);
                }

                if state != LoadMoreState::Error
                    && props.focus_new_items
                    && added.unwrap_or(0) > 0
                    && let (Some(target), Some(index)) = (props.target, at_request)
                {
                    focus_moved = true;
                    let index = usize::try_from(index).unwrap_or(usize::MAX);

                    spawn(async move {
                        focus_element_by_id(target, Some(index)).await;
                    });
                }

                if state == LoadMoreState::Idle
                    && let Some(observer) = *watcher.peek()
                {
                    observer.send("refresh");
                }
            }

            // The button hides once the feed is done; keep focus on the message instead of the page.
            if !focus_moved
                && state == LoadMoreState::Done
                && before.is_some()
                && *button_focused.peek()
            {
                message_focusable.set(true);
                focus_element(message_node.peek().clone());
            }
        },
    ));

    // Infinite mode: the sentinel requests in the idle state only, so errors wait for a retry.
    let margin = props
        .root_margin
        .clone()
        .unwrap_or_else(|| "0px 0px 200px 0px".to_string());
    let observed = props.auto.then(|| sentinel_id.clone());
    use_effect(use_reactive(
        (&observed, &margin),
        move |(observed, margin)| {
            if let Some(previous) = watcher.write().take() {
                previous.stop();
            }

            if let Some(id) = observed {
                let next = watch_visible(id, margin, move || {
                    if latest.peek().state == LoadMoreState::Idle {
                        request(false);
                    }
                });
                watcher.set(Some(next));
            }
        },
    ));
    use_drop(move || {
        if let Some(previous) = watcher.write().take() {
            previous.stop();
        }
    });

    let class = compose([Some("ui-load-more"), props.class.as_deref()]);
    let loading = state == LoadMoreState::Loading;
    let control_class = "ui-button ui-button--outline ui-button--default-size ui-load-more__button";
    let mut on_activate = move |event: MouseEvent, link: bool| {
        // The href is a no-script fallback; once running, the page stays and the app appends items.
        if link {
            event.prevent_default();
        }

        let current = latest.peek().state;

        if current != LoadMoreState::Loading {
            request(current == LoadMoreState::Error);
        }
    };
    let content = rsx! {
        span { aria_hidden: "true", class: "ui-spinner", "data-slot": "load-more-spinner", hidden: !loading }
        span { class: "ui-button__content", "data-slot": "load-more-label", "{button_text}" }
    };

    rsx! {
        div {
            aria_busy: loading.then_some("true"),
            class,
            "data-auto": props.auto.then_some(""),
            "data-focus-new-items": props.focus_new_items.then_some(""),
            "data-slot": "load-more",
            "data-state": state.as_str(),
            "data-target": props.target.clone(),
            "data-ui-load-more": "",
            "data-ui-owner": "dioxus",
            ..props.attributes,
            span {
                aria_hidden: "true",
                class: "ui-load-more__sentinel",
                "data-slot": "load-more-sentinel",
                id: props.auto.then_some(sentinel_id),
            }
            if let Some(href) = href {
                a {
                    aria_disabled: loading.then_some("true"),
                    class: control_class,
                    "data-slot": "load-more-button",
                    hidden: state == LoadMoreState::Done,
                    href,
                    onclick: move |event| on_activate(event, true),
                    onfocus: move |_| button_focused.set(true),
                    onblur: move |_| button_focused.set(false),
                    {content}
                }
            } else {
                button {
                    r#type: "button",
                    aria_disabled: loading.then_some("true"),
                    class: control_class,
                    "data-slot": "load-more-button",
                    hidden: state == LoadMoreState::Done,
                    onclick: move |event| on_activate(event, false),
                    onfocus: move |_| button_focused.set(true),
                    onblur: move |_| button_focused.set(false),
                    {content}
                }
            }
            p {
                class: "ui-load-more__message",
                "data-slot": "load-more-message",
                "data-state": state.as_str(),
                hidden: message.is_empty(),
                tabindex: message_focusable().then_some("-1"),
                onmounted: move |event| message_node.set(Some(event.data())),
                "{message}"
            }
            span {
                aria_atomic: "true",
                aria_live: "polite",
                class: "ui-load-more__status",
                "data-slot": "load-more-status",
                role: "status",
                "{announcer.text}"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{LoadMoreState, SelectionBarCountLabel, load_more_announcement};

    #[test]
    fn state_precedence_matches_lumen_core() {
        assert_eq!(
            LoadMoreState::resolve(true, true, false),
            LoadMoreState::Loading
        );
        assert_eq!(
            LoadMoreState::resolve(false, true, false),
            LoadMoreState::Error
        );
        assert_eq!(
            LoadMoreState::resolve(false, false, false),
            LoadMoreState::Done
        );
        assert_eq!(
            LoadMoreState::resolve(false, false, true),
            LoadMoreState::Idle
        );
    }

    #[test]
    fn announcements_count_added_items() {
        let label = SelectionBarCountLabel::plural("{count} item added", "{count} items added");
        let announce = |state, added| {
            load_more_announcement(
                state,
                added,
                &label,
                "More items loaded",
                "No more items",
                "Failed",
                "en",
            )
        };
        assert_eq!(
            announce(LoadMoreState::Idle, Some(3)).as_deref(),
            Some("3 items added")
        );
        assert_eq!(
            announce(LoadMoreState::Idle, Some(1)).as_deref(),
            Some("1 item added")
        );
        assert_eq!(announce(LoadMoreState::Idle, Some(0)), None);
        assert_eq!(
            announce(LoadMoreState::Idle, None).as_deref(),
            Some("More items loaded")
        );
        assert_eq!(
            announce(LoadMoreState::Done, Some(2)).as_deref(),
            Some("2 items added No more items")
        );
        assert_eq!(
            announce(LoadMoreState::Done, Some(0)).as_deref(),
            Some("No more items")
        );
        assert_eq!(
            announce(LoadMoreState::Error, Some(2)).as_deref(),
            Some("Failed")
        );
        assert_eq!(announce(LoadMoreState::Loading, Some(2)), None);
    }
}