Skip to main content

egui_kit/remote/
live.rs

1//! [`Live`]: a query made from inputs that change.
2
3use core::fmt;
4use core::hash::Hash;
5use core::time::Duration;
6use std::rc::Rc;
7
8use web_time::Instant;
9
10use super::query::{Query, QueryState};
11use super::runtime::MaybeSend;
12use super::{context, hash};
13
14/// A [`Query`] made from inputs that change, like a date range or a search: made again when
15/// they do.
16///
17/// A query is made from its inputs, and a new one fetches on its first read, so a view can't
18/// make one from its inputs every frame. Keep a `Live` in the view's state instead, and
19/// [`update`](Self::update) it every frame with the inputs: it makes a new query only when they
20/// changed. The inputs are only hashed (like a [key](Query::key)), so pass them borrowed.
21///
22/// Optionally, it [keeps showing the previous value](Self::keep_previous) while the query for
23/// new inputs loads, so that a list doesn't flicker back to a spinner, and [waits for the
24/// inputs to settle](Self::debounce) before it makes the query, so that a search doesn't ask for
25/// every letter typed.
26///
27/// ```
28/// use core::time::Duration;
29///
30/// use egui_kit::remote::{self, Live, Query};
31///
32/// # #[derive(Clone)]
33/// # struct Api;
34/// # impl Api {
35/// #     async fn search(&self, _text: &str) -> Result<Vec<String>, String> { Ok(Vec::new()) }
36/// # }
37/// fn search(api: &Api, text: &str) -> Query<Vec<String>, String> {
38///     let (api, owned) = (api.clone(), text.to_owned());
39///     remote::query(move || {
40///         let (api, text) = (api.clone(), owned.clone());
41///         async move { api.search(&text).await }
42///     })
43///     .key(("search", text))
44/// }
45///
46/// struct Search {
47///     api: Api,
48///     text: String,
49///     results: Live<Vec<String>, String>,
50/// }
51///
52/// impl Search {
53///     fn new(api: Api) -> Self {
54///         Self {
55///             api,
56///             text: String::new(),
57///             results: remote::live()
58///                 // Ask once the text didn't change for a moment…
59///                 .debounce(Duration::from_millis(300))
60///                 // …and show the last results until the new ones arrive.
61///                 .keep_previous(),
62///         }
63///     }
64///
65///     fn ui(&mut self, ui: &mut egui::Ui) {
66///         ui.text_edit_singleline(&mut self.text);
67///         let results = self
68///             .results
69///             .update(&self.text, || search(&self.api, &self.text));
70///         if let Some(names) = results.data() {
71///             // Dimmed while they're the results of an earlier text.
72///             ui.add_enabled_ui(!results.is_previous(), |ui| {
73///                 for name in names.iter() {
74///                     ui.label(name);
75///                 }
76///             });
77///         }
78///     }
79/// }
80/// ```
81///
82/// See [Queries from changing inputs](crate::remote#queries-from-changing-inputs).
83pub struct Live<T, E> {
84    /// The query made last, and the hash of its inputs.
85    current: Option<(u64, Query<T, E>)>,
86    /// The value of an earlier query, until `current` has an answer (with `keep_previous`).
87    previous: Option<Rc<T>>,
88    keep_previous: bool,
89    debounce: Option<Duration>,
90    /// Inputs seen but not made into a query yet, and since when (with `debounce`).
91    wanted: Option<(u64, Instant)>,
92}
93
94/// A [`Live`].
95pub fn live<T: MaybeSend + 'static, E: MaybeSend + 'static>() -> Live<T, E> {
96    Live::default()
97}
98
99impl<T, E> Default for Live<T, E> {
100    fn default() -> Self {
101        Self {
102            current: None,
103            previous: None,
104            keep_previous: false,
105            debounce: None,
106            wanted: None,
107        }
108    }
109}
110
111impl<T: MaybeSend + 'static, E: MaybeSend + 'static> Live<T, E> {
112    /// While the query for new inputs has no answer yet, shows the last value of the one
113    /// before: [`state`](Self::state) is `Ready` with it, and [`is_previous`](Self::is_previous)
114    /// says so. Off by default, so that a view shows `Loading` for new inputs.
115    #[must_use]
116    pub fn keep_previous(mut self) -> Self {
117        self.keep_previous = true;
118        self
119    }
120
121    /// Makes the query only once the inputs didn't change for `after`, the first ones included.
122    /// Meanwhile, it shows the query made before (and [`is_previous`](Self::is_previous)).
123    #[must_use]
124    pub fn debounce(mut self, after: Duration) -> Self {
125        self.debounce = Some(after);
126        self
127    }
128
129    /// Call it every frame with the inputs: makes the query with `make` when they differ from
130    /// the last query's (once they [settled](Self::debounce)), and keeps the one made before
131    /// otherwise. Returns `self`, to read it.
132    ///
133    /// The inputs are hashed, so they may be borrowed: `(&from, &to)`. `make` should key the
134    /// query with them if it's to be [cached](Query::key).
135    pub fn update(&mut self, inputs: impl Hash, make: impl FnOnce() -> Query<T, E>) -> &Self {
136        let inputs = hash(inputs);
137        // The new query answered: the previous value isn't needed anymore.
138        if let Some((_, query)) = &self.current
139            && self.previous.is_some()
140        {
141            let (value, failed) = query.peek();
142            if value.is_some() || failed {
143                self.previous = None;
144            }
145        }
146        if self
147            .current
148            .as_ref()
149            .is_some_and(|(made, _)| *made == inputs)
150        {
151            self.wanted = None;
152            return self;
153        }
154        if let Some(after) = self.debounce {
155            let now = Instant::now();
156            let since = match self.wanted {
157                Some((wanted, since)) if wanted == inputs => since,
158                _ => {
159                    self.wanted = Some((inputs, now));
160                    now
161                }
162            };
163            let left = after.saturating_sub(now.saturating_duration_since(since));
164            if !left.is_zero() {
165                if let Some(ctx) = context() {
166                    ctx.request_repaint_after(left);
167                }
168                return self;
169            }
170        }
171        self.wanted = None;
172        let query = make();
173        // Peeked, not read: the old query's fetch is aborted, not started.
174        if let Some((_, old)) = self.current.replace((inputs, query))
175            && self.keep_previous
176            && let Some(value) = old.peek().0
177        {
178            self.previous = Some(value);
179        }
180        self
181    }
182
183    /// Drops the query, for when there's nothing to ask: it's `Loading` until the next
184    /// [`update`](Self::update).
185    pub fn clear(&mut self) {
186        self.current = None;
187        self.previous = None;
188        self.wanted = None;
189    }
190
191    /// The query made last, if any.
192    pub fn query(&self) -> Option<&Query<T, E>> {
193        self.current.as_ref().map(|(_, query)| query)
194    }
195
196    /// What to show, like [`Query::state`], with the previous value while the query loads if
197    /// [kept](Self::keep_previous). `Loading` while no query was made.
198    pub fn state(&self) -> QueryState<T, E> {
199        let Some(query) = self.query() else {
200            return QueryState::Loading;
201        };
202        match (query.state(), &self.previous) {
203            (QueryState::Loading, Some(previous)) => QueryState::Ready(Rc::clone(previous)),
204            (state, _) => state,
205        }
206    }
207
208    /// The query's value, like [`Query::data`], or the previous value while it loads if
209    /// [kept](Self::keep_previous).
210    pub fn data(&self) -> Option<Rc<T>> {
211        let query = self.query()?;
212        query.data().or_else(|| {
213            query
214                .error()
215                .is_none()
216                .then(|| self.previous.clone())
217                .flatten()
218        })
219    }
220
221    /// Why the query's last fetch failed.
222    pub fn error(&self) -> Option<Rc<E>> {
223        self.query()?.error()
224    }
225
226    /// Whether the query is fetching, see [`Query::is_fetching`].
227    pub fn is_fetching(&self) -> bool {
228        self.query().is_some_and(Query::is_fetching)
229    }
230
231    /// Whether what it shows isn't about the last [`update`](Self::update)'s inputs yet: a
232    /// [debounce](Self::debounce) is waiting, or the [previous value](Self::keep_previous) is
233    /// shown while the new query loads.
234    pub fn is_previous(&self) -> bool {
235        self.wanted.is_some()
236            || self.previous.is_some()
237                && self
238                    .query()
239                    .is_some_and(|query| query.data().is_none() && query.error().is_none())
240    }
241}
242
243impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for Live<T, E> {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.debug_struct("Live")
246            .field("query", &self.current.as_ref().map(|(_, query)| query))
247            .field("previous", &self.previous)
248            .field("waiting", &self.wanted.is_some())
249            .finish_non_exhaustive()
250    }
251}