Make Widget::diff mutable

This commit is contained in:
Héctor Ramón Jiménez 2025-08-20 23:14:23 +02:00
parent 31bc6d48cd
commit 497ebcd0c3
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
31 changed files with 114 additions and 81 deletions

View file

@ -2,7 +2,7 @@
use crate::Widget;
use std::any::{self, Any};
use std::borrow::Borrow;
use std::borrow::{Borrow, BorrowMut};
use std::fmt;
/// A persistent state widget tree.
@ -56,12 +56,12 @@ impl Tree {
/// [`Widget::diff`]: crate::Widget::diff
pub fn diff<'a, Message, Theme, Renderer>(
&mut self,
new: impl Borrow<dyn Widget<Message, Theme, Renderer> + 'a>,
mut new: impl BorrowMut<dyn Widget<Message, Theme, Renderer> + 'a>,
) where
Renderer: crate::Renderer,
{
if self.tag == new.borrow().tag() {
new.borrow().diff(self);
if self.tag == new.borrow_mut().tag() {
new.borrow_mut().diff(self);
} else {
*self = Self::new(new);
}
@ -70,13 +70,15 @@ impl Tree {
/// Reconciles the children of the tree with the provided list of widgets.
pub fn diff_children<'a, Message, Theme, Renderer>(
&mut self,
new_children: &[impl Borrow<dyn Widget<Message, Theme, Renderer> + 'a>],
new_children: &mut [impl BorrowMut<
dyn Widget<Message, Theme, Renderer> + 'a,
>],
) where
Renderer: crate::Renderer,
{
self.diff_children_custom(
new_children,
|tree, widget| tree.diff(widget.borrow()),
|tree, widget| tree.diff(widget.borrow_mut()),
|widget| Self::new(widget.borrow()),
);
}
@ -85,8 +87,8 @@ impl Tree {
/// logic both for diffing and creating new widget state.
pub fn diff_children_custom<T>(
&mut self,
new_children: &[T],
diff: impl Fn(&mut Tree, &T),
new_children: &mut [T],
diff: impl Fn(&mut Tree, &mut T),
new_state: impl Fn(&T) -> Self,
) {
if self.children.len() > new_children.len() {
@ -94,7 +96,7 @@ impl Tree {
}
for (child_state, new) in
self.children.iter_mut().zip(new_children.iter())
self.children.iter_mut().zip(new_children.iter_mut())
{
diff(child_state, new);
}
@ -114,8 +116,8 @@ impl Tree {
/// `maybe_changed` closure.
pub fn diff_children_custom_with_search<T>(
current_children: &mut Vec<Tree>,
new_children: &[T],
diff: impl Fn(&mut Tree, &T),
new_children: &mut [T],
diff: impl Fn(&mut Tree, &mut T),
maybe_changed: impl Fn(usize) -> bool,
new_state: impl Fn(&T) -> Tree,
) {
@ -183,7 +185,7 @@ pub fn diff_children_custom_with_search<T>(
// TODO: Merge loop with extend logic (?)
for (child_state, new) in
current_children.iter_mut().zip(new_children.iter())
current_children.iter_mut().zip(new_children.iter_mut())
{
diff(child_state, new);
}