Skip to main content

lumen_dioxus/navigation/
load_more.rs

1//! `LoadMore` and the state logic ported from `lumen-core/load-more`.
2
3use std::rc::Rc;
4use std::time::Duration;
5
6use dioxus::prelude::*;
7
8use crate::class::compose;
9use crate::hooks::use_unique_id;
10use crate::overlay::focus_element;
11use crate::time::sleep;
12
13use super::selection_bar::{Announcer, SelectionBarCountLabel};
14use super::util::{optional_text, resolve_safe_href};
15use super::web::{Watcher, focus_element_by_id, set_busy_by_id, watch_visible};
16
17/// Visible state of a [`LoadMore`].
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum LoadMoreState {
21    /// Ready to request the next page.
22    #[default]
23    Idle,
24    /// The app is fetching the next page.
25    Loading,
26    /// The last load failed; the button retries.
27    Error,
28    /// Nothing is left to load; the button hides.
29    Done,
30}
31
32impl LoadMoreState {
33    /// The `data-state` value.
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Idle => "idle",
37            Self::Loading => "loading",
38            Self::Error => "error",
39            Self::Done => "done",
40        }
41    }
42
43    /// Resolves the state like `resolveLumenLoadMoreState`: loading, then error, then done,
44    /// then idle.
45    pub fn resolve(loading: bool, error: bool, has_more: bool) -> Self {
46        if loading {
47            Self::Loading
48        } else if error {
49            Self::Error
50        } else if has_more {
51            Self::Idle
52        } else {
53            Self::Done
54        }
55    }
56}
57
58/// A request for the next page.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct LoadMoreRequest {
61    /// True when the request retries a failed load.
62    pub retry: bool,
63}
64
65/// The polite announcement after a load finishes, like `resolveLumenLoadMoreAnnouncement`:
66/// the pluralized added count (or `loaded_label` when the feed is not counted), followed by
67/// `done_label` once the feed is exhausted.
68pub fn load_more_announcement(
69    state: LoadMoreState,
70    added: Option<u64>,
71    added_label: &SelectionBarCountLabel,
72    loaded_label: &str,
73    done_label: &str,
74    error_message: &str,
75    locale: &str,
76) -> Option<String> {
77    match state {
78        LoadMoreState::Loading => None,
79        LoadMoreState::Error => Some(error_message.to_string()),
80        LoadMoreState::Idle | LoadMoreState::Done => {
81            let added_text = match added {
82                None => Some(loaded_label.to_string()),
83                Some(0) => None,
84                Some(count) => Some(added_label.format(count, locale)),
85            };
86            let parts: Vec<String> = added_text
87                .into_iter()
88                .chain((state == LoadMoreState::Done).then(|| done_label.to_string()))
89                .collect();
90
91            (!parts.is_empty()).then(|| parts.join(" "))
92        }
93    }
94}
95
96/// Props a [`LoadMore`] reads from handlers and effects created on earlier renders.
97#[derive(Clone, Default)]
98struct LoadMoreLatest {
99    state: LoadMoreState,
100    item_count: Option<u64>,
101    on_load_more: Option<EventHandler<LoadMoreRequest>>,
102    added_label: SelectionBarCountLabel,
103    loaded_label: String,
104    done_label: String,
105    error_message: String,
106    locale: String,
107    target: Option<String>,
108    focus_new_items: bool,
109    delay: Duration,
110}
111
112fn copy_or(value: Option<&String>, fallback: &str) -> String {
113    match value {
114        Some(text) if !text.trim().is_empty() => text.clone(),
115        _ => fallback.to_string(),
116    }
117}
118
119/// Props for [`LoadMore`].
120// The flags mirror lumen-react's `loading`, `hasMore`, `error`, `auto`, and `focusNewItems` props.
121#[allow(clippy::struct_excessive_bools)]
122#[derive(Props, Clone, PartialEq)]
123pub struct LoadMoreProps {
124    /// Requests the next page. The app fetches, appends items, and updates `loading`,
125    /// `has_more`, and `error`.
126    pub on_load_more: Option<EventHandler<LoadMoreRequest>>,
127    /// True while the app fetches the next page.
128    #[props(default)]
129    pub loading: bool,
130    /// Set to false once the feed has no more items. Defaults to true.
131    #[props(default = true)]
132    pub has_more: bool,
133    /// Marks the last load as failed.
134    #[props(default)]
135    pub error: bool,
136    /// Custom error copy. A non-blank message also marks the last load as failed.
137    #[props(into)]
138    pub error_message: Option<String>,
139    /// Number of items currently in the feed. Lumen counts the items added by each load from it
140    /// (lumen-react counts the feed's DOM children instead).
141    pub item_count: Option<u64>,
142    /// Id of the feed container. On web and desktop it is marked busy while loading, and
143    /// `focus_new_items` focuses its first new child.
144    #[props(into)]
145    pub target: Option<String>,
146    /// Moves focus to the first new item after a load (web and desktop; needs `target` and
147    /// `item_count`).
148    #[props(default)]
149    pub focus_new_items: bool,
150    /// Requests the next page when the end of the feed scrolls into view (web and desktop). The
151    /// button stays as a fallback.
152    #[props(default)]
153    pub auto: bool,
154    /// Observer margin for `auto`. Defaults to `0px 0px 200px 0px`.
155    #[props(into)]
156    pub root_margin: Option<String>,
157    /// Renders the control as a link to the next page, for server-rendered pages without
158    /// JavaScript. Activating it still calls `on_load_more`.
159    #[props(into)]
160    pub href: Option<String>,
161    /// Button text. Defaults to `Load more`.
162    #[props(into)]
163    pub label: Option<String>,
164    /// Button text while loading. Defaults to `Loading…`.
165    #[props(into)]
166    pub loading_label: Option<String>,
167    /// Button text after an error. Defaults to `Try again`.
168    #[props(into)]
169    pub retry_label: Option<String>,
170    /// Shown and announced once `has_more` is false. Defaults to `No more items`.
171    #[props(into)]
172    pub done_label: Option<String>,
173    /// Default error copy. Defaults to `Could not load more items.`.
174    #[props(into)]
175    pub error_label: Option<String>,
176    /// Announced after a load when `item_count` is unset. Defaults to `More items loaded`.
177    #[props(into)]
178    pub loaded_label: Option<String>,
179    /// Announced after a load. Defaults to `{count} item added` / `{count} items added`.
180    #[props(default = SelectionBarCountLabel::plural("{count} item added", "{count} items added"), into)]
181    pub added_label: SelectionBarCountLabel,
182    /// Locale for plural rules and number formatting. Defaults to `en`.
183    #[props(default = "en".to_string(), into)]
184    pub locale: String,
185    /// Milliseconds between announcements. Defaults to 150.
186    #[props(default = 150)]
187    pub announce_delay: u64,
188    /// Extra classes appended after the Lumen class.
189    #[props(into)]
190    pub class: Option<String>,
191    /// Any other `<div>` or global attribute.
192    #[props(extends = GlobalAttributes, extends = div)]
193    pub attributes: Vec<Attribute>,
194}
195
196/// A "Load more" control for a feed. It never fetches: activating it (or, with `auto`, the end
197/// of the feed scrolling into view) calls `on_load_more`, and the app updates `loading`,
198/// `has_more`, and `error`. Finished loads are announced politely.
199#[component]
200#[allow(clippy::too_many_lines)]
201pub fn LoadMore(props: LoadMoreProps) -> Element {
202    let custom_error = optional_text(props.error_message.as_deref());
203    let state = LoadMoreState::resolve(
204        props.loading,
205        props.error || custom_error.is_some(),
206        props.has_more,
207    );
208    let label = copy_or(props.label.as_ref(), "Load more");
209    let loading_label = copy_or(props.loading_label.as_ref(), "Loading…");
210    let retry_label = copy_or(props.retry_label.as_ref(), "Try again");
211    let done_label = copy_or(props.done_label.as_ref(), "No more items");
212    let error_label = copy_or(props.error_label.as_ref(), "Could not load more items.");
213    let loaded_label = copy_or(props.loaded_label.as_ref(), "More items loaded");
214    let error_message = custom_error.unwrap_or(error_label);
215    let message = match state {
216        LoadMoreState::Done => done_label.clone(),
217        LoadMoreState::Error => error_message.clone(),
218        LoadMoreState::Idle | LoadMoreState::Loading => String::new(),
219    };
220    let button_text = match state {
221        LoadMoreState::Loading => loading_label,
222        LoadMoreState::Error => retry_label,
223        LoadMoreState::Idle | LoadMoreState::Done => label,
224    };
225    let href = props.href.as_deref().and_then(resolve_safe_href);
226    let target = props
227        .target
228        .as_deref()
229        .map(str::trim)
230        .filter(|id| !id.is_empty())
231        .map(str::to_string);
232    let sentinel_id = format!("ui-load-more-{}-sentinel", use_unique_id());
233    let announcer = Announcer::use_new();
234    let mut previous = use_hook(|| CopyValue::new(None::<LoadMoreState>));
235    let mut pending = use_hook(|| CopyValue::new(false));
236    let mut count_at_request = use_hook(|| CopyValue::new(None::<u64>));
237    let mut button_focused = use_hook(|| CopyValue::new(false));
238    let mut message_node = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
239    let mut message_focusable = use_signal(|| false);
240    let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));
241    // The latest props, read by handlers and effects that were created on an earlier render.
242    let mut latest = use_hook(|| CopyValue::new(LoadMoreLatest::default()));
243    let item_count = props.item_count;
244
245    latest.set(LoadMoreLatest {
246        state,
247        item_count,
248        on_load_more: props.on_load_more,
249        added_label: props.added_label.clone(),
250        loaded_label,
251        done_label: done_label.clone(),
252        error_message: error_message.clone(),
253        locale: props.locale.clone(),
254        target: target.clone(),
255        focus_new_items: props.focus_new_items,
256        delay: Duration::from_millis(props.announce_delay),
257    });
258
259    let mut request = move |retry: bool| {
260        let current = latest.peek().state;
261
262        if *pending.peek() || current == LoadMoreState::Loading || current == LoadMoreState::Done {
263            return;
264        }
265
266        let item_count = latest.peek().item_count;
267        count_at_request.set(item_count);
268        pending.set(true);
269
270        // Release the guard even when the app ignores the request and never re-renders.
271        spawn(async move {
272            sleep(Duration::ZERO).await;
273            pending.set(false);
274        });
275
276        if let Some(handler) = latest.peek().on_load_more {
277            handler.call(LoadMoreRequest { retry });
278        }
279    };
280
281    // Busy feed while loading (web and desktop).
282    let busy_target = target.clone();
283    use_effect(use_reactive(
284        (&busy_target, &(state == LoadMoreState::Loading)),
285        move |(target, busy)| {
286            if let Some(target) = target {
287                set_busy_by_id(target, busy);
288            }
289        },
290    ));
291
292    // Announcements and focus after each state change.
293    use_effect(use_reactive(
294        (&state, &item_count),
295        move |(state, item_count)| {
296            let before = *previous.peek();
297            pending.set(false);
298
299            if before == Some(state) {
300                return;
301            }
302
303            previous.set(Some(state));
304            let props = latest.peek().clone();
305            let mut focus_moved = false;
306
307            if before == Some(LoadMoreState::Loading) {
308                let at_request = count_at_request.write().take();
309                let added = at_request
310                    .zip(item_count)
311                    .map(|(before, now)| now.saturating_sub(before));
312
313                if let Some(text) = load_more_announcement(
314                    state,
315                    added,
316                    &props.added_label,
317                    &props.loaded_label,
318                    &props.done_label,
319                    &props.error_message,
320                    &props.locale,
321                ) {
322                    announcer.announce(text, props.delay);
323                }
324
325                if state != LoadMoreState::Error
326                    && props.focus_new_items
327                    && added.unwrap_or(0) > 0
328                    && let (Some(target), Some(index)) = (props.target, at_request)
329                {
330                    focus_moved = true;
331                    let index = usize::try_from(index).unwrap_or(usize::MAX);
332
333                    spawn(async move {
334                        focus_element_by_id(target, Some(index)).await;
335                    });
336                }
337
338                if state == LoadMoreState::Idle
339                    && let Some(observer) = *watcher.peek()
340                {
341                    observer.send("refresh");
342                }
343            }
344
345            // The button hides once the feed is done; keep focus on the message instead of the page.
346            if !focus_moved
347                && state == LoadMoreState::Done
348                && before.is_some()
349                && *button_focused.peek()
350            {
351                message_focusable.set(true);
352                focus_element(message_node.peek().clone());
353            }
354        },
355    ));
356
357    // Infinite mode: the sentinel requests in the idle state only, so errors wait for a retry.
358    let margin = props
359        .root_margin
360        .clone()
361        .unwrap_or_else(|| "0px 0px 200px 0px".to_string());
362    let observed = props.auto.then(|| sentinel_id.clone());
363    use_effect(use_reactive(
364        (&observed, &margin),
365        move |(observed, margin)| {
366            if let Some(previous) = watcher.write().take() {
367                previous.stop();
368            }
369
370            if let Some(id) = observed {
371                let next = watch_visible(id, margin, move || {
372                    if latest.peek().state == LoadMoreState::Idle {
373                        request(false);
374                    }
375                });
376                watcher.set(Some(next));
377            }
378        },
379    ));
380    use_drop(move || {
381        if let Some(previous) = watcher.write().take() {
382            previous.stop();
383        }
384    });
385
386    let class = compose([Some("ui-load-more"), props.class.as_deref()]);
387    let loading = state == LoadMoreState::Loading;
388    let control_class = "ui-button ui-button--outline ui-button--default-size ui-load-more__button";
389    let mut on_activate = move |event: MouseEvent, link: bool| {
390        // The href is a no-script fallback; once running, the page stays and the app appends items.
391        if link {
392            event.prevent_default();
393        }
394
395        let current = latest.peek().state;
396
397        if current != LoadMoreState::Loading {
398            request(current == LoadMoreState::Error);
399        }
400    };
401    let content = rsx! {
402        span { aria_hidden: "true", class: "ui-spinner", "data-slot": "load-more-spinner", hidden: !loading }
403        span { class: "ui-button__content", "data-slot": "load-more-label", "{button_text}" }
404    };
405
406    rsx! {
407        div {
408            aria_busy: loading.then_some("true"),
409            class,
410            "data-auto": props.auto.then_some(""),
411            "data-focus-new-items": props.focus_new_items.then_some(""),
412            "data-slot": "load-more",
413            "data-state": state.as_str(),
414            "data-target": props.target.clone(),
415            "data-ui-load-more": "",
416            "data-ui-owner": "dioxus",
417            ..props.attributes,
418            span {
419                aria_hidden: "true",
420                class: "ui-load-more__sentinel",
421                "data-slot": "load-more-sentinel",
422                id: props.auto.then_some(sentinel_id),
423            }
424            if let Some(href) = href {
425                a {
426                    aria_disabled: loading.then_some("true"),
427                    class: control_class,
428                    "data-slot": "load-more-button",
429                    hidden: state == LoadMoreState::Done,
430                    href,
431                    onclick: move |event| on_activate(event, true),
432                    onfocus: move |_| button_focused.set(true),
433                    onblur: move |_| button_focused.set(false),
434                    {content}
435                }
436            } else {
437                button {
438                    r#type: "button",
439                    aria_disabled: loading.then_some("true"),
440                    class: control_class,
441                    "data-slot": "load-more-button",
442                    hidden: state == LoadMoreState::Done,
443                    onclick: move |event| on_activate(event, false),
444                    onfocus: move |_| button_focused.set(true),
445                    onblur: move |_| button_focused.set(false),
446                    {content}
447                }
448            }
449            p {
450                class: "ui-load-more__message",
451                "data-slot": "load-more-message",
452                "data-state": state.as_str(),
453                hidden: message.is_empty(),
454                tabindex: message_focusable().then_some("-1"),
455                onmounted: move |event| message_node.set(Some(event.data())),
456                "{message}"
457            }
458            span {
459                aria_atomic: "true",
460                aria_live: "polite",
461                class: "ui-load-more__status",
462                "data-slot": "load-more-status",
463                role: "status",
464                "{announcer.text}"
465            }
466        }
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::{LoadMoreState, SelectionBarCountLabel, load_more_announcement};
473
474    #[test]
475    fn state_precedence_matches_lumen_core() {
476        assert_eq!(
477            LoadMoreState::resolve(true, true, false),
478            LoadMoreState::Loading
479        );
480        assert_eq!(
481            LoadMoreState::resolve(false, true, false),
482            LoadMoreState::Error
483        );
484        assert_eq!(
485            LoadMoreState::resolve(false, false, false),
486            LoadMoreState::Done
487        );
488        assert_eq!(
489            LoadMoreState::resolve(false, false, true),
490            LoadMoreState::Idle
491        );
492    }
493
494    #[test]
495    fn announcements_count_added_items() {
496        let label = SelectionBarCountLabel::plural("{count} item added", "{count} items added");
497        let announce = |state, added| {
498            load_more_announcement(
499                state,
500                added,
501                &label,
502                "More items loaded",
503                "No more items",
504                "Failed",
505                "en",
506            )
507        };
508        assert_eq!(
509            announce(LoadMoreState::Idle, Some(3)).as_deref(),
510            Some("3 items added")
511        );
512        assert_eq!(
513            announce(LoadMoreState::Idle, Some(1)).as_deref(),
514            Some("1 item added")
515        );
516        assert_eq!(announce(LoadMoreState::Idle, Some(0)), None);
517        assert_eq!(
518            announce(LoadMoreState::Idle, None).as_deref(),
519            Some("More items loaded")
520        );
521        assert_eq!(
522            announce(LoadMoreState::Done, Some(2)).as_deref(),
523            Some("2 items added No more items")
524        );
525        assert_eq!(
526            announce(LoadMoreState::Done, Some(0)).as_deref(),
527            Some("No more items")
528        );
529        assert_eq!(
530            announce(LoadMoreState::Error, Some(2)).as_deref(),
531            Some("Failed")
532        );
533        assert_eq!(announce(LoadMoreState::Loading, Some(2)), None);
534    }
535}