Skip to main content

inertia/props/
mod.rs

1//! Page props: the data a page component receives, and the behavior that
2//! controls when and how each prop is sent.
3
4mod prop;
5mod resolver;
6mod scroll;
7
8use std::fmt;
9use std::future::Future;
10
11use indexmap::IndexMap;
12use serde::Serialize;
13use serde_json::Value;
14
15use crate::page::LiveListener;
16
17pub(crate) use self::prop::{Computed, Loading, Merge, Once, Source};
18pub use self::prop::{IntoProp, Prop};
19pub(crate) use self::resolver::PropsResolver;
20pub use self::scroll::{ProvidesScrollMetadata, ScrollMetadata};
21
22/// A boxed error, as returned by fallible prop callbacks.
23pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
24
25/// An error raised while resolving a prop.
26#[derive(Debug)]
27pub struct PropError {
28    error: BoxError,
29    type_name: &'static str,
30}
31
32impl PropError {
33    /// Wrap an error.
34    pub fn new<E: Into<BoxError>>(error: E) -> Self {
35        Self {
36            error: error.into(),
37            type_name: std::any::type_name::<E>(),
38        }
39    }
40
41    /// The name of the error's type, as [`std::any::type_name`] gives it,
42    /// since the boxed error from [`into_inner`](Self::into_inner) no longer
43    /// has it.
44    pub fn type_name(&self) -> &'static str {
45        self.type_name
46    }
47
48    /// The error the prop failed with.
49    pub fn into_inner(self) -> BoxError {
50        self.error
51    }
52}
53
54impl fmt::Display for PropError {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        self.error.fmt(f)
57    }
58}
59
60impl std::error::Error for PropError {
61    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
62        Some(&*self.error)
63    }
64}
65
66impl From<serde_json::Error> for PropError {
67    fn from(error: serde_json::Error) -> Self {
68        Self::new(error)
69    }
70}
71
72/// An ordered set of page props.
73///
74/// Keys may use dot notation (`"auth.user"`) to set nested props. The
75/// [`props!`](crate::props!) macro is the most convenient way to build one.
76#[derive(Debug, Default)]
77pub struct Props(pub(crate) IndexMap<String, Prop>);
78
79impl Props {
80    /// Create an empty set of props.
81    pub fn new() -> Self {
82        Self::default()
83    }
84
85    /// Insert a prop, replacing any prop with the same key.
86    pub fn insert(&mut self, key: impl Into<String>, value: impl IntoProp) -> &mut Self {
87        self.0.insert(key.into(), value.into_prop());
88        self
89    }
90
91    /// Insert a prop, returning the set for chaining.
92    pub fn with(mut self, key: impl Into<String>, value: impl IntoProp) -> Self {
93        self.insert(key, value);
94        self
95    }
96
97    /// Remove a prop.
98    pub fn remove(&mut self, key: &str) -> Option<Prop> {
99        self.0.shift_remove(key)
100    }
101
102    /// Whether a prop with the given key exists.
103    pub fn contains_key(&self, key: &str) -> bool {
104        self.0.contains_key(key)
105    }
106
107    /// The prop keys, in order.
108    pub fn keys(&self) -> impl Iterator<Item = &str> {
109        self.0.keys().map(String::as_str)
110    }
111
112    /// The number of props.
113    pub fn len(&self) -> usize {
114        self.0.len()
115    }
116
117    /// Whether there are no props.
118    pub fn is_empty(&self) -> bool {
119        self.0.is_empty()
120    }
121}
122
123impl<K: Into<String>, V: IntoProp> Extend<(K, V)> for Props {
124    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
125        for (key, value) in iter {
126            self.insert(key, value);
127        }
128    }
129}
130
131impl<K: Into<String>, V: IntoProp> FromIterator<(K, V)> for Props {
132    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
133        let mut props = Self::new();
134        props.extend(iter);
135        props
136    }
137}
138
139impl IntoIterator for Props {
140    type Item = (String, Prop);
141    type IntoIter = indexmap::map::IntoIter<String, Prop>;
142
143    fn into_iter(self) -> Self::IntoIter {
144        self.0.into_iter()
145    }
146}
147
148/// Conversion into the props of a page.
149///
150/// Implemented for [`Props`] and for any `Serialize` type that serializes to
151/// a JSON object (such as a struct) or to `null` (such as `()`).
152pub trait IntoProps {
153    /// Convert the value into props.
154    ///
155    /// # Errors
156    ///
157    /// Fails when the value doesn't serialize to a JSON object or `null`.
158    fn into_props(self) -> Result<Props, PropError>;
159}
160
161impl IntoProps for Props {
162    fn into_props(self) -> Result<Props, PropError> {
163        Ok(self)
164    }
165}
166
167impl<T: Serialize> IntoProps for T {
168    fn into_props(self) -> Result<Props, PropError> {
169        match serde_json::to_value(self)? {
170            Value::Object(object) => Ok(object.into_iter().collect()),
171            Value::Null => Ok(Props::new()),
172            other => Err(PropError::new(format!(
173                "page props must serialize to a JSON object, not `{other}`"
174            ))),
175        }
176    }
177}
178
179/// Build a set of [`Props`]: from the variables it names, `name => value`
180/// pairs, or `"name" => value` pairs for keys that aren't Rust identifiers,
181/// such as dotted paths. A key is the name as written.
182///
183/// ```
184/// let user = String::from("Taylor");
185///
186/// let props = inertia::props! {
187///     user,
188///     can_edit => true,
189///     "auth.user.id" => 1,
190///     stats => inertia::defer(async || 42),
191/// };
192///
193/// assert_eq!(user, "Taylor");
194/// ```
195///
196/// A variable named on its own is borrowed and serialized straight away, so
197/// the caller keeps it. A `name => value` pair takes the value as written:
198/// pass `&value` to keep it, and move a [`Prop`], such as a deferred one,
199/// with `stats => stats`.
200///
201/// `if`, `else if`, `else` and `if let` blocks add their props only when
202/// their condition holds:
203///
204/// ```
205/// # let (is_admin, team) = (true, Some("Laravel"));
206/// let props = inertia::props! {
207///     if is_admin {
208///         stats => inertia::defer(async || 42),
209///     } else {
210///         upgrade => "Upgrade to see stats",
211///     }
212///     if let Some(team) = team {
213///         team,
214///     }
215/// };
216///
217/// assert!(props.contains_key("stats") && props.contains_key("team"));
218/// assert!(!props.contains_key("upgrade"));
219/// ```
220#[macro_export]
221macro_rules! props {
222    ($($tokens:tt)*) => {
223        $crate::__private::props!($crate; $($tokens)*)
224    };
225}
226
227/// What a lazy prop's callback returns: a value to serialize, or a
228/// `Result` of one, whose error fails the response unless the prop is
229/// [rescued](Prop::rescue).
230///
231/// The marker `M` tells the two apart. A callback that returns a `Result`
232/// whose `Ok` and `Err` types are both `Serialize`, such as
233/// `Result<T, String>`, matches both; use [`try_lazy`] for it.
234#[diagnostic::on_unimplemented(
235    message = "a lazy prop's callback returns `{Self}`, which isn't a prop value",
236    label = "this callback",
237    note = "return a `Serialize` value, or a `Result` of one whose error converts into `Box<dyn Error + Send + Sync>`"
238)]
239pub trait Loaded<M> {
240    #[doc(hidden)]
241    fn into_json(self) -> Result<Value, PropError>;
242}
243
244#[doc(hidden)]
245pub enum Plain {}
246
247#[doc(hidden)]
248pub enum Fallible {}
249
250impl<T: Serialize> Loaded<Plain> for T {
251    fn into_json(self) -> Result<Value, PropError> {
252        Ok(serde_json::to_value(self)?)
253    }
254}
255
256impl<T: Serialize, E: Into<BoxError>> Loaded<Fallible> for Result<T, E> {
257    fn into_json(self) -> Result<Value, PropError> {
258        Ok(serde_json::to_value(self.map_err(PropError::new)?)?)
259    }
260}
261
262/// A prop computed by a callback, which only runs when the prop is part of
263/// the response, after the handler has returned. The callback owns what it
264/// uses, so move values into it.
265///
266/// The callback may return a `Result`. Its error fails the response, unless
267/// the prop is [rescued](Prop::rescue).
268///
269/// ```
270/// # async fn load_stats() -> Result<u32, std::io::Error> { Ok(1) }
271/// let user = inertia::lazy(async || "Taylor");
272/// let stats = inertia::lazy(async || load_stats().await);
273/// ```
274pub fn lazy<F, Fut, T, M>(callback: F) -> Prop
275where
276    F: FnOnce() -> Fut + Send + 'static,
277    Fut: Future<Output = T> + Send + 'static,
278    T: Loaded<M>,
279{
280    Prop::from_source(Source::Callback(Box::new(move || {
281        Box::pin(async move {
282            Ok(Computed {
283                value: callback().await.into_json()?,
284                scroll: None,
285            })
286        })
287    })))
288}
289
290/// A prop computed by a fallible callback. An error fails the response,
291/// unless the prop is [rescued](Prop::rescue).
292///
293/// ```
294/// # async fn load_stats() -> Result<u32, std::io::Error> { Ok(1) }
295/// let stats = inertia::try_lazy(|| load_stats()).deferred().rescue();
296/// ```
297pub fn try_lazy<F, Fut, T, E>(callback: F) -> Prop
298where
299    F: FnOnce() -> Fut + Send + 'static,
300    Fut: Future<Output = Result<T, E>> + Send + 'static,
301    T: Serialize,
302    E: Into<BoxError>,
303{
304    Prop::from_source(Source::Callback(Box::new(move || {
305        Box::pin(async move {
306            let value = callback().await.map_err(PropError::new)?;
307
308            Ok(Computed {
309                value: serde_json::to_value(value)?,
310                scroll: None,
311            })
312        })
313    })))
314}
315
316/// A prop that is only sent when a partial reload asks for it.
317pub fn optional<F, Fut, T, M>(callback: F) -> Prop
318where
319    F: FnOnce() -> Fut + Send + 'static,
320    Fut: Future<Output = T> + Send + 'static,
321    T: Loaded<M>,
322{
323    lazy(callback).optional()
324}
325
326/// A prop the client fetches right after the first render, so a slow prop
327/// doesn't hold up the page.
328pub fn defer<F, Fut, T, M>(callback: F) -> Prop
329where
330    F: FnOnce() -> Fut + Send + 'static,
331    Fut: Future<Output = T> + Send + 'static,
332    T: Loaded<M>,
333{
334    lazy(callback).deferred()
335}
336
337/// A prop that is resolved once and remembered by the client on later visits.
338pub fn once<F, Fut, T, M>(callback: F) -> Prop
339where
340    F: FnOnce() -> Fut + Send + 'static,
341    Fut: Future<Output = T> + Send + 'static,
342    T: Loaded<M>,
343{
344    lazy(callback).once()
345}
346
347/// A prop that is sent with every response, even partial reloads that
348/// didn't ask for it.
349pub fn always(value: impl IntoProp) -> Prop {
350    value.into_prop().always()
351}
352
353/// A prop the client refreshes with a partial reload whenever it receives
354/// one of the listeners' broadcast events.
355///
356/// ```
357/// use inertia::{LiveChannel, LiveListener};
358///
359/// let order = inertia::live(
360///     inertia::lazy(async || "shipped"),
361///     [LiveListener::new(LiveChannel::private("orders.1"), ["OrderUpdated"])],
362/// );
363/// ```
364pub fn live(value: impl IntoProp, listeners: impl IntoIterator<Item = LiveListener>) -> Prop {
365    value.into_prop().live(listeners)
366}
367
368/// Add props to a broadcast event's payload, so the client applies them to
369/// the live props they name without reloading them.
370///
371/// The props are sent under `__inertia.props`. Their keys are kept as
372/// written; dot notation doesn't nest them.
373///
374/// ```
375/// use serde_json::json;
376///
377/// let payload = inertia::broadcast_props(json!({ "order_id": 1 }), json!({ "order": "shipped" }))?;
378///
379/// assert_eq!(payload, json!({ "order_id": 1, "__inertia": { "props": { "order": "shipped" } } }));
380/// # Ok::<(), inertia::PropError>(())
381/// ```
382///
383/// # Errors
384///
385/// Fails when the payload isn't a JSON object, or the props don't serialize
386/// to one.
387pub fn broadcast_props(payload: Value, props: impl Serialize) -> Result<Value, PropError> {
388    let Value::Object(mut payload) = payload else {
389        return Err(PropError::new(format!(
390            "a broadcast payload must be a JSON object, not `{payload}`"
391        )));
392    };
393
394    let props = serde_json::to_value(props)?;
395
396    if !props.is_object() {
397        return Err(PropError::new(format!(
398            "broadcast props must serialize to a JSON object, not `{props}`"
399        )));
400    }
401
402    payload.insert("__inertia".to_owned(), serde_json::json!({ "props": props }));
403
404    Ok(Value::Object(payload))
405}
406
407/// A prop that is appended to its client-side value instead of replacing it.
408pub fn merge(value: impl IntoProp) -> Prop {
409    value.into_prop().merge()
410}
411
412/// A prop that is deep merged with its client-side value.
413pub fn deep_merge(value: impl IntoProp) -> Prop {
414    value.into_prop().deep_merge()
415}
416
417/// An infinite scroll prop, from a page of items that describes its pages with
418/// [`ProvidesScrollMetadata`]. The items go under the page's `data` key.
419pub fn scroll<P>(page: P) -> Prop
420where
421    P: ProvidesScrollMetadata + Serialize,
422{
423    let metadata = page.scroll_metadata();
424
425    scrollable(Prop::value(page), Some(metadata))
426}
427
428/// A page of items that a [`scroll_with`] callback returns: a value with
429/// [`ProvidesScrollMetadata`], or a `Result` of one. The marker `M` tells the
430/// two apart.
431#[diagnostic::on_unimplemented(
432    message = "a scroll prop's callback returns `{Self}`, which isn't a page of items",
433    label = "this callback",
434    note = "return a `Serialize` value that implements `ProvidesScrollMetadata`, or a `Result` of one whose error converts into `Box<dyn Error + Send + Sync>`"
435)]
436pub trait LoadedPage<M> {
437    #[doc(hidden)]
438    fn into_page(self) -> Result<(Value, ScrollMetadata), PropError>;
439}
440
441impl<P: ProvidesScrollMetadata + Serialize> LoadedPage<Plain> for P {
442    fn into_page(self) -> Result<(Value, ScrollMetadata), PropError> {
443        let metadata = self.scroll_metadata();
444
445        Ok((serde_json::to_value(self)?, metadata))
446    }
447}
448
449impl<P: ProvidesScrollMetadata + Serialize, E: Into<BoxError>> LoadedPage<Fallible> for Result<P, E> {
450    fn into_page(self) -> Result<(Value, ScrollMetadata), PropError> {
451        self.map_err(PropError::new)?.into_page()
452    }
453}
454
455/// An infinite scroll prop, from a callback that loads a page of items. The
456/// callback may return a `Result`. Its error fails the response, unless the
457/// prop is [rescued](Prop::rescue).
458pub fn scroll_with<F, Fut, P, M>(callback: F) -> Prop
459where
460    F: FnOnce() -> Fut + Send + 'static,
461    Fut: Future<Output = P> + Send + 'static,
462    P: LoadedPage<M>,
463{
464    let source = Source::Callback(Box::new(move || {
465        Box::pin(async move {
466            let (value, metadata) = callback().await.into_page()?;
467
468            Ok(Computed {
469                value,
470                scroll: Some(metadata),
471            })
472        })
473    }));
474
475    scrollable(Prop::from_source(source), None)
476}
477
478fn scrollable(prop: Prop, metadata: Option<ScrollMetadata>) -> Prop {
479    let mut prop = prop.merge();
480    prop.options.scroll = Some(prop::Scroll {
481        wrapper: "data".to_owned(),
482        metadata,
483    });
484    prop
485}