From b27b9db38084e553a051645407c2051fd0769085 Mon Sep 17 00:00:00 2001 From: Jonathan Johnson Date: Wed, 8 Nov 2023 07:44:10 -0800 Subject: [PATCH] IntoDynamic --- src/value.rs | 24 ++++++++++++++++++++++++ src/window.rs | 8 +++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/value.rs b/src/value.rs index 0cd0535a1..0b6c328cc 100644 --- a/src/value.rs +++ b/src/value.rs @@ -513,6 +513,30 @@ impl Generation { } } +/// A type that can convert into a `Dynamic`. +pub trait IntoDynamic { + /// Returns `self` as a dynamic. + fn into_dynamic(self) -> Dynamic; +} + +impl IntoDynamic for Dynamic { + fn into_dynamic(self) -> Dynamic { + self + } +} + +impl IntoDynamic for F +where + F: FnMut(&T) + Send + 'static, + T: Default, +{ + /// Returns [`Dynamic::default()`] with `self` installed as a for-each + /// callback. + fn into_dynamic(self) -> Dynamic { + Dynamic::default().with_for_each(self) + } +} + /// A value that may be either constant or dynamic. #[derive(Debug)] pub enum Value { diff --git a/src/window.rs b/src/window.rs index fc3af4ce5..63884a3ac 100644 --- a/src/window.rs +++ b/src/window.rs @@ -28,7 +28,7 @@ use crate::graphics::Graphics; use crate::styles::components::VisualOrder; use crate::tree::Tree; use crate::utils::ModifiersExt; -use crate::value::Dynamic; +use crate::value::{Dynamic, IntoDynamic}; use crate::widget::{EventHandling, ManagedWidget, Widget, WidgetInstance, HANDLED, IGNORED}; use crate::window::sealed::WindowCommand; use crate::{ConstraintLimit, Run}; @@ -80,7 +80,8 @@ impl Window { /// /// `focused` will be initialized with an initial state /// of `false`. - pub fn with_focused(mut self, focused: Dynamic) -> Self { + pub fn with_focused(mut self, focused: impl IntoDynamic) -> Self { + let focused = focused.into_dynamic(); focused.update(false); self.focused = Some(focused); self @@ -94,7 +95,8 @@ impl Window { /// visible, this value will contain `true`. /// /// `occluded` will be initialized with an initial state of `false`. - pub fn with_occluded(mut self, occluded: Dynamic) -> Self { + pub fn with_occluded(mut self, occluded: impl IntoDynamic) -> Self { + let occluded = occluded.into_dynamic(); occluded.update(false); self.occluded = Some(occluded); self