HtmlSelect: make sure selection is updated after render (#163)

This commit is contained in:
Cecile Tonglet 2023-01-30 15:52:58 +01:00 committed by GitHub
parent c2f9b5cce7
commit 2edd2a02b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -8,6 +8,7 @@ use yew::prelude::*;
#[derive(Debug)] #[derive(Debug)]
pub struct HtmlSelect<T: Clone + PartialEq + 'static> { pub struct HtmlSelect<T: Clone + PartialEq + 'static> {
select_element: NodeRef, select_element: NodeRef,
update_selected: bool,
phantom: PhantomData<T>, phantom: PhantomData<T>,
} }
@ -39,6 +40,7 @@ impl<T: ImplicitClone + PartialEq + 'static> Component for HtmlSelect<T> {
fn create(_ctx: &Context<Self>) -> Self { fn create(_ctx: &Context<Self>) -> Self {
Self { Self {
select_element: NodeRef::default(), select_element: NodeRef::default(),
update_selected: false,
phantom: PhantomData, phantom: PhantomData,
} }
} }
@ -57,18 +59,8 @@ impl<T: ImplicitClone + PartialEq + 'static> Component for HtmlSelect<T> {
false false
} }
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool { fn changed(&mut self, _ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
if let Some(value) = ctx.props().value.as_ref() { self.update_selected = true;
if let Some(select) = self.select_element.cast::<HtmlSelectElement>() {
if let Some(i) = ctx.props().options.iter().position(|(x, _)| &x == value) {
if let Ok(i) = i.try_into() {
if select.selected_index() != i {
select.set_selected_index(i);
}
}
}
}
}
true true
} }
@ -122,4 +114,21 @@ impl<T: ImplicitClone + PartialEq + 'static> Component for HtmlSelect<T> {
</div> </div>
} }
} }
fn rendered(&mut self, ctx: &Context<Self>, _first_render: bool) {
if self.update_selected {
self.update_selected = false;
if let Some(value) = ctx.props().value.as_ref() {
if let Some(select) = self.select_element.cast::<HtmlSelectElement>() {
if let Some(i) = ctx.props().options.iter().position(|(x, _)| &x == value) {
if let Ok(i) = i.try_into() {
if select.selected_index() != i {
select.set_selected_index(i);
}
}
}
}
}
}
}
} }