Skip to main content

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 = HttpResponse::new()
209            .header("Content-Type", inertia_response.content_type)
210            .set_body(inertia_response.body)
211            .status(inertia_response.status);
212
213        for (name, value) in inertia_response.headers {
214            response = response.header(name, value);
215        }
216
217        response
218    }
219
220    /// Check if the current request is an Inertia XHR request.
221    pub fn is_inertia_request(req: &Request) -> bool {
222        req.is_inertia()
223    }
224
225    /// Get the current URL from the request.
226    pub fn current_url(req: &Request) -> String {
227        req.path().to_string()
228    }
229
230    /// Check for version mismatch and return 409 Conflict if needed.
231    ///
232    /// Call this in middleware to handle asset version changes.
233    pub fn check_version(
234        req: &Request,
235        current_version: &str,
236        redirect_url: &str,
237    ) -> Option<Response> {
238        ferro_inertia::Inertia::check_version(req, current_version, redirect_url)
239            .map(|http_response| Ok(Self::convert_response(http_response)))
240    }
241
242    /// Create an Inertia-aware redirect.
243    ///
244    /// This properly handles the Inertia protocol:
245    /// - For POST/PUT/PATCH/DELETE requests, uses 303 status to force GET
246    /// - Includes X-Inertia header for Inertia XHR requests
247    /// - Falls back to standard 302 for non-Inertia requests
248    ///
249    /// # Example
250    ///
251    /// ```rust,ignore
252    /// use ferro_rs::{Inertia, Request, Response};
253    ///
254    /// pub async fn login(req: Request) -> Response {
255    ///     // ... validation and auth logic ...
256    ///     Inertia::redirect(&req, "/dashboard")
257    /// }
258    /// ```
259    pub fn redirect(req: &Request, path: impl Into<String>) -> Response {
260        let url = path.into();
261        let is_inertia = req.is_inertia();
262        let is_post_like = matches!(req.method().as_str(), "POST" | "PUT" | "PATCH" | "DELETE");
263
264        if is_inertia {
265            // 303 See Other forces browser to GET the redirect location
266            let status = if is_post_like { 303 } else { 302 };
267            Ok(HttpResponse::new()
268                .status(status)
269                .header("X-Inertia", "true")
270                .header("Location", url))
271        } else {
272            // Standard redirect for non-Inertia requests
273            Ok(HttpResponse::new().status(302).header("Location", url))
274        }
275    }
276
277    /// Create an Inertia-aware redirect using saved context.
278    ///
279    /// Use when you've consumed the Request but need to redirect.
280    ///
281    /// # Example
282    ///
283    /// ```rust,ignore
284    /// use ferro_rs::{Inertia, Request, Response, SavedInertiaContext};
285    ///
286    /// pub async fn store(req: Request) -> Response {
287    ///     let ctx = SavedInertiaContext::from(&req);
288    ///     let form: CreateForm = req.input().await?;
289    ///
290    ///     // ... create record ...
291    ///
292    ///     Inertia::redirect_ctx(&ctx, "/items")
293    /// }
294    /// ```
295    pub fn redirect_ctx(ctx: &SavedInertiaContext, path: impl Into<String>) -> Response {
296        let url = path.into();
297        let is_inertia = ctx.headers.contains_key("X-Inertia");
298
299        // When using saved context, we assume POST-like (form submissions)
300        // because that's the common case for needing SavedInertiaContext
301        if is_inertia {
302            Ok(HttpResponse::new()
303                .status(303)
304                .header("X-Inertia", "true")
305                .header("Location", url))
306        } else {
307            Ok(HttpResponse::new().status(302).header("Location", url))
308        }
309    }
310}
311
312// Keep deprecated InertiaContext for backward compatibility during migration
313#[deprecated(
314    since = "0.2.0",
315    note = "Use Inertia::render() instead - thread-local storage is async-unsafe"
316)]
317pub struct InertiaContext;
318
319#[allow(deprecated)]
320impl InertiaContext {
321    #[deprecated(note = "Use Inertia::render() instead")]
322    pub fn set(_ctx: InertiaContextData) {
323        // No-op - kept for compilation compatibility during migration
324    }
325
326    #[deprecated(note = "Use Inertia::is_inertia_request(&req) instead")]
327    pub fn is_inertia_request() -> bool {
328        false
329    }
330
331    #[deprecated(note = "Use req.path() instead")]
332    pub fn current_path() -> String {
333        String::new()
334    }
335
336    #[deprecated(note = "No longer needed")]
337    pub fn clear() {
338        // No-op
339    }
340
341    #[deprecated(note = "Use req methods instead")]
342    pub fn get() -> Option<InertiaContextData> {
343        None
344    }
345}
346
347/// Legacy context data - kept for migration compatibility.
348#[deprecated(since = "0.2.0", note = "Use Request methods instead")]
349#[derive(Clone, Default)]
350pub struct InertiaContextData {
351    pub path: String,
352    pub is_inertia: bool,
353    pub version: Option<String>,
354}