From 28c9b001e4cffefd8c38d4404cea62c93ff189e5 Mon Sep 17 00:00:00 2001 From: Michael Aaron Murphy Date: Fri, 1 Sep 2023 07:25:00 +0200 Subject: [PATCH] feat(ext): add CollectionWidget extension trait --- src/ext.rs | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/src/ext.rs b/src/ext.rs index 12e52853..984a0f6b 100644 --- a/src/ext.rs +++ b/src/ext.rs @@ -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 { + /// Moves all the elements of `other` into `self`, leaving `other` empty. + #[must_use] + fn append(self, other: &mut Vec) -> Self + where + E: Into>; + + /// Appends all elements in an iterator to the widget. + #[must_use] + fn extend(self, iterator: impl Iterator) -> Self + where + E: Into>; + + /// Conditionally pushes an element to the widget. + #[must_use] + fn push_maybe(self, element: Option>>) -> Self; +} + +impl<'a, Message> CollectionWidget<'a, Message> + for crate::widget::Column<'a, Message, crate::Renderer> +{ + fn append(self, other: &mut Vec) -> Self + where + E: Into>, + { + self.extend(other.drain(..)) + } + + fn extend(mut self, iterator: impl Iterator) -> Self + where + E: Into>, + { + for item in iterator { + self = self.push(item.into()); + } + + self + } + + fn push_maybe(self, element: Option>>) -> 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(self, other: &mut Vec) -> Self + where + E: Into>, + { + self.extend(other.drain(..)) + } + + fn extend(mut self, iterator: impl Iterator) -> Self + where + E: Into>, + { + for item in iterator { + self = self.push(item.into()); + } + + self + } + + fn push_maybe(self, element: Option>>) -> Self { + if let Some(element) = element { + self.push(element.into()) + } else { + self + } + } +}