1use std::cell::RefCell;
2use std::sync::Arc;
3pub use crate::core::blade::{BladeEngine, BladeContext};
4
5thread_local! {
6 static CURRENT_ERRORS: RefCell<serde_json::Value> = RefCell::new(serde_json::json!({}));
7 static CURRENT_FLASHES: RefCell<serde_json::Value> = RefCell::new(serde_json::json!([]));
8 static CURRENT_OLD: RefCell<serde_json::Value> = RefCell::new(serde_json::json!({}));
9 static CURRENT_LOCALE: RefCell<String> = RefCell::new("en".to_string());
10}
11
12#[derive(Clone)]
13pub struct ViewEngine {
14 inner: Arc<BladeEngine>,
15 pub lang: Option<Arc<crate::core::i18n::LangManager>>,
16}
17
18impl ViewEngine {
19 pub fn new(lang: Option<Arc<crate::core::i18n::LangManager>>) -> Self {
21 let engine = BladeEngine::new();
22 Self {
23 inner: Arc::new(engine),
24 lang,
25 }
26 }
27
28 pub fn render(&self, template_name: &str, context: &BladeContext) -> String {
30 self.inner.render(template_name, context)
31 }
32
33 pub fn blade_engine(&self) -> &Arc<BladeEngine> {
35 &self.inner
36 }
37
38 pub async fn render_with_session(
40 &self,
41 template_name: &str,
42 mut context: BladeContext,
43 session: &tower_sessions::Session,
44 locale: Option<String>,
45 ) -> String {
46 let current_locale = locale.unwrap_or_else(|| "en".to_string());
48 context.insert("locale", ¤t_locale);
49
50 if let Ok(Some(user)) = session.get::<crate::core::auth::AuthUser>("user").await {
52 context.insert("email", &user.email);
53 context.insert("user_id", &user.sub);
54 context.insert("role", &user.role);
55 } else {
56 context.insert("email", "");
57 context.insert("user_id", "");
58 context.insert("role", "");
59 }
60
61 let flash_manager = crate::core::session::FlashManager::new(session);
63 let flashes = flash_manager.consume().await;
64 context.insert("flashes", &flashes);
65
66 let errors = session
68 .get::<serde_json::Value>("_errors")
69 .await
70 .unwrap_or_default()
71 .unwrap_or_else(|| serde_json::json!({}));
72 context.insert("errors", &errors);
73
74 if !errors
75 .as_object()
76 .unwrap_or(&serde_json::Map::new())
77 .is_empty()
78 {
79 let _ = session.remove::<serde_json::Value>("_errors").await;
80 }
81
82 let old = session
84 .get::<serde_json::Value>("_old")
85 .await
86 .unwrap_or_default()
87 .unwrap_or_else(|| serde_json::json!({}));
88 context.insert("old", &old);
89
90 if !old
91 .as_object()
92 .unwrap_or(&serde_json::Map::new())
93 .is_empty()
94 {
95 let _ = session.remove::<serde_json::Value>("_old").await;
96 }
97
98 self.render(template_name, &context)
99 }
100}
101
102pub struct View;
104
105pub struct ViewBuilder {
106 template: String,
107 context: BladeContext,
108}
109
110impl View {
111 pub fn make(template: &str) -> ViewBuilder {
113 ViewBuilder::new(template)
114 }
115}
116
117impl ViewBuilder {
118 pub fn new(template: &str) -> Self {
119 Self {
120 template: template.to_string(),
121 context: BladeContext::new(),
122 }
123 }
124
125 pub fn with<T: serde::Serialize>(mut self, key: &str, value: T) -> Self {
127 self.context.insert(key, value);
128 self
129 }
130
131 pub async fn render<R: std::borrow::Borrow<crate::core::request::Request>>(mut self, req: R) -> ViewResponse {
135 let req = req.borrow();
136 if let Ok(token) = req.token.authenticity_token() {
138 self.context.insert("csrf_token", &token);
139 }
140
141 let locale = req
143 .extensions
144 .get::<crate::core::i18n::Locale>()
145 .map(|l| l.0.clone());
146
147 let html = req
148 .state
149 .view
150 .render_with_session(&self.template, self.context, &req.session, locale)
151 .await;
152 ViewResponse {
153 html,
154 token: Some(req.token.clone()),
155 }
156 }
157}
158
159pub struct ViewResponse {
160 pub html: String,
161 pub token: Option<axum_csrf::CsrfToken>,
162}
163
164impl axum::response::IntoResponse for ViewResponse {
165 fn into_response(self) -> axum::response::Response {
166 if let Some(token) = self.token {
167 (token, axum::response::Html(self.html)).into_response()
168 } else {
169 axum::response::Html(self.html).into_response()
170 }
171 }
172}