1mod 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
22pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
24
25#[derive(Debug)]
27pub struct PropError {
28 error: BoxError,
29 type_name: &'static str,
30}
31
32impl PropError {
33 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 pub fn type_name(&self) -> &'static str {
45 self.type_name
46 }
47
48 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#[derive(Debug, Default)]
77pub struct Props(pub(crate) IndexMap<String, Prop>);
78
79impl Props {
80 pub fn new() -> Self {
82 Self::default()
83 }
84
85 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 pub fn with(mut self, key: impl Into<String>, value: impl IntoProp) -> Self {
93 self.insert(key, value);
94 self
95 }
96
97 pub fn remove(&mut self, key: &str) -> Option<Prop> {
99 self.0.shift_remove(key)
100 }
101
102 pub fn contains_key(&self, key: &str) -> bool {
104 self.0.contains_key(key)
105 }
106
107 pub fn keys(&self) -> impl Iterator<Item = &str> {
109 self.0.keys().map(String::as_str)
110 }
111
112 pub fn len(&self) -> usize {
114 self.0.len()
115 }
116
117 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
148pub trait IntoProps {
153 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#[macro_export]
221macro_rules! props {
222 ($($tokens:tt)*) => {
223 $crate::__private::props!($crate; $($tokens)*)
224 };
225}
226
227#[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
262pub 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
290pub 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
316pub 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
326pub 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
337pub 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
347pub fn always(value: impl IntoProp) -> Prop {
350 value.into_prop().always()
351}
352
353pub fn live(value: impl IntoProp, listeners: impl IntoIterator<Item = LiveListener>) -> Prop {
365 value.into_prop().live(listeners)
366}
367
368pub 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
407pub fn merge(value: impl IntoProp) -> Prop {
409 value.into_prop().merge()
410}
411
412pub fn deep_merge(value: impl IntoProp) -> Prop {
414 value.into_prop().deep_merge()
415}
416
417pub 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#[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
455pub 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}