feat: Add support for multiple options in Select (#166)

* feat!: Add support for multiple options in Select

* feat: Sync Select menu when value is updated

* feat: Decrease line height of multi select items

* fix: Invalid callback on multiselect tag close

* feat: Sync Select menu only for multiple values

* feat: separate `MultiSelect` from `Select` component

* fix: SelectLabel slot implementation

* feat: rename `MultiSelect` to `SelectMulti`

* feat: rename and move `MultiSelect`

* feat: add arrow to select component

* feat: lower opacity of select dropdown arrow icon

* fix: inconsistent select font size

* fix: select menu font size

* feat: add clear button to multi select

* fix: Multi select icon on click attribute

* feat: use inline-block for select component

* feat: detect select min width based on options

* feat: add `allow_clear` prop to `MultiSelect`

* feat: remove select min width detection

* feat: use `Children` for `SelectLabel`

* feat: rename `allow_clear` to `clearable`

* fix: follower min width

* feat: remove inline-block from `Select`
This commit is contained in:
Ari Seyhun 2024-04-23 09:41:01 +08:00 committed by GitHub
parent f75b38f97d
commit 324bc57e42
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 517 additions and 180 deletions

View file

@ -4,18 +4,9 @@ use thaw::*;
#[component]
pub fn SwitchVersion() -> impl IntoView {
let options = vec![
SelectOption {
label: "main".into(),
value: "https://thawui.vercel.app".into(),
},
SelectOption {
label: "0.2.6".into(),
value: "https://thaw-mzh1656cm-thaw.vercel.app".into(),
},
SelectOption {
label: "0.2.5".into(),
value: "https://thaw-8og1kv8zs-thaw.vercel.app".into(),
},
SelectOption::new("main", "https://thawui.vercel.app".into()),
SelectOption::new("0.2.6", "https://thaw-mzh1656cm-thaw.vercel.app".into()),
SelectOption::new("0.2.5", "https://thaw-8og1kv8zs-thaw.vercel.app".into()),
];
cfg_if::cfg_if! {

View file

@ -4,14 +4,8 @@
let value = create_rw_signal(None::<String>);
let options = vec![
SelectOption {
label: String::from("RwSignal"),
value: String::from("rw_signal"),
},
SelectOption {
label: String::from("Memo"),
value: String::from("memo"),
},
SelectOption::new("RwSignal", String::from("rw_signal")),
SelectOption::new("Memo", String::from("memo")),
];
view! {
@ -19,6 +13,31 @@ view! {
}
```
# Multiple Select
```rust demo
let value = create_rw_signal(vec![
"rust".to_string(),
"javascript".to_string(),
"zig".to_string(),
"python".to_string(),
"cpp".to_string(),
]);
let options = vec![
MultiSelectOption::new("Rust", String::from("rust")).with_variant(TagVariant::Success),
MultiSelectOption::new("JavaScript", String::from("javascript")),
MultiSelectOption::new("Python", String::from("python")).with_variant(TagVariant::Warning),
MultiSelectOption::new("C++", String::from("cpp")).with_variant(TagVariant::Error),
MultiSelectOption::new("Lua", String::from("lua")),
MultiSelectOption::new("Zig", String::from("zig")),
];
view! {
<MultiSelect value options />
}
```
### Select Props
| Name | Type | Default | Description |
@ -26,3 +45,18 @@ view! {
| class | `OptionalProp<MaybeSignal<String>>` | `Default::default()` | Addtional classes for the select element. |
| value | `Model<Option<T>>` | `None` | Checked value. |
| options | `MaybeSignal<Vec<SelectOption<T>>>` | `vec![]` | Options that can be selected. |
### Multiple Select Props
| Name | Type | Default | Description |
| --------- | ----------------------------------- | -------------------- | ----------------------------------------- |
| class | `OptionalProp<MaybeSignal<String>>` | `Default::default()` | Addtional classes for the select element. |
| value | `Model<Vec<T>>` | `vec![]` | Checked values. |
| options | `MaybeSignal<Vec<SelectOption<T>>>` | `vec![]` | Options that can be selected. |
| clearable | `MaybeSignal<bool>` | `false` | Allow the options to be cleared. |
### Select Slots
| Name | Default | Description |
| ----------- | ------- | ------------- |
| SelectLabel | `None` | Select label. |

View file

@ -8,11 +8,11 @@ use syn::ItemFn;
macro_rules! file_path {
($($key:expr => $value:expr),*) => {
{
let mut pairs = Vec::new();
vec![
$(
pairs.push(($key, include_str!($value)));
($key, include_str!($value)),
)*
pairs
]
}
}
}
@ -111,7 +111,7 @@ pub fn include_md(_token_stream: proc_macro::TokenStream) -> proc_macro::TokenSt
})
.map(|demo| {
syn::parse_str::<ItemFn>(&demo)
.expect(&format!("Cannot be resolved as a function: \n {demo}"))
.unwrap_or_else(|_| panic!("Cannot be resolved as a function: \n {demo}"))
})
.collect();

View file

@ -20,6 +20,9 @@ pub fn Icon(
/// HTML style attribute.
#[prop(into, optional)]
style: Option<MaybeSignal<String>>,
/// Callback when clicking on the icon.
#[prop(optional, into)]
on_click: Option<Callback<ev::MouseEvent>>,
) -> impl IntoView {
let icon_style = RwSignal::new(None);
let icon_x = RwSignal::new(None);
@ -33,6 +36,11 @@ pub fn Icon(
let icon_stroke = RwSignal::new(None);
let icon_fill = RwSignal::new(None);
let icon_data = RwSignal::new(None);
let on_click = move |ev| {
if let Some(click) = on_click.as_ref() {
click.call(ev);
}
};
create_isomorphic_effect(move |_| {
let icon = icon.get();
@ -84,6 +92,7 @@ pub fn Icon(
stroke=move || take(icon_stroke)
fill=move || take(icon_fill)
inner_html=move || take(icon_data)
on:click=on_click
></svg>
}
}

View file

@ -1,177 +1,95 @@
mod multi;
mod raw;
mod theme;
pub use multi::*;
pub use theme::SelectTheme;
use crate::{theme::use_theme, Theme};
use leptos::*;
use std::hash::Hash;
use thaw_components::{Binder, CSSTransition, Follower, FollowerPlacement, FollowerWidth};
use thaw_utils::{class_list, mount_style, Model, OptionalProp};
use std::{hash::Hash, rc::Rc};
use thaw_utils::{Model, OptionalProp};
#[derive(Clone, PartialEq, Eq, Hash)]
use crate::{
select::raw::{RawSelect, SelectIcon},
Icon,
};
#[slot]
pub struct SelectLabel {
children: Children,
}
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct SelectOption<T> {
pub label: String,
pub value: T,
}
impl<T> SelectOption<T> {
pub fn new(label: impl Into<String>, value: T) -> SelectOption<T> {
SelectOption {
label: label.into(),
value,
}
}
}
#[component]
pub fn Select<T>(
#[prop(optional, into)] value: Model<Option<T>>,
#[prop(optional, into)] options: MaybeSignal<Vec<SelectOption<T>>>,
#[prop(optional, into)] class: OptionalProp<MaybeSignal<String>>,
#[prop(optional)] select_label: Option<SelectLabel>,
) -> impl IntoView
where
T: Eq + Hash + Clone + 'static,
{
mount_style("select", include_str!("./select.css"));
let theme = use_theme(Theme::light);
let css_vars = create_memo(move |_| {
let mut css_vars = String::new();
theme.with(|theme| {
let border_color_hover = theme.common.color_primary.clone();
css_vars.push_str(&format!("--thaw-border-color-hover: {border_color_hover};"));
css_vars.push_str(&format!(
"--thaw-background-color: {};",
theme.select.background_color
));
css_vars.push_str(&format!("--thaw-font-color: {};", theme.select.font_color));
css_vars.push_str(&format!(
"--thaw-border-color: {};",
theme.select.border_color
));
let is_menu_visible = create_rw_signal(false);
let show_menu = move |_| is_menu_visible.set(true);
let hide_menu = move |_| is_menu_visible.set(false);
let is_selected = move |v: &T| with!(|value| value.as_ref() == Some(v));
let on_select: Callback<(ev::MouseEvent, SelectOption<T>)> =
Callback::new(move |(_, option): (ev::MouseEvent, SelectOption<T>)| {
let item_value = option.value;
value.set(Some(item_value));
hide_menu(());
});
css_vars
});
let menu_css_vars = create_memo(move |_| {
let mut css_vars = String::new();
theme.with(|theme| {
css_vars.push_str(&format!(
"--thaw-background-color: {};",
theme.select.menu_background_color
));
css_vars.push_str(&format!(
"--thaw-background-color-hover: {};",
theme.select.menu_background_color_hover
));
css_vars.push_str(&format!("--thaw-font-color: {};", theme.select.font_color));
css_vars.push_str(&format!(
"--thaw-font-color-selected: {};",
theme.common.color_primary
));
});
css_vars
});
let is_show_menu = create_rw_signal(false);
let trigger_ref = create_node_ref::<html::Div>();
let menu_ref = create_node_ref::<html::Div>();
let show_menu = move |_| {
is_show_menu.set(true);
};
#[cfg(any(feature = "csr", feature = "hydrate"))]
{
use leptos::wasm_bindgen::__rt::IntoJsResult;
let timer = window_event_listener(ev::click, move |ev| {
let el = ev.target();
let mut el: Option<web_sys::Element> =
el.into_js_result().map_or(None, |el| Some(el.into()));
let body = document().body().unwrap();
while let Some(current_el) = el {
if current_el == *body {
break;
};
if current_el == ***menu_ref.get().unwrap()
|| current_el == ***trigger_ref.get().unwrap()
{
return;
}
el = current_el.parent_element();
}
is_show_menu.set(false);
});
on_cleanup(move || timer.remove());
}
let temp_options = options.clone();
let select_option_label = create_memo(move |_| match value.get() {
Some(value) => temp_options
.get()
let select_label = select_label.unwrap_or_else(|| {
let options = options.clone();
let value_label = Signal::derive(move || {
with!(|value, options| {
match value {
Some(value) => options
.iter()
.find(move |v| v.value == value)
.find(|opt| &opt.value == value)
.map_or(String::new(), |v| v.label.clone()),
None => String::new(),
}
})
});
view! {
<Binder target_ref=trigger_ref>
<div
class=class_list!["thaw-select", class.map(| c | move || c.get())]
ref=trigger_ref
on:click=show_menu
style=move || css_vars.get()
>
{move || select_option_label.get()}
</div>
<Follower
slot
show=is_show_menu
placement=FollowerPlacement::BottomStart
width=FollowerWidth::Target
>
<CSSTransition
node_ref=menu_ref
name="fade-in-scale-up-transition"
appear=is_show_menu.get_untracked()
show=is_show_menu
let:display
>
<div
class="thaw-select-menu"
style=move || {
display
.get()
.map(|d| d.to_string())
.unwrap_or_else(|| menu_css_vars.get())
SelectLabel {
children: Box::new(move || Fragment::new(vec![value_label.into_view()])),
}
ref=menu_ref
>
<For
each=move || options.get()
key=move |item| item.value.clone()
children=move |item| {
let item = store_value(item);
let onclick = move |_| {
let SelectOption { value: item_value, label: _ } = item
.get_value();
value.set(Some(item_value));
is_show_menu.set(false);
});
let select_icon = SelectIcon {
children: Rc::new(move || {
Fragment::new(vec![
view! { <Icon class="thaw-select-dropdown-icon" icon=icondata_ai::AiDownOutlined/> }.into_view()
])
}),
};
view! {
<div
class="thaw-select-menu__item"
class=(
"thaw-select-menu__item-selected",
move || value.get() == Some(item.get_value().value),
)
on:click=onclick
>
{item.get_value().label}
</div>
}
}
<RawSelect
options
class
select_label
select_icon
is_menu_visible
on_select=on_select
show_menu
hide_menu
is_selected=is_selected
/>
</div>
</CSSTransition>
</Follower>
</Binder>
}
}

199
thaw/src/select/multi.rs Normal file
View file

@ -0,0 +1,199 @@
use leptos::*;
use std::{hash::Hash, rc::Rc, time::Duration};
use thaw_utils::{Model, OptionalProp};
use crate::{
select::raw::{RawSelect, SelectIcon},
Icon, SelectLabel, SelectOption, Tag, TagVariant,
};
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct MultiSelectOption<T> {
pub label: String,
pub value: T,
pub variant: TagVariant,
}
impl<T> MultiSelectOption<T> {
pub fn new(label: impl Into<String>, value: T) -> MultiSelectOption<T> {
MultiSelectOption {
label: label.into(),
value,
variant: TagVariant::Default,
}
}
pub fn with_variant(mut self, variant: TagVariant) -> MultiSelectOption<T> {
self.variant = variant;
self
}
}
impl<T> From<MultiSelectOption<T>> for SelectOption<T> {
fn from(opt: MultiSelectOption<T>) -> Self {
SelectOption {
label: opt.label,
value: opt.value,
}
}
}
#[component]
pub fn MultiSelect<T>(
#[prop(optional, into)] value: Model<Vec<T>>,
#[prop(optional, into)] options: MaybeSignal<Vec<MultiSelectOption<T>>>,
#[prop(optional, into)] class: OptionalProp<MaybeSignal<String>>,
#[prop(optional, into)] clearable: MaybeSignal<bool>,
#[prop(optional)] select_label: Option<SelectLabel>,
) -> impl IntoView
where
T: Eq + Hash + Clone + 'static,
{
let select_options: Signal<Vec<_>> = Signal::derive({
let options = options.clone();
move || options.get().into_iter().map(SelectOption::from).collect()
});
let class: OptionalProp<_> = match class.into_option() {
Some(MaybeSignal::Dynamic(class)) => {
Some(MaybeSignal::Dynamic(Signal::derive(move || {
with!(|class| format!("thaw-select--multiple {class}"))
})))
.into()
}
Some(MaybeSignal::Static(class)) => Some(MaybeSignal::Static(format!(
"thaw-select--multiple {class}"
)))
.into(),
None => Some(MaybeSignal::Static("thaw-select--multiple".to_string())).into(),
};
let is_menu_visible = create_rw_signal(false);
let show_menu = move |_| is_menu_visible.set(true);
let hide_menu = move |_| is_menu_visible.set(false);
let is_selected = move |v: &T| with!(|value| value.contains(v));
let on_select: Callback<(ev::MouseEvent, SelectOption<T>)> =
Callback::new(move |(_, option): (ev::MouseEvent, SelectOption<T>)| {
let item_value = option.value;
update!(|value| {
let index = value
.iter()
.enumerate()
.find_map(|(i, v)| (v == &item_value).then_some(i));
match index {
Some(i) => {
value.remove(i);
}
None => {
value.push(item_value);
}
}
});
});
let select_label = select_label.unwrap_or_else(|| {
let options = options.clone();
let signal_value = value;
let value_label = Signal::derive(move || {
with!(|value, options| {
value
.iter()
.map(|value| {
let (label, variant) = options
.iter()
.find(move |v| &v.value == value)
.map_or((String::new(), TagVariant::Default), |v| {
(v.label.clone(), v.variant)
});
let value = value.clone();
let on_close = Callback::new(move |ev: ev::MouseEvent| {
ev.stop_propagation();
let value = value.clone();
// We remove the item on the next tick to ensure the menu on click handler works correctly
set_timeout(
move || {
update!(|signal_value| {
let index = signal_value
.iter()
.enumerate()
.find_map(|(i, v)| (v == &value).then_some(i));
if let Some(i) = index {
signal_value.remove(i);
}
});
},
Duration::ZERO,
)
});
view! {
<Tag
variant
closable=true
on_close
>
{label}
</Tag>
}
})
.collect_view()
})
});
SelectLabel {
children: Box::new(move || Fragment::new(vec![value_label.into_view()])),
}
});
let is_hovered = RwSignal::new(false);
let show_clear_icon = Signal::derive(move || {
clearable.get()
&& ((is_hovered.get() || is_menu_visible.get()) && with!(|value| !value.is_empty()))
});
let on_hover_enter = Callback::new(move |_| is_hovered.set(true));
let on_hover_exit = Callback::new(move |_| is_hovered.set(false));
let select_icon = SelectIcon {
children: Rc::new(move || {
Fragment::new(vec![view! {
{move || if show_clear_icon.get() {
view! {
<Icon
class="thaw-select-dropdown-icon thaw-select-dropdown-icon--clear"
icon=icondata_ai::AiCloseCircleFilled
on_click=Callback::new(move |_| {
set_timeout(
move || value.set(vec![]),
Duration::ZERO,
)
})
/>
}
} else {
view! {
<Icon class="thaw-select-dropdown-icon" icon=icondata_ai::AiDownOutlined/>
}
}}
}
.into_view()])
}),
};
// Trigger the following menu to resync when the value is updated
let _ = watch(
move || value.track(),
move |_, _, _| {
is_menu_visible.update(|_| {});
},
false,
);
view! {
<RawSelect
options=select_options
class
select_label
select_icon
is_menu_visible
on_select=on_select
show_menu
hide_menu
on_hover_enter
on_hover_exit
is_selected=is_selected
/>
}
}

158
thaw/src/select/raw.rs Normal file
View file

@ -0,0 +1,158 @@
use std::{hash::Hash, time::Duration};
use leptos::*;
use thaw_components::{Binder, CSSTransition, Follower, FollowerPlacement, FollowerWidth};
use thaw_utils::{class_list, mount_style, OptionalProp};
use crate::{theme::use_theme, SelectLabel, SelectOption, Theme};
#[slot]
pub(crate) struct SelectIcon {
children: ChildrenFn,
}
#[component]
pub(super) fn RawSelect<T, F>(
#[prop(optional, into)] options: MaybeSignal<Vec<SelectOption<T>>>,
#[prop(optional, into)] class: OptionalProp<MaybeSignal<String>>,
select_label: SelectLabel,
select_icon: SelectIcon,
#[prop(optional, into)] is_menu_visible: Signal<bool>,
#[prop(into)] on_select: Callback<(ev::MouseEvent, SelectOption<T>)>,
#[prop(into)] show_menu: Callback<()>,
#[prop(into)] hide_menu: Callback<()>,
#[prop(optional, into)] on_hover_enter: Option<Callback<()>>,
#[prop(optional, into)] on_hover_exit: Option<Callback<()>>,
is_selected: F,
) -> impl IntoView
where
T: Eq + Hash + Clone + 'static,
F: Fn(&T) -> bool + Copy + 'static,
{
mount_style("select", include_str!("./select.css"));
let trigger_ref = create_node_ref::<html::Div>();
let menu_ref = create_node_ref::<html::Div>();
#[cfg(any(feature = "csr", feature = "hydrate"))]
{
use leptos::wasm_bindgen::__rt::IntoJsResult;
let listener = window_event_listener(ev::click, move |ev| {
let el = ev.target();
let el: Option<web_sys::Node> = el.into_js_result().map_or(None, |el| Some(el.into()));
let is_descendent_of_select = trigger_ref.get().unwrap().contains(el.as_ref());
let is_descendent_of_menu = menu_ref.get().unwrap().contains(el.as_ref());
if (!is_descendent_of_select && !is_descendent_of_menu)
|| (is_menu_visible.get() && el.unwrap() == ****trigger_ref.get().unwrap())
{
hide_menu.call(());
}
});
on_cleanup(move || listener.remove());
}
let theme = use_theme(Theme::light);
let css_vars = create_memo(move |_| {
let mut css_vars = String::new();
theme.with(|theme| {
let border_color_hover = theme.common.color_primary.clone();
css_vars.push_str(&format!("--thaw-border-color-hover: {border_color_hover};"));
css_vars.push_str(&format!(
"--thaw-background-color: {};",
theme.select.background_color
));
css_vars.push_str(&format!("--thaw-font-color: {};", theme.select.font_color));
css_vars.push_str(&format!(
"--thaw-border-color: {};",
theme.select.border_color
));
});
css_vars
});
let menu_css_vars = create_memo(move |_| {
let mut css_vars = String::new();
theme.with(|theme| {
css_vars.push_str(&format!(
"--thaw-background-color: {};",
theme.select.menu_background_color
));
css_vars.push_str(&format!(
"--thaw-background-color-hover: {};",
theme.select.menu_background_color_hover
));
css_vars.push_str(&format!("--thaw-font-color: {};", theme.select.font_color));
css_vars.push_str(&format!(
"--thaw-font-color-selected: {};",
theme.common.color_primary
));
});
css_vars
});
view! {
<Binder target_ref=trigger_ref>
<div
class=class_list!["thaw-select", class.map(|c| move || c.get())]
ref=trigger_ref
on:click=move |_| {
if !is_menu_visible.get_untracked() {
set_timeout(move || show_menu.call(()), Duration::ZERO);
}
}
on:mouseenter=move |_| if let Some(cb) = on_hover_enter { cb.call(()) }
on:mouseleave=move |_| if let Some(cb) = on_hover_exit { cb.call(()) }
style=move || css_vars.get()
>
{(select_label.children)()}
{select_icon.children}
</div>
<Follower
slot
show=is_menu_visible
placement=FollowerPlacement::BottomStart
width=FollowerWidth::MinTarget
>
<CSSTransition
node_ref=menu_ref
name="fade-in-scale-up-transition"
appear=is_menu_visible.get_untracked()
show=is_menu_visible
let:display
>
<div
class="thaw-select-menu"
style=move || {
display
.get()
.map(|d| d.to_string())
.unwrap_or_else(|| menu_css_vars.get())
}
ref=menu_ref
>
<For
each=move || options.get()
key=move |item| item.value.clone()
children=move |item| {
let item = store_value(item);
view! {
<div
class="thaw-select-menu__item"
class=(
"thaw-select-menu__item-selected",
move || item.with_value(|item_value| is_selected(&item_value.value)),
)
on:click=move |ev| on_select.call((ev, item.get_value()))
>
{item.get_value().label}
</div>
}
}
/>
</div>
</CSSTransition>
</Follower>
</Binder>
}
}

View file

@ -1,9 +1,10 @@
.thaw-select {
position: relative;
padding: 0 10px;
height: 30px;
line-height: 30px;
padding: 0 30px 0 10px;
min-height: 30px;
line-height: 28px;
background-color: var(--thaw-background-color);
font-size: 14px;
color: var(--thaw-font-color);
border: 1px solid var(--thaw-border-color);
border-radius: 3px;
@ -12,11 +13,35 @@
box-sizing: border-box;
}
.thaw-select.thaw-select--multiple {
padding: 0 30px 0 3px;
}
.thaw-select-dropdown-icon {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
opacity: 40%;
pointer-events: none;
}
.thaw-select-dropdown-icon--clear {
pointer-events: auto;
}
.thaw-select.thaw-select--multiple .thaw-tag {
height: 20px;
margin-right: 3px;
}
.thaw-select:hover {
border-color: var(--thaw-border-color-hover);
}
.thaw-select-menu {
font-size: 14px;
color: var(--thaw-font-color);
background-color: var(--thaw-background-color);
box-sizing: border-box;

View file

@ -6,7 +6,7 @@ use crate::{theme::use_theme, Icon, Theme};
use leptos::*;
use thaw_utils::{class_list, mount_style, OptionalProp};
#[derive(Clone, Default)]
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum TagVariant {
#[default]
Default,

View file

@ -24,6 +24,8 @@ pub struct Follower {
pub enum FollowerWidth {
/// The popup width is the same as the target DOM width.
Target,
/// The popup min width is the same as the target DOM width.
MinTarget,
/// Customize the popup width.
Px(u32),
}
@ -181,6 +183,7 @@ fn FollowerContainer<El: ElementDescriptor + Clone + 'static>(
if let Some(width) = width {
let width = match width {
FollowerWidth::Target => format!("width: {}px;", target_rect.width()),
FollowerWidth::MinTarget => format!("min-width: {}px;", target_rect.width()),
FollowerWidth::Px(width) => format!("width: {width}px;"),
};
style.push_str(&width);