Skip to main content

perspective_viewer/components/form/
select_value_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};
14use std::rc::Rc;
15
16use itertools::Itertools;
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 SelectValueFieldProps<T>
24where
25    T: Display + PartialEq + Clone + 'static,
26{
27    pub current_value: Option<T>,
28    pub default_value: T,
29    pub label: String,
30    pub on_change: Callback<Option<T>>,
31    pub values: Rc<Vec<T>>,
32
33    #[prop_or_default]
34    pub disabled: bool,
35}
36
37#[function_component(SelectValueField)]
38pub fn select_value_field<T>(props: &SelectValueFieldProps<T>) -> yew::Html
39where
40    T: Display + PartialEq + Clone + 'static,
41{
42    let values = yew::use_memo(props.values.clone(), |values| {
43        values.iter().cloned().map(SelectItem::Option).collect_vec()
44    });
45
46    let selected = props
47        .current_value
48        .clone()
49        .unwrap_or_else(|| props.default_value.clone());
50
51    let checked = selected != props.default_value;
52    html! {
53        <div class="row">
54            <OptionalField
55                label={props.label.clone()}
56                on_check={props.on_change.reform(|_| None)}
57                {checked}
58                disabled={props.disabled}
59            >
60                <Select<T> {values} {selected} on_select={props.on_change.reform(Option::Some)} />
61            </OptionalField>
62        </div>
63    }
64}