lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Keyboard focus movement for groups of items (menubars, toggle groups, navigation links, command
//! lists), replacing the DOM queries of Lumen's web runtime with a render-order registry.

use std::collections::BTreeMap;
use std::rc::Rc;

use dioxus::prelude::*;

use crate::overlay::focus_element;

/// One registered item.
#[derive(Clone, Copy)]
struct RovingEntry {
    key: usize,
    disabled: bool,
    hidden: bool,
}

/// Which arrow keys move focus.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RovingAxis {
    /// Left/Right and Up/Down both move, like Lumen's roving web runtime.
    Both,
    /// Only Up and Down move, for vertical lists.
    Vertical,
}

/// A movement requested by a key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RovingMove {
    Next,
    Previous,
    First,
    Last,
}

/// Maps a key to a movement. Left/Right swap in right-to-left layouts.
pub(crate) fn roving_move(key: &Key, axis: RovingAxis, rtl: bool) -> Option<RovingMove> {
    let (back, forward) = if rtl {
        (Key::ArrowRight, Key::ArrowLeft)
    } else {
        (Key::ArrowLeft, Key::ArrowRight)
    };

    match key {
        Key::ArrowDown => Some(RovingMove::Next),
        Key::ArrowUp => Some(RovingMove::Previous),
        Key::Home => Some(RovingMove::First),
        Key::End => Some(RovingMove::Last),
        key if axis == RovingAxis::Both && *key == forward => Some(RovingMove::Next),
        key if axis == RovingAxis::Both && *key == back => Some(RovingMove::Previous),
        _ => None,
    }
}

/// The index to focus next among `navigable` flags, starting at `current`. Skips items that are
/// not navigable and wraps, like `getNextNavigableRovingItem` in the web runtime.
pub(crate) fn next_navigable(
    navigable: &[bool],
    current: Option<usize>,
    movement: RovingMove,
) -> Option<usize> {
    let len = navigable.len();

    if len == 0 {
        return None;
    }

    let (start, step): (usize, isize) = match movement {
        RovingMove::First => (0, 1),
        RovingMove::Last => (len - 1, -1),
        RovingMove::Next => (current.map_or(0, |index| (index + 1) % len), 1),
        RovingMove::Previous => (current.map_or(len - 1, |index| (index + len - 1) % len), -1),
    };

    (0..len)
        .map(|offset| {
            let offset = offset % len;

            if step > 0 {
                (start + offset) % len
            } else {
                (start + len - offset) % len
            }
        })
        .find(|index| navigable[*index])
}

/// A registry of focusable items in render order. It is `Copy`.
#[derive(Clone, Copy)]
pub(crate) struct Roving {
    entries: Signal<Vec<RovingEntry>>,
    /// Mounted elements by item key, kept apart from `entries` because items register those in an
    /// effect while dioxus-web dispatches `onmounted` as it flushes edits, before effects run. Not
    /// reactive: nothing renders from it.
    mounted: CopyValue<BTreeMap<usize, Rc<MountedData>>>,
    next_key: CopyValue<usize>,
    active: Signal<Option<usize>>,
    /// True once the group has mounted on a live renderer. Server rendering keeps the markup of
    /// the no-script contract, so roving `tabindex` values appear only after this.
    enhanced: Signal<bool>,
}

impl Roving {
    /// Creates a registry owned by the calling component.
    pub(crate) fn use_new() -> Self {
        let roving = use_hook(|| Self {
            entries: Signal::new(Vec::new()),
            mounted: CopyValue::new(BTreeMap::new()),
            next_key: CopyValue::new(0),
            active: Signal::new(None),
            enhanced: Signal::new(false),
        });
        let mut enhanced = roving.enhanced;

        use_effect(move || enhanced.set(true));

        roving
    }

    /// Registers the calling item and returns its key. Call once per item component.
    pub(crate) fn use_item(self, disabled: bool, hidden: bool) -> usize {
        let mut next_key = self.next_key;
        let key = use_hook(move || {
            let key = *next_key.peek();
            next_key.set(key + 1);
            key
        });
        let (mut entries, mut mounted) = (self.entries, self.mounted);

        use_effect(use_reactive(
            (&disabled, &hidden),
            move |(disabled, hidden)| {
                let mut list = entries.write();

                if let Some(entry) = list.iter_mut().find(|entry| entry.key == key) {
                    entry.disabled = disabled;
                    entry.hidden = hidden;
                } else {
                    list.push(RovingEntry {
                        key,
                        disabled,
                        hidden,
                    });
                    list.sort_by_key(|entry| entry.key);
                }
            },
        ));

        use_drop(move || {
            if let Ok(mut list) = entries.try_write() {
                list.retain(|entry| entry.key != key);
            }

            if let Ok(mut elements) = mounted.try_write() {
                elements.remove(&key);
            }
        });

        key
    }

