Skip to main content

dfui/widgets/
builder.rs

1use std::cell::{Cell, OnceCell};
2use std::future::Future;
3use std::hash::{DefaultHasher, Hash, Hasher};
4use std::task::{Context, Poll};
5
6use futures_core::Stream;
7use taffy::{FlexDirection, Style};
8
9use super::Styled;
10use crate::runtime::task::{Notifier, Task};
11use crate::widget::{BuildCx, Element, Scope, State, Widget};
12
13/// What an async source has produced so far, and whether it has finished.
14#[derive(Default)]
15pub struct Snapshot<T> {
16    /// Everything received so far: the stream's items, or the future's value.
17    pub data: T,
18    /// The source has finished; `data` won't change until it restarts.
19    pub done: bool,
20}
21
22const DRAIN_LIMIT: usize = 1024;
23
24type Source<S> = Box<dyn FnMut(&mut Context, &mut S) -> (bool, bool)>;
25type Start<S> = Box<dyn FnOnce(Scope) -> Source<S>>;
26
27/// Subtree built from the state an async source writes. The source starts on
28/// first build, restarts with fresh state when `deps` change, and is dropped
29/// (cancelled) with the widget.
30pub struct Builder<S> {
31    deps: u64,
32    start: Cell<Option<Start<S>>>,
33    build: Box<dyn Fn(&S) -> Element>,
34    child: OnceCell<[Element; 1]>,
35    style: Style,
36}
37
38/// Rebuilds from a stream's items, collected into `S` (a `Vec`, `String`, ...).
39/// `stream` gets the providers in scope.
40#[doc = example!("stream_builder")]
41pub fn stream_builder<St, S, E>(
42    deps: impl Hash,
43    stream: impl FnOnce(Scope) -> St + 'static,
44    build: impl Fn(&Snapshot<S>) -> E + 'static,
45) -> Builder<Snapshot<S>>
46where
47    St: Stream + 'static,
48    S: Default + Extend<St::Item> + 'static,
49    E: Into<Element>,
50{
51    builder(deps, build, move |scope| {
52        let mut st = Box::pin(stream(scope));
53        Box::new(move |cx: &mut Context, snap: &mut Snapshot<S>| {
54            let mut changed = false;
55            // Drains what's ready, so a burst costs one rebuild; the limit
56            // keeps a stream that never runs dry from taking the UI thread.
57            for _ in 0..DRAIN_LIMIT {
58                match st.as_mut().poll_next(cx) {
59                    Poll::Ready(Some(item)) => {
60                        snap.data.extend([item]);
61                        changed = true;
62                    }
63                    Poll::Ready(None) => {
64                        snap.done = true;
65                        return (true, true);
66                    }
67                    Poll::Pending => return (changed, false),
68                }
69            }
70            cx.waker().wake_by_ref();
71            (changed, false)
72        })
73    })
74}
75
76/// Rebuilds once `future` resolves. `future` gets the providers in scope.
77#[doc = example!("future_builder")]
78pub fn future_builder<F, E>(
79    deps: impl Hash,
80    future: impl FnOnce(Scope) -> F + 'static,
81    build: impl Fn(&Snapshot<Option<F::Output>>) -> E + 'static,
82) -> Builder<Snapshot<Option<F::Output>>>
83where
84    F: Future + 'static,
85    E: Into<Element>,
86{
87    builder(deps, build, move |scope| {
88        let mut f = Box::pin(future(scope));
89        Box::new(
90            move |cx: &mut Context, snap: &mut Snapshot<Option<F::Output>>| match f
91                .as_mut()
92                .poll(cx)
93            {
94                Poll::Ready(v) => {
95                    snap.data = Some(v);
96                    snap.done = true;
97                    (true, true)
98                }
99                Poll::Pending => (false, false),
100            },
101        )
102    })
103}
104
105/// Rebuilds `build`'s subtree each time `notifier` is notified, from any
106/// thread. Unlike a stream, it can't run dry: restarts and several watchers
107/// of one notifier all keep working.
108#[doc = example!("watch")]
109pub fn watch<E: Into<Element>>(
110    notifier: &Notifier,
111    build: impl Fn() -> E + 'static,
112) -> Builder<Seen> {
113    let n = notifier.clone();
114    builder(
115        notifier.id(),
116        move |_: &Seen| build(),
117        move |_| {
118            Box::new(move |cx: &mut Context, seen: &mut Seen| {
119                let v = n.poll_version(cx);
120                let changed = v != seen.0;
121                seen.0 = v;
122                (changed, false)
123            })
124        },
125    )
126}
127
128/// The notifier version a [`watch`] last built from.
129#[derive(Default)]
130pub struct Seen(u64);
131
132fn builder<S: Default + 'static, E: Into<Element>>(
133    deps: impl Hash,
134    build: impl Fn(&S) -> E + 'static,
135    start: impl FnOnce(Scope) -> Source<S> + 'static,
136) -> Builder<S> {
137    let mut h = DefaultHasher::new();
138    deps.hash(&mut h);
139    Builder {
140        deps: h.finish(),
141        start: Cell::new(Some(Box::new(start))),
142        build: Box::new(move |s| build(s).into()),
143        child: OnceCell::new(),
144        style: Style {
145            flex_direction: FlexDirection::Column,
146            ..Style::default()
147        },
148    }
149}
150
151impl<S: Default + 'static> From<Builder<S>> for Element {
152    fn from(w: Builder<S>) -> Self {
153        Element::new(w)
154    }
155}
156
157impl<S> Styled for Builder<S> {
158    fn style_mut(&mut self) -> &mut Style {
159        &mut self.style
160    }
161}
162
163impl<S: Default + 'static> Widget for Builder<S> {
164    fn style(&self) -> Style {
165        self.style.clone()
166    }
167    fn expand(&self, cx: &mut BuildCx) {
168        let stale = cx.tasks.get(&cx.id).is_none_or(|t| t.deps != self.deps);
169        if stale && let Some(start) = self.start.take() {
170            *cx.state.get::<S>() = S::default();
171            let mut source = start(cx.scope);
172            let poll = move |c: &mut Context, st: &mut State| source(c, st.get::<S>());
173            cx.tasks.insert(
174                cx.id,
175                Task {
176                    deps: self.deps,
177                    poll: Some(Box::new(poll)),
178                    polled: false,
179                },
180            );
181        }
182        self.child
183            .get_or_init(|| [(self.build)(cx.state.get::<S>())]);
184    }
185    fn children(&self) -> &[Element] {
186        self.child.get().map_or(&[], |c| c.as_slice())
187    }
188}