IntoDynamic<T>

This commit is contained in:
Jonathan Johnson 2023-11-08 07:44:10 -08:00
parent 57a689b8c8
commit b27b9db380
No known key found for this signature in database
GPG key ID: A66D6A34D6620579
2 changed files with 29 additions and 3 deletions

View file

@ -513,6 +513,30 @@ impl Generation {
}
}
/// A type that can convert into a `Dynamic<T>`.
pub trait IntoDynamic<T> {
/// Returns `self` as a dynamic.
fn into_dynamic(self) -> Dynamic<T>;
}
impl<T> IntoDynamic<T> for Dynamic<T> {
fn into_dynamic(self) -> Dynamic<T> {
self
}
}
impl<T, F> IntoDynamic<T> 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<T> {
Dynamic::default().with_for_each(self)
}
}
/// A value that may be either constant or dynamic.
#[derive(Debug)]
pub enum Value<T> {

View file

@ -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<WidgetInstance> {
///
/// `focused` will be initialized with an initial state
/// of `false`.
pub fn with_focused(mut self, focused: Dynamic<bool>) -> Self {
pub fn with_focused(mut self, focused: impl IntoDynamic<bool>) -> Self {
let focused = focused.into_dynamic();
focused.update(false);
self.focused = Some(focused);
self
@ -94,7 +95,8 @@ impl Window<WidgetInstance> {
/// visible, this value will contain `true`.
///
/// `occluded` will be initialized with an initial state of `false`.
pub fn with_occluded(mut self, occluded: Dynamic<bool>) -> Self {
pub fn with_occluded(mut self, occluded: impl IntoDynamic<bool>) -> Self {
let occluded = occluded.into_dynamic();
occluded.update(false);
self.occluded = Some(occluded);
self