use crate::props::closure::{DeferredProp, LazyProp};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::future::Future;
pub struct InertiaResponse {
pub(crate) component: String,
pub(crate) base_props: Value,
pub(crate) lazies: HashMap<String, LazyProp>,
pub(crate) deferreds: HashMap<String, DeferredProp>,
pub(crate) merges: HashSet<String>,
pub(crate) encrypt_history: bool,
pub(crate) clear_history: bool,
pub(crate) reset_merge_props: Vec<String>,
pub(crate) skip_ssr: bool,
pub(crate) redirect: Option<crate::protocol::Redirect>,
pub(crate) pending_flash: crate::session::Flash,
}
impl InertiaResponse {
pub(crate) fn new(component: impl Into<String>, base_props: Value) -> Self {
Self {
component: component.into(),
base_props,
lazies: HashMap::new(),
deferreds: HashMap::new(),
merges: HashSet::new(),
encrypt_history: false,
clear_history: false,
reset_merge_props: Vec::new(),
skip_ssr: false,
redirect: None,
pending_flash: Default::default(),
}
}
pub fn lazy<F, Fut>(mut self, key: impl Into<String>, f: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = Value> + Send + 'static,
{
self.lazies.insert(
key.into(),
LazyProp {
closure: Box::new(|| Box::pin(f())),
},
);
self
}
pub fn optional<F, Fut>(self, key: impl Into<String>, f: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = Value> + Send + 'static,
{
self.lazy(key, f)
}
pub fn deferred<F, Fut>(mut self, key: impl Into<String>, group: &'static str, f: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = Value> + Send + 'static,
{
self.deferreds.insert(
key.into(),
DeferredProp {
group,
closure: Box::new(|| Box::pin(f())),
},
);
self
}
pub fn merge(mut self, key: impl Into<String>) -> Self {
self.merges.insert(key.into());
self
}
pub fn encrypt_history(mut self) -> Self {
self.encrypt_history = true;
self
}
pub fn clear_history(mut self) -> Self {
self.clear_history = true;
self
}
pub fn reset_merge(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.reset_merge_props
.extend(keys.into_iter().map(Into::into));
self
}
pub fn no_ssr(mut self) -> Self {
self.skip_ssr = true;
self
}
pub fn with_errors<E: crate::errors::IntoErrorBag>(mut self, errors: E) -> Self {
self.pending_flash.errors.extend(errors.into_error_bag());
self
}
pub fn with_flash(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.pending_flash.bags.insert(key.into(), value.into());
self
}
pub fn redirect(mut self, location: impl Into<String>) -> Self {
self.redirect = Some(crate::protocol::Redirect::Internal(location.into()));
self
}
pub fn location(mut self, location: impl Into<String>) -> Self {
self.redirect = Some(crate::protocol::Redirect::External(location.into()));
self
}
}