feat(ext): add CollectionWidget extension trait

This commit is contained in:
Michael Aaron Murphy 2023-09-01 07:25:00 +02:00 committed by Michael Murphy
parent 26777464c5
commit 28c9b001e4

View file

@ -2,6 +2,7 @@
// SPDX-License-Identifier: MPL-2.0
use iced::Color;
use iced_core::Widget;
pub trait ElementExt {
#[must_use]
@ -17,3 +18,82 @@ impl<'a, Message: 'static> ElementExt for crate::Element<'a, Message> {
}
}
}
/// Additional methods for the [`Column`] and [`Row`] widgets.
pub trait CollectionWidget<'a, Message>: Widget<Message, crate::Renderer> {
/// Moves all the elements of `other` into `self`, leaving `other` empty.
#[must_use]
fn append<E>(self, other: &mut Vec<E>) -> Self
where
E: Into<crate::Element<'a, Message>>;
/// Appends all elements in an iterator to the widget.
#[must_use]
fn extend<E>(self, iterator: impl Iterator<Item = E>) -> Self
where
E: Into<crate::Element<'a, Message>>;
/// Conditionally pushes an element to the widget.
#[must_use]
fn push_maybe(self, element: Option<impl Into<crate::Element<'a, Message>>>) -> Self;
}
impl<'a, Message> CollectionWidget<'a, Message>
for crate::widget::Column<'a, Message, crate::Renderer>
{
fn append<E>(self, other: &mut Vec<E>) -> Self
where
E: Into<crate::Element<'a, Message>>,
{
self.extend(other.drain(..))
}
fn extend<E>(mut self, iterator: impl Iterator<Item = E>) -> Self
where
E: Into<crate::Element<'a, Message>>,
{
for item in iterator {
self = self.push(item.into());
}
self
}
fn push_maybe(self, element: Option<impl Into<crate::Element<'a, Message>>>) -> Self {
if let Some(element) = element {
self.push(element.into())
} else {
self
}
}
}
impl<'a, Message> CollectionWidget<'a, Message>
for crate::widget::Row<'a, Message, crate::Renderer>
{
fn append<E>(self, other: &mut Vec<E>) -> Self
where
E: Into<crate::Element<'a, Message>>,
{
self.extend(other.drain(..))
}
fn extend<E>(mut self, iterator: impl Iterator<Item = E>) -> Self
where
E: Into<crate::Element<'a, Message>>,
{
for item in iterator {
self = self.push(item.into());
}
self
}
fn push_maybe(self, element: Option<impl Into<crate::Element<'a, Message>>>) -> Self {
if let Some(element) = element {
self.push(element.into())
} else {
self
}
}
}