Skip to main content

dfui/widgets/
provide.rs

1use std::any::Any;
2
3use taffy::{FlexDirection, Style};
4
5use super::Styled;
6use crate::widget::{Element, Widget};
7
8/// Makes `T` available to every descendant through `Scope::get`, e.g. a
9/// handle to external state or a service a builder starts work from.
10pub struct Provide<T> {
11    value: T,
12    child: [Element; 1],
13    style: Style,
14}
15
16/// `child` with `value` in its scope; see [`Provide`].
17#[doc = example!("provide")]
18pub fn provide<T: 'static>(value: T, child: impl Into<Element>) -> Provide<T> {
19    Provide {
20        value,
21        child: [child.into()],
22        style: Style {
23            flex_direction: FlexDirection::Column,
24            ..Style::default()
25        },
26    }
27}
28
29impl<T: 'static> From<Provide<T>> for Element {
30    fn from(w: Provide<T>) -> Self {
31        Element::new(w)
32    }
33}
34
35impl<T> Styled for Provide<T> {
36    fn style_mut(&mut self) -> &mut Style {
37        &mut self.style
38    }
39}
40
41impl<T: 'static> Widget for Provide<T> {
42    fn style(&self) -> Style {
43        self.style.clone()
44    }
45    fn children(&self) -> &[Element] {
46        &self.child
47    }
48    fn provide(&self) -> Option<&dyn Any> {
49        Some(&self.value)
50    }
51}