material_yew/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)]
8pub enum ListIndex {
9    /// Provided when `multi` prop is set to `false` (default) on the component
10    ///
11    /// `None` denotes value os `-1`
12    Single(Option<usize>),
13    /// Provided when `multi` prop is set to `true` on the component
14    Multi(HashSet<usize>),
15}
16
17impl From<JsValue> for ListIndex {
18    fn from(val: JsValue) -> Self {
19        if let Ok(set) = val.clone().dyn_into::<js_sys::Set>() {
20            let indices = set
21                .values()
22                .into_iter()
23                .filter_map(|item| item.ok())
24                .filter_map(|value| value.as_f64())
25                .map(|num| num as usize)
26                .collect();
27            ListIndex::Multi(indices)
28        } else if let Some(value) = val.as_f64() {
29            #[allow(clippy::float_cmp)]
30            ListIndex::Single(if value != -1.0 {
31                Some(value as usize)
32            } else {
33                None
34            })
35        } else {
36            panic!("This should never happen")
37        }
38    }
39}