Take AsRef<Widget> instead of Element in Tree API

This commit is contained in:
Héctor Ramón Jiménez 2022-05-06 19:42:14 +02:00
parent 2243e46190
commit f1c1d519c5
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
2 changed files with 27 additions and 13 deletions

View file

@ -321,3 +321,11 @@ where
.map(move |overlay| overlay.map(mapper))
}
}
impl<'a, Message, Renderer> AsRef<dyn Widget<Message, Renderer> + 'a>
for Element<'a, Message, Renderer>
{
fn as_ref(&self) -> &(dyn Widget<Message, Renderer> + 'a) {
self.widget.as_ref()
}
}

View file

@ -1,5 +1,5 @@
//! Store internal widget state in a state tree to ensure continuity.
use crate::Element;
use crate::Widget;
use std::any::{self, Any};
@ -28,13 +28,15 @@ impl Tree {
}
/// Creates a new [`Tree`] for the provided [`Element`].
pub fn new<Message, Renderer>(
element: &Element<'_, Message, Renderer>,
pub fn new<'a, Message, Renderer>(
widget: impl AsRef<dyn Widget<Message, Renderer> + 'a>,
) -> Self {
let widget = widget.as_ref();
Self {
tag: element.as_widget().tag(),
state: element.as_widget().state(),
children: element.as_widget().children(),
tag: widget.tag(),
state: widget.state(),
children: widget.children(),
}
}
@ -46,23 +48,27 @@ impl Tree {
/// Otherwise, the whole [`Tree`] is recreated.
///
/// [`Widget::diff`]: crate::Widget::diff
pub fn diff<Message, Renderer>(
pub fn diff<'a, Message, Renderer>(
&mut self,
new: &Element<'_, Message, Renderer>,
new: impl AsRef<dyn Widget<Message, Renderer> + 'a>,
) {
if self.tag == new.as_widget().tag() {
new.as_widget().diff(self)
if self.tag == new.as_ref().tag() {
new.as_ref().diff(self)
} else {
*self = Self::new(new);
}
}
/// Reconciliates the children of the tree with the provided list of [`Element`].
pub fn diff_children<Message, Renderer>(
pub fn diff_children<'a, Message, Renderer>(
&mut self,
new_children: &[Element<'_, Message, Renderer>],
new_children: &[impl AsRef<dyn Widget<Message, Renderer> + 'a>],
) {
self.diff_children_custom(new_children, Self::diff, Self::new)
self.diff_children_custom(
new_children,
|tree, widget| Self::diff(tree, widget),
|widget| Self::new(widget),
)
}
/// Reconciliates the children of the tree with the provided list of [`Element`] using custom