Skip to main content

inertia/props/
prop.rs

1use std::fmt;
2use std::time::Duration;
3
4use futures_util::future::BoxFuture;
5use serde::Serialize;
6use serde_json::Value;
7
8use jiff::tz::TimeZone;
9use jiff::{Timestamp, ZonedDateTimeArithmetic};
10
11use super::{PropError, Props, ScrollMetadata};
12use crate::page::{LiveListener, LiveState};
13
14/// A single page prop.
15///
16/// Any `Serialize` value converts into a prop; the functions at the crate
17/// root ([`lazy`](crate::lazy), [`defer`](crate::defer), [`merge`](crate::merge), ...)
18/// create props with special behavior, which the builder methods refine:
19///
20/// ```
21/// let users = inertia::defer(async || vec!["Taylor", "Jess"])
22///     .group("sidebar")
23///     .merge()
24///     .match_on("id");
25/// ```
26#[derive(Debug)]
27#[must_use]
28pub struct Prop {
29    pub(crate) source: Source,
30    pub(crate) options: Options,
31}
32
33/// Where a prop's value comes from.
34pub(crate) enum Source {
35    /// An already serialized value.
36    Value(Value),
37    /// Nested props, which may have behavior of their own.
38    Props(Props),
39    /// A callback that only runs when the prop is part of the response.
40    Callback(Callback),
41    /// A value that failed to serialize.
42    Failed(PropError),
43}
44
45type Callback = Box<dyn FnOnce() -> BoxFuture<'static, Result<Computed, PropError>> + Send>;
46
47/// The output of a prop callback.
48pub(crate) struct Computed {
49    pub(crate) value: Value,
50    pub(crate) scroll: Option<ScrollMetadata>,
51}
52
53/// How a prop behaves during resolution.
54#[derive(Debug, Clone, Default)]
55pub(crate) struct Options {
56    pub(crate) loading: Loading,
57    pub(crate) always: bool,
58    pub(crate) rescue: bool,
59    pub(crate) merge: Option<Merge>,
60    pub(crate) once: Option<Once>,
61    pub(crate) scroll: Option<Scroll>,
62    pub(crate) live: Option<LiveState>,
63}
64
65/// When a prop is sent to the client.
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub(crate) enum Loading {
68    /// With every response that includes it.
69    #[default]
70    Eager,
71    /// Only when a partial reload asks for it.
72    Optional,
73    /// Fetched by the client right after the first render, with its group.
74    Deferred { group: String },
75}
76
77/// How a mergeable prop combines with its client-side value.
78#[derive(Debug, Clone)]
79pub(crate) struct Merge {
80    pub(crate) deep: bool,
81    pub(crate) append: bool,
82    pub(crate) appends_at: Vec<String>,
83    pub(crate) prepends_at: Vec<String>,
84    pub(crate) match_on: Vec<String>,
85}
86
87impl Default for Merge {
88    fn default() -> Self {
89        Self {
90            deep: false,
91            append: true,
92            appends_at: Vec::new(),
93            prepends_at: Vec::new(),
94            match_on: Vec::new(),
95        }
96    }
97}
98
99impl Merge {
100    fn merges_at_root(&self) -> bool {
101        self.appends_at.is_empty() && self.prepends_at.is_empty()
102    }
103
104    pub(crate) fn appends_at_root(&self) -> bool {
105        self.append && self.merges_at_root()
106    }
107
108    pub(crate) fn prepends_at_root(&self) -> bool {
109        !self.append && self.merges_at_root()
110    }
111}
112
113/// The options of a prop the client remembers across visits.
114#[derive(Debug, Clone, Default)]
115pub(crate) struct Once {
116    pub(crate) key: Option<String>,
117    pub(crate) ttl: Option<Duration>,
118    pub(crate) fresh: bool,
119}
120
121/// The options of an infinite scroll prop.
122#[derive(Debug, Clone)]
123pub(crate) struct Scroll {
124    pub(crate) wrapper: String,
125    pub(crate) metadata: Option<ScrollMetadata>,
126}
127
128impl Prop {
129    pub(crate) fn from_source(source: Source) -> Self {
130        Self {
131            source,
132            options: Options::default(),
133        }
134    }
135
136    /// Create a prop from a serializable value.
137    pub fn value(value: impl Serialize) -> Self {
138        Self::from_source(match serde_json::to_value(value) {
139            Ok(value) => Source::Value(value),
140            Err(error) => Source::Failed(error.into()),
141        })
142    }
143
144    /// Only send the prop when a partial reload asks for it.
145    pub fn optional(mut self) -> Self {
146        self.options.loading = Loading::Optional;
147        self
148    }
149
150    /// Leave the prop out of the first render; the client fetches it right
151    /// after, in the `default` group.
152    pub fn deferred(self) -> Self {
153        self.group("default")
154    }
155
156    /// Defer the prop, fetching it with the other props in the given group.
157    pub fn group(mut self, group: impl Into<String>) -> Self {
158        self.options.loading = Loading::Deferred { group: group.into() };
159        self
160    }
161
162    /// Report a failure to resolve the prop in `rescuedProps` instead of
163    /// failing the whole response.
164    pub fn rescue(mut self) -> Self {
165        self.options.rescue = true;
166        self
167    }
168
169    /// Send the prop with every response, even partial reloads that didn't
170    /// ask for it.
171    pub fn always(mut self) -> Self {
172        self.options.always = true;
173        self
174    }
175
176    /// Merge the prop into its client-side value rather than replacing it.
177    pub fn merge(mut self) -> Self {
178        self.merge_options();
179        self
180    }
181
182    /// Deep merge the prop into its client-side value.
183    pub fn deep_merge(mut self) -> Self {
184        self.merge_options().deep = true;
185        self
186    }
187
188    /// Append the prop to its client-side value (the default when merging).
189    pub fn append(mut self) -> Self {
190        self.merge_options().append = true;
191        self
192    }
193
194    /// Prepend the prop to its client-side value.
195    pub fn prepend(mut self) -> Self {
196        self.merge_options().append = false;
197        self
198    }
199
200    /// Append the value at the given nested path, such as `data`.
201    pub fn append_at(mut self, path: impl Into<String>) -> Self {
202        self.merge_options().appends_at.push(path.into());
203        self
204    }
205
206    /// Prepend the value at the given nested path.
207    pub fn prepend_at(mut self, path: impl Into<String>) -> Self {
208        self.merge_options().prepends_at.push(path.into());
209        self
210    }
211
212    /// Match items on the given key while merging, updating them in place
213    /// instead of duplicating them. Use a path like `data.id` for nested items.
214    pub fn match_on(mut self, key: impl Into<String>) -> Self {
215        self.merge_options().match_on.push(key.into());
216        self
217    }
218
219    fn merge_options(&mut self) -> &mut Merge {
220        self.options.merge.get_or_insert_with(Merge::default)
221    }
222
223    /// Resolve the prop once; the client remembers it on later visits.
224    pub fn once(mut self) -> Self {
225        self.once_options();
226        self
227    }
228
229    /// Remember the once prop under the given key, so pages can share it
230    /// under different prop names.
231    pub fn once_as(mut self, key: impl Into<String>) -> Self {
232        self.once_options().key = Some(key.into());
233        self
234    }
235
236    /// Have the client forget the once prop after the given length of
237    /// time, such as `7.days()` or a `std::time::Duration`. Calendar units
238    /// count from now, in UTC.
239    ///
240    /// ```
241    /// use jiff::ToSpan;
242    ///
243    /// let plans = inertia::once(async || ["basic", "pro"]).until(7.days());
244    /// ```
245    pub fn until(mut self, ttl: impl Into<ZonedDateTimeArithmetic>) -> Self {
246        self.once_options().ttl = Some(exact_duration(ttl));
247        self
248    }
249
250    /// Send the once prop even if the client already has it.
251    pub fn fresh(mut self) -> Self {
252        self.once_options().fresh = true;
253        self
254    }
255
256    fn once_options(&mut self) -> &mut Once {
257        self.options.once.get_or_insert_with(Once::default)
258    }
259
260    /// Refresh the prop with a partial reload whenever the client receives
261    /// one of the listeners' broadcast events. Calling it again adds more
262    /// listeners. A live prop can't also merge.
263    ///
264    /// ```
265    /// use inertia::{LiveChannel, LiveListener};
266    ///
267    /// let order = inertia::lazy(async || "shipped")
268    ///     .live([LiveListener::new(LiveChannel::private("orders.1"), ["OrderUpdated"])]);
269    /// ```
270    pub fn live(mut self, listeners: impl IntoIterator<Item = LiveListener>) -> Self {
271        let live = self.live_options();
272
273        for LiveListener { channel, events } in listeners {
274            for event in events {
275                match live.listeners.iter_mut().find(|listener| listener.channel == channel) {
276                    Some(listener) if listener.events.contains(&event) => {}
277                    Some(listener) => listener.events.push(event),
278                    None => live.listeners.push(LiveListener::new(channel.clone(), [event])),
279                }
280            }
281        }
282
283        self
284    }
285
286    /// Refresh the live prop at most once per the given length of time,
287    /// such as `5.seconds()` or a `std::time::Duration`.
288    ///
289    /// ```
290    /// use inertia::{LiveChannel, LiveListener};
291    /// use jiff::ToSpan;
292    ///
293    /// let metrics = inertia::defer(async || 42)
294    ///     .live([LiveListener::new(LiveChannel::public("metrics"), ["MetricsUpdated"])])
295    ///     .throttle(5.seconds());
296    /// ```
297    pub fn throttle(mut self, throttle: impl Into<ZonedDateTimeArithmetic>) -> Self {
298        let throttle = exact_duration(throttle);
299        self.live_options().throttle = Some(u64::try_from(throttle.as_millis()).unwrap_or(u64::MAX));
300        self
301    }
302
303    fn live_options(&mut self) -> &mut LiveState {
304        self.options.live.get_or_insert_with(LiveState::default)
305    }
306
307    /// Set the key holding the items of an infinite scroll prop (`data` by default).
308    pub fn wrapper(mut self, wrapper: impl Into<String>) -> Self {
309        if let Some(scroll) = &mut self.options.scroll {
310            scroll.wrapper = wrapper.into();
311        }
312        self
313    }
314}
315
316/// The exact length of a span from now, in UTC: zero when it's negative, and
317/// the longest `Duration` when it ends past the last representable time.
318fn exact_duration(span: impl Into<ZonedDateTimeArithmetic>) -> Duration {
319    let now = Timestamp::now().to_zoned_datetime(TimeZone::UTC);
320    let Ok(later) = now.checked_add(span) else {
321        return Duration::MAX;
322    };
323
324    Duration::try_from(later.timestamp().duration_since(now.timestamp())).unwrap_or(Duration::ZERO)
325}
326
327impl fmt::Debug for Source {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        match self {
330            Self::Value(value) => f.debug_tuple("Value").field(value).finish(),
331            Self::Props(props) => f.debug_tuple("Props").field(props).finish(),
332            Self::Callback(_) => f.write_str("Callback"),
333            Self::Failed(error) => f.debug_tuple("Failed").field(error).finish(),
334        }
335    }
336}
337
338/// Conversion into a [`Prop`].
339///
340/// Implemented for every `Serialize` type, for [`Prop`] and for nested [`Props`].
341pub trait IntoProp {
342    /// Convert the value into a prop.
343    fn into_prop(self) -> Prop;
344}
345
346impl IntoProp for Prop {
347    fn into_prop(self) -> Prop {
348        self
349    }
350}
351
352impl IntoProp for Props {
353    fn into_prop(self) -> Prop {
354        Prop::from_source(Source::Props(self))
355    }
356}
357
358impl<T: Serialize> IntoProp for T {
359    fn into_prop(self) -> Prop {
360        Prop::value(self)
361    }
362}