ferro_rs/inertia/context.rs
1//! Inertia.js integration - async-safe implementation.
2//!
3//! This module provides the main `Inertia` struct for rendering Inertia responses.
4//! It wraps the framework-agnostic `ferro-inertia` crate with Ferro-specific features.
5
6use crate::csrf::csrf_token;
7use crate::http::{HttpResponse, Request};
8use crate::Response;
9use ferro_inertia::{InertiaConfig, InertiaRequest as InertiaRequestTrait};
10use serde::Serialize;
11use std::collections::HashMap;
12
13// Re-export InertiaShared from ferro-inertia
14pub use ferro_inertia::InertiaShared;
15
16/// Implement the framework-agnostic InertiaRequest trait for Ferro's Request type.
17impl InertiaRequestTrait for Request {
18 fn inertia_header(&self, name: &str) -> Option<&str> {
19 self.header(name)
20 }
21
22 fn path(&self) -> &str {
23 Request::path(self)
24 }
25}
26
27/// Saved Inertia context for use after consuming the Request.
28///
29/// Use this when you need to call `req.input()` (which consumes the request)
30/// but still need to render Inertia error responses.
31///
32/// # Example
33///
34/// ```rust,ignore
35/// use ferro_rs::{Inertia, Request, Response, SavedInertiaContext};
36///
37/// pub async fn login(req: Request) -> Response {
38/// // Save Inertia context before consuming request
39/// let ctx = SavedInertiaContext::from(&req);
40///
41/// // This consumes the request
42/// let form: LoginForm = req.input().await?;
43///
44/// // Use saved context for error responses
45/// if let Err(errors) = form.validate() {
46/// return Inertia::render(&ctx, "auth/Login", LoginProps { errors });
47/// }
48///
49/// // ...
50/// }
51/// ```
52#[derive(Clone, Debug)]
53pub struct SavedInertiaContext {
54 path: String,
55 headers: HashMap<String, String>,
56}
57
58impl SavedInertiaContext {
59 /// Create a new SavedInertiaContext by capturing data from a Request.
60 pub fn new(req: &Request) -> Self {
61 let mut headers = HashMap::new();
62
63 // Capture Inertia-relevant headers
64 for name in &[
65 "X-Inertia",
66 "X-Inertia-Version",
67 "X-Inertia-Partial-Data",
68 "X-Inertia-Partial-Component",
69 ] {
70 if let Some(value) = req.header(name) {
71 headers.insert(name.to_string(), value.to_string());
72 }
73 }
74
75 Self {
76 path: req.path().to_string(),
77 headers,
78 }
79 }
80}
81
82impl From<&Request> for SavedInertiaContext {
83 fn from(req: &Request) -> Self {
84 Self::new(req)
85 }
86}
87
88impl InertiaRequestTrait for SavedInertiaContext {
89 fn inertia_header(&self, name: &str) -> Option<&str> {
90 self.headers.get(name).map(|s| s.as_str())
91 }
92
93 fn path(&self) -> &str {
94 &self.path
95 }
96}
97
98/// Main Inertia integration struct for Ferro framework.
99///
100/// Provides methods for rendering Inertia responses in an async-safe manner.
101/// All state is derived from the Request, not thread-local storage.
102pub struct Inertia;
103
104impl Inertia {
105 /// Render an Inertia response.
106 ///
107 /// This is the primary method for returning Inertia responses from controllers.
108 /// It automatically:
109 /// - Detects XHR vs initial page load
110 /// - Merges shared props from middleware
111 /// - Filters props for partial reloads
112 /// - Includes CSRF token in HTML responses
113 ///
114 /// # Example
115 ///
116 /// ```rust,ignore
117 /// use ferro_rs::{Inertia, Request, Response};
118 ///
119 /// pub async fn index(req: Request) -> Response {
120 /// Inertia::render(&req, "Home", HomeProps {
121 /// title: "Welcome".into(),
122 /// })
123 /// }
124 /// ```
125 pub fn render<P: Serialize>(req: &Request, component: &str, props: P) -> Response {
126 Self::render_with_config(req, component, props, InertiaConfig::default())
127 }
128
129 /// Render an Inertia response with custom configuration.
130 pub fn render_with_config<P: Serialize>(
131 req: &Request,
132 component: &str,
133 props: P,
134 config: InertiaConfig,
135 ) -> Response {
136 // Get shared props from middleware (if set)
137 let shared = req.get::<InertiaShared>();
138
139 // Get CSRF token for HTML responses
140 let csrf = csrf_token().unwrap_or_default();
141
142 // Build shared props with CSRF included
143 let effective_shared = if let Some(existing) = shared {
144 // Clone and add CSRF if not already set
145 let mut shared_clone = existing.clone();
146 if shared_clone.csrf.is_none() {
147 shared_clone.csrf = Some(csrf.clone());
148 }
149 Some(shared_clone)
150 } else {
151 Some(InertiaShared::new().csrf(csrf.clone()))
152 };
153
154 // Use ferro-inertia for the core rendering logic
155 let http_response = ferro_inertia::Inertia::render_with_options(
156 req,
157 component,
158 props,
159 effective_shared.as_ref(),
160 config,
161 );
162
163 // Convert InertiaHttpResponse to Ferro's Response
164 Ok(Self::convert_response(http_response))
165 }
166
167 /// Render an Inertia response using a saved context.
168 ///
169 /// Use this when you've already consumed the Request (e.g., via `req.input()`)
170 /// but still need to render an Inertia response (typically for validation errors).
171 ///
172 /// # Example
173 ///
174 /// ```rust,ignore
175 /// use ferro_rs::{Inertia, Request, Response, SavedInertiaContext};
176 ///
177 /// pub async fn login(req: Request) -> Response {
178 /// let ctx = SavedInertiaContext::from(&req);
179 /// let form: LoginForm = req.input().await?;
180 ///
181 /// if let Err(errors) = form.validate() {
182 /// return Inertia::render_ctx(&ctx, "auth/Login", LoginProps { errors });
183 /// }
184 /// // ...
185 /// }
186 /// ```
187 pub fn render_ctx<P: Serialize>(
188 ctx: &SavedInertiaContext,
189 component: &str,
190 props: P,
191 ) -> Response {
192 let csrf = csrf_token().unwrap_or_default();
193 let shared = InertiaShared::new().csrf(csrf);
194
195 let http_response = ferro_inertia::Inertia::render_with_options(
196 ctx,
197 component,
198 props,
199 Some(&shared),
200 InertiaConfig::default(),
201 );
202
203 Ok(Self::convert_response(http_response))
204 }
205
206 /// Convert an InertiaHttpResponse to Ferro's HttpResponse.
207 fn convert_response(inertia_response: ferro_inertia::InertiaHttpResponse) -> HttpResponse {
208 let mut response = match inertia_response.content_type {
209 "application/json" => HttpResponse::text(inertia_response.body),
210 "text/html; charset=utf-8" => HttpResponse::text(inertia_response.body),
211 _ => HttpResponse::text(inertia_response.body),
212 };
213
214 response = response.status(inertia_response.status);
215 response = response.header("Content-Type", inertia_response.content_type);
216
217 for (name, value) in inertia_response.headers {
218 response = response.header(name, value);
219 }
220
221 response
222 }
223
224 /// Check if the current request is an Inertia XHR request.
225 pub fn is_inertia_request(req: &Request) -> bool {
226 req.is_inertia()
227 }
228
229 /// Get the current URL from the request.
230 pub fn current_url(req: &Request) -> String {
231 req.path().to_string()
232 }
233
234 /// Check for version mismatch and return 409 Conflict if needed.
235 ///
236 /// Call this in middleware to handle asset version changes.
237 pub fn check_version(
238 req: &Request,
239 current_version: &str,
240 redirect_url: &str,
241 ) -> Option<Response> {
242 ferro_inertia::Inertia::check_version(req, current_version, redirect_url)
243 .map(|http_response| Ok(Self::convert_response(http_response)))
244 }
245
246 /// Create an Inertia-aware redirect.
247 ///
248 /// This properly handles the Inertia protocol:
249 /// - For POST/PUT/PATCH/DELETE requests, uses 303 status to force GET
250 /// - Includes X-Inertia header for Inertia XHR requests
251 /// - Falls back to standard 302 for non-Inertia requests
252 ///
253 /// # Example
254 ///
255 /// ```rust,ignore
256 /// use ferro_rs::{Inertia, Request, Response};
257 ///
258 /// pub async fn login(req: Request) -> Response {
259 /// // ... validation and auth logic ...
260 /// Inertia::redirect(&req, "/dashboard")
261 /// }
262 /// ```
263 pub fn redirect(req: &Request, path: impl Into<String>) -> Response {
264 let url = path.into();
265 let is_inertia = req.is_inertia();
266 let is_post_like = matches!(req.method().as_str(), "POST" | "PUT" | "PATCH" | "DELETE");
267
268 if is_inertia {
269 // 303 See Other forces browser to GET the redirect location
270 let status = if is_post_like { 303 } else { 302 };
271 Ok(HttpResponse::new()
272 .status(status)
273 .header("X-Inertia", "true")
274 .header("Location", url))
275 } else {
276 // Standard redirect for non-Inertia requests
277 Ok(HttpResponse::new().status(302).header("Location", url))
278 }
279 }
280
281 /// Create an Inertia-aware redirect using saved context.
282 ///
283 /// Use when you've consumed the Request but need to redirect.
284 ///
285 /// # Example
286 ///
287 /// ```rust,ignore
288 /// use ferro_rs::{Inertia, Request, Response, SavedInertiaContext};
289 ///
290 /// pub async fn store(req: Request) -> Response {
291 /// let ctx = SavedInertiaContext::from(&req);
292 /// let form: CreateForm = req.input().await?;
293 ///
294 /// // ... create record ...
295 ///
296 /// Inertia::redirect_ctx(&ctx, "/items")
297 /// }
298 /// ```
299 pub fn redirect_ctx(ctx: &SavedInertiaContext, path: impl Into<String>) -> Response {
300 let url = path.into();
301 let is_inertia = ctx.headers.contains_key("X-Inertia");
302
303 // When using saved context, we assume POST-like (form submissions)
304 // because that's the common case for needing SavedInertiaContext
305 if is_inertia {
306 Ok(HttpResponse::new()
307 .status(303)
308 .header("X-Inertia", "true")
309 .header("Location", url))
310 } else {
311 Ok(HttpResponse::new().status(302).header("Location", url))
312 }
313 }
314}
315
316// Keep deprecated InertiaContext for backward compatibility during migration
317#[deprecated(
318 since = "0.2.0",
319 note = "Use Inertia::render() instead - thread-local storage is async-unsafe"
320)]
321pub struct InertiaContext;
322
323#[allow(deprecated)]
324impl InertiaContext {
325 #[deprecated(note = "Use Inertia::render() instead")]
326 pub fn set(_ctx: InertiaContextData) {
327 // No-op - kept for compilation compatibility during migration
328 }
329
330 #[deprecated(note = "Use Inertia::is_inertia_request(&req) instead")]
331 pub fn is_inertia_request() -> bool {
332 false
333 }
334
335 #[deprecated(note = "Use req.path() instead")]
336 pub fn current_path() -> String {
337 String::new()
338 }
339
340 #[deprecated(note = "No longer needed")]
341 pub fn clear() {
342 // No-op
343 }
344
345 #[deprecated(note = "Use req methods instead")]
346 pub fn get() -> Option<InertiaContextData> {
347 None
348 }
349}
350
351/// Legacy context data - kept for migration compatibility.
352#[deprecated(since = "0.2.0", note = "Use Request methods instead")]
353#[derive(Clone, Default)]
354pub struct InertiaContextData {
355 pub path: String,
356 pub is_inertia: bool,
357 pub version: Option<String>,
358}