    /// Stores the mounted element of an item so keys can focus it. Works whether or not the item's
    /// registration effect has run yet.
    pub(crate) fn mount(self, key: usize, element: Rc<MountedData>) {
        let mut mounted = self.mounted;
        mounted.write().insert(key, element);
    }

    /// Whether the group has mounted on a live renderer.
    pub(crate) fn enhanced(self) -> bool {
        *self.enhanced.read()
    }

    /// The key that owns `tabindex="0"`: the last focused item, or the first navigable one.
    pub(crate) fn tab_stop(self) -> Option<usize> {
        let entries = self.entries.read();
        let active = *self.active.read();

        active
            .filter(|key| {
                entries
                    .iter()
                    .any(|entry| entry.key == *key && !entry.disabled && !entry.hidden)
            })
            .or_else(|| {
                entries
                    .iter()
                    .find(|entry| !entry.disabled && !entry.hidden)
                    .map(|entry| entry.key)
            })
    }

    /// `tabindex` for an item once the group is enhanced: `0` for the tab stop, `-1` otherwise.
    pub(crate) fn tabindex(self, key: usize) -> Option<&'static str> {
        if !self.enhanced() {
            return None;
        }

        Some(if self.tab_stop() == Some(key) {
            "0"
        } else {
            "-1"
        })
    }

    /// Records that an item received focus, so it keeps the tab stop.
    pub(crate) fn focused(self, key: usize) {
        let mut active = self.active;

        if *active.peek() != Some(key) {
            active.set(Some(key));
        }
    }

    /// Moves focus from `from` (or from nothing) and returns the newly focused key.
    pub(crate) fn move_focus(self, from: Option<usize>, movement: RovingMove) -> Option<usize> {
        let entries = self.entries.peek().clone();
        let navigable: Vec<bool> = entries
            .iter()
            .map(|entry| !entry.disabled && !entry.hidden)
            .collect();
        let current = from.and_then(|key| entries.iter().position(|entry| entry.key == key));
        let index = next_navigable(&navigable, current, movement)?;
        let target = entries.get(index)?;

        let element = self.mounted.peek().get(&target.key).cloned();

        self.focused(target.key);
        focus_element(element);
        Some(target.key)
    }

    /// Focuses the first or last navigable item.
    pub(crate) fn focus_edge(self, last: bool) -> Option<usize> {
        self.move_focus(
            None,
            if last {
                RovingMove::Last
            } else {
                RovingMove::First
            },
        )
    }

    /// Keys of the visible items, in render order.
    pub(crate) fn visible_count(self) -> usize {
        self.entries
            .read()
            .iter()
            .filter(|entry| !entry.hidden)
            .count()
    }
}

#[cfg(test)]
mod tests {
    use super::{Key, RovingAxis, RovingMove, next_navigable, roving_move};

    #[test]
    fn keys_map_to_movements() {
        assert_eq!(
            roving_move(&Key::ArrowRight, RovingAxis::Both, false),
            Some(RovingMove::Next)
        );
        assert_eq!(
            roving_move(&Key::ArrowRight, RovingAxis::Both, true),
            Some(RovingMove::Previous)
        );
        assert_eq!(
            roving_move(&Key::ArrowRight, RovingAxis::Vertical, false),
            None
        );
        assert_eq!(
            roving_move(&Key::End, RovingAxis::Vertical, false),
            Some(RovingMove::Last)
        );
        assert_eq!(roving_move(&Key::Enter, RovingAxis::Both, false), None);
    }

    #[test]
    fn movement_skips_disabled_items_and_wraps() {
        let items = [true, false, true, true];
        assert_eq!(next_navigable(&items, Some(0), RovingMove::Next), Some(2));
        assert_eq!(next_navigable(&items, Some(3), RovingMove::Next), Some(0));
        assert_eq!(
            next_navigable(&items, Some(2), RovingMove::Previous),
            Some(0)
        );
        assert_eq!(
            next_navigable(&items, Some(0), RovingMove::Previous),
            Some(3)
        );
        assert_eq!(next_navigable(&items, None, RovingMove::Next), Some(0));
        assert_eq!(next_navigable(&items, None, RovingMove::Previous), Some(3));
        assert_eq!(next_navigable(&items, None, RovingMove::First), Some(0));
        assert_eq!(
            next_navigable(&[false, true, false], None, RovingMove::Last),
            Some(1)
        );
        assert_eq!(
            next_navigable(&[false, false], Some(0), RovingMove::Next),
            None
        );
        assert_eq!(next_navigable(&[], None, RovingMove::First), None);
    }
}