Skip to main content

perspective_viewer/components/form/
select_enum_field.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::fmt::{Debug, Display};
14
15use itertools::Itertools;
16use strum::IntoEnumIterator;
17use yew::{Callback, Properties, function_component, html};
18
19use crate::components::containers::select::{Select, SelectItem};
20use crate::components::form::optional_field::OptionalField;
21
22#[derive(Properties, Debug, PartialEq, Clone)]
23pub struct SelectEnumFieldProps<T>
24where
25    T: IntoEnumIterator + Display + Default + PartialEq + Clone + 'static,
26{
27    pub current_value: Option<T>,
28    pub label: String,
29    pub on_change: Callback<Option<T>>,
30
31    #[prop_or_default]
32    pub default_value: Option<T>,
33
34    #[prop_or_default]
35    pub disabled: bool,
36}
37
38#[function_component(SelectEnumField)]
39pub fn select_enum_field<T>(props: &SelectEnumFieldProps<T>) -> yew::Html
40where
41    T: IntoEnumIterator + Debug + Display + Default + PartialEq + Clone + 'static,
42{
43    let values = yew::use_memo((), |_| T::iter().map(SelectItem::Option).collect_vec());
44    let selected = props.current_value.clone().unwrap_or_default();
45    let checked = selected != props.default_value.clone().unwrap_or_default();
46    let reset_value = props.default_value.clone();
47    html! {
48        <div class="row">
49            <OptionalField
50                label={props.label.clone()}
51                on_check={props.on_change.reform(move |_| reset_value.clone())}
52                {checked}
53                disabled={props.disabled}
54            >
55                <Select<T> {values} {selected} on_select={props.on_change.reform(Option::Some)} />
56            </OptionalField>
57        </div>
58    }
59}