material_dioxus/list/
list_index.rs

1use std::collections::HashSet;
2use wasm_bindgen::{JsCast, JsValue};
3
4/// The `MWCListIndex` type
5///
6/// [MWC Documentation](https://github.com/material-components/material-components-web-components/tree/v0.27.0/packages/list#mwc-list-1)
7#[derive(Debug, Clone)]
8pub enum ListIndex {
9    /// Provided when `multi` prop is set to `false` (default) on the component
10    ///
11    /// `None` denotes value of `-1`
12    Single(Option<usize>),
13    /// Provided when `multi` prop is set to `true` on the component
14    Multi(HashSet<usize>),
15}
16
17impl ListIndex {
18    pub fn unwrap_single(self) -> Option<usize> {
19        match self {
20            ListIndex::Single(val) => val,
21            ListIndex::Multi(_) => panic!("called `unwrap_single` on {self:?}"),
22        }
23    }
24
25    pub fn unwrap_multi(self) -> HashSet<usize> {
26        match self {
27            ListIndex::Multi(val) => val,
28            ListIndex::Single(_) => panic!("called `unwrap_multi` on {self:?}"),
29        }
30    }
31}
32
33impl From<JsValue> for ListIndex {
34    fn from(val: JsValue) -> Self {
35        if let Ok(set) = val.clone().dyn_into::<js_sys::Set>() {
36            let indices = set
37                .values()
38                .into_iter()
39                .filter_map(|item| item.ok())
40                .filter_map(|value| value.as_f64())
41                .map(|num| num as usize)
42                .collect();
43            ListIndex::Multi(indices)
44        } else if let Some(value) = val.as_f64() {
45            ListIndex::Single(if value != -1.0 {
46                Some(value as usize)
47            } else {
48                None
49            })
50        } else {
51            panic!("This should never happen")
52        }
53    }
54}