Skip to main content

renox_core/
view.rs

1use std::path::{Component as PathPart, Path, PathBuf};
2use std::sync::Arc;
3
4use axum::body::Body;
5use axum::extract::{Request, State};
6use axum::http::header::{ACCEPT, CONTENT_LENGTH, CONTENT_TYPE};
7use axum::http::{HeaderValue, StatusCode};
8use axum::middleware::Next;
9use axum::response::{IntoResponse, Redirect, Response};
10use minijinja::value::{Rest, merge_maps};
11use minijinja::{Environment, ErrorKind, Value, context};
12use minijinja_autoreload::AutoReloader;
13use serde::Serialize;
14
15use crate::auth::CurrentUser;
16use crate::error::{ErrorPage, reason};
17use crate::storage::Storage;
18use crate::validation::ValidationError;
19use crate::{AppState, Config, Error, Htmx, RouteTable, Session, assets};
20
21/// Templates that ship with Renox. An app overrides one by creating a file
22/// with the same name in its views directory.
23pub(crate) const BUILTIN: &[(&str, &str)] = &[
24    ("renox/error.html", include_str!("../views/error.html")),
25    (
26        "renox/pagination.html",
27        include_str!("../views/pagination.html"),
28    ),
29    (
30        "renox/auth/layout.html",
31        include_str!("../views/auth/layout.html"),
32    ),
33    (
34        "renox/auth/login.html",
35        include_str!("../views/auth/login.html"),
36    ),
37    (
38        "renox/auth/register.html",
39        include_str!("../views/auth/register.html"),
40    ),
41    (
42        "renox/auth/forgot-password.html",
43        include_str!("../views/auth/forgot-password.html"),
44    ),
45    (
46        "renox/auth/reset-password.html",
47        include_str!("../views/auth/reset-password.html"),
48    ),
49    (
50        "renox/auth/verify-email.html",
51        include_str!("../views/auth/verify-email.html"),
52    ),
53    (
54        "renox/mail/layout.html",
55        include_str!("../views/mail/layout.html"),
56    ),
57    (
58        "renox/mail/button.html",
59        include_str!("../views/mail/button.html"),
60    ),
61    ("renox/live.html", include_str!("../views/live.html")),
62    ("renox/ui.html", include_str!("../views/ui.html")),
63    (
64        "renox/import_report.html",
65        include_str!("../views/import_report.html"),
66    ),
67    ("renox/grid.html", include_str!("../views/grid.html")),
68    (
69        "renox/grid_print.html",
70        include_str!("../views/grid_print.html"),
71    ),
72    ("renox/debug.html", include_str!("../views/debug.html")),
73    (
74        "renox/custom_fields.html",
75        include_str!("../views/custom_fields.html"),
76    ),
77    (
78        "renox/transition_actions.html",
79        include_str!("../views/transition_actions.html"),
80    ),
81    (
82        "renox/notifications.html",
83        include_str!("../views/notifications.html"),
84    ),
85    (
86        "renox/queue/dashboard.html",
87        include_str!("../views/queue/dashboard.html"),
88    ),
89    (
90        "renox/mail/components.html",
91        include_str!("../views/mail/components.html"),
92    ),
93    (
94        "renox/auth/account.html",
95        include_str!("../views/auth/account.html"),
96    ),
97    (
98        "renox/auth/account_sections.html",
99        include_str!("../views/auth/account_sections.html"),
100    ),
101    (
102        "renox/auth/confirm-password.html",
103        include_str!("../views/auth/confirm-password.html"),
104    ),
105    (
106        "renox/mail/auth/reset-password.html",
107        include_str!("../views/mail/auth/reset-password.html"),
108    ),
109    (
110        "renox/mail/auth/reset-password.txt",
111        include_str!("../views/mail/auth/reset-password.txt"),
112    ),
113    (
114        "renox/mail/auth/verify-email.html",
115        include_str!("../views/mail/auth/verify-email.html"),
116    ),
117    (
118        "renox/mail/auth/verify-email.txt",
119        include_str!("../views/mail/auth/verify-email.txt"),
120    ),
121    (
122        "renox/auth/login-link.html",
123        include_str!("../views/auth/login-link.html"),
124    ),
125    (
126        "renox/auth/login-link-confirm.html",
127        include_str!("../views/auth/login-link-confirm.html"),
128    ),
129    (
130        "renox/auth/login-code.html",
131        include_str!("../views/auth/login-code.html"),
132    ),
133    (
134        "renox/auth/login-code-verify.html",
135        include_str!("../views/auth/login-code-verify.html"),
136    ),
137    (
138        "renox/mail/auth/login-link.html",
139        include_str!("../views/mail/auth/login-link.html"),
140    ),
141    (
142        "renox/mail/auth/login-link.txt",
143        include_str!("../views/mail/auth/login-link.txt"),
144    ),
145    (
146        "renox/mail/auth/login-code.html",
147        include_str!("../views/mail/auth/login-code.html"),
148    ),
149    (
150        "renox/mail/auth/login-code.txt",
151        include_str!("../views/mail/auth/login-code.txt"),
152    ),
153];
154
155/// The template engine (MiniJinja), reading from `VIEWS_PATH`.
156///
157/// Templates are reloaded when they change while `APP_DEBUG` is on.
158#[derive(Clone)]
159pub struct Views {
160    reloader: Arc<AutoReloader>,
161    /// `APP_DEBUG`: also warn about values hidden by imported macros.
162    debug: bool,
163    /// `VIEWS_PATH`, where the app's templates live.
164    dir: PathBuf,
165    /// Templates compiled into the binary, used instead of `dir` when given.
166    embedded: Option<&'static [(&'static str, &'static str)]>,
167    /// The plugins' components, next to the built-in ones.
168    plugin_components: Arc<Vec<crate::components::Contract>>,
169    /// The page structs registered with `App::view_data`, checked by `view:check`.
170    typed: Arc<Vec<TypedView>>,
171    /// The keys of `App::share` / `Registry::share` values, which every view gets.
172    shared: Arc<Vec<String>>,
173}
174
175/// A page struct registered with `App::view_data`: its template and fields.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub(crate) struct TypedView {
178    /// The struct's name, without its module path.
179    pub name: String,
180    /// `ViewData::TEMPLATE`.
181    pub template: &'static str,
182    /// `ViewData::FIELDS`.
183    pub fields: &'static [&'static str],
184}
185
186impl TypedView {
187    pub(crate) fn of<T: ViewData>() -> Self {
188        Self {
189            name: short_type_name(std::any::type_name::<T>()),
190            template: T::TEMPLATE,
191            fields: T::FIELDS,
192        }
193    }
194}
195
196/// `app::pages::Suppliers<'a>` → `Suppliers<'a>`: the last path segment, generics kept.
197fn short_type_name(full: &str) -> String {
198    let base = full.split('<').next().unwrap_or(full);
199    let start = base.rfind("::").map_or(0, |i| i + 2);
200    full[start..].to_owned()
201}
202
203/// The data of one page: a struct whose fields are its template's variables, so the
204/// compiler checks the handler's side and `view:check` the template's (the variables it
205/// uses that the struct lacks). Derive it with `#[derive(ViewData)]` and
206/// `#[view(template = "…")]`, render it with [`View::typed`], and register it with
207/// `App::view_data::<T>()` (`Registry::view_data` in a module) so `view:check` knows it.
208///
209/// ```
210/// # use renox::prelude::*;
211/// #[derive(serde::Serialize, ViewData)]
212/// #[view(template = "suppliers/index.html")]
213/// struct SupplierList {
214///     suppliers: Vec<String>,
215///     #[serde(rename = "total")]
216///     count: usize,
217/// }
218///
219/// assert_eq!(SupplierList::TEMPLATE, "suppliers/index.html");
220/// assert_eq!(SupplierList::FIELDS, ["suppliers", "total"]);
221///
222/// async fn index() -> View {
223///     View::typed(SupplierList { suppliers: vec!["Velo".into()], count: 1 })
224/// }
225/// let app = App::new().view_data::<SupplierList>();
226/// ```
227///
228/// The check reads what MiniJinja loads (after the `rx-*` components are compiled) and
229/// follows neither `extends` nor `include` nor imported macros: a variable used only in
230/// the layout or a partial isn't checked. Besides the struct's fields, a template may
231/// use the request globals (`auth`, `request`, `t`, `old`…), the environment's
232/// functions and globals, the `App::share` keys and the names it defines itself.
233pub trait ViewData: Serialize {
234    /// The template the page renders, relative to `VIEWS_PATH`.
235    const TEMPLATE: &'static str;
236    /// The names the template sees: the fields as serialized (`#[serde(rename)]` applied,
237    /// skipped fields left out).
238    const FIELDS: &'static [&'static str];
239}
240
241/// One template that does not compile, found by [`Views::check`].
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub(crate) struct ViewProblem {
244    /// The template's name, e.g. `products/index.html`.
245    pub template: String,
246    /// The line the error is on, when the compiler knows it.
247    pub line: Option<usize>,
248    /// What is wrong.
249    pub message: String,
250}
251
252impl std::fmt::Display for ViewProblem {
253    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
254        match self.line {
255            Some(line) => write!(f, "{}:{line}: {}", self.template, self.message),
256            None => write!(f, "{}: {}", self.template, self.message),
257        }
258    }
259}
260
261/// Every `*.html` and `*.txt` file under `dir`, as names relative to it with
262/// `/` separators. Dotfiles and dot directories are skipped.
263fn walk(dir: &Path, prefix: &str, out: &mut Vec<String>) {
264    let Ok(entries) = std::fs::read_dir(dir) else {
265        return;
266    };
267    for entry in entries.flatten() {
268        let file_name = entry.file_name().to_string_lossy().into_owned();
269        if file_name.starts_with('.') {
270            continue;
271        }
272        let name = if prefix.is_empty() {
273            file_name
274        } else {
275            format!("{prefix}/{file_name}")
276        };
277        let path = entry.path();
278        if path.is_dir() {
279            walk(&path, &name, out);
280        } else if name.ends_with(".html") || name.ends_with(".txt") {
281            out.push(name);
282        }
283    }
284}
285
286/// What an `App::share` function knows about the request being rendered.
287#[non_exhaustive]
288#[derive(Clone)]
289pub struct ViewContext {
290    /// The application state.
291    pub state: AppState,
292    /// The logged-in user, if any.
293    pub user: Option<Arc<crate::auth::User>>,
294    /// The request's language, e.g. `en`.
295    pub locale: String,
296    /// The request's path, e.g. `/products`.
297    pub path: String,
298    /// The request's session (absent only where no session middleware ran),
299    /// e.g. a guest's cart kept there:
300    ///
301    /// ```
302    /// # use renox::prelude::*;
303    /// # let _ =
304    /// App::new().share("cart_count", |ctx: renox::view::ViewContext| async move {
305    ///     let cart: Vec<i64> = ctx.session.and_then(|s| s.get("cart")).unwrap_or_default();
306    ///     Ok(cart.len())
307    /// })
308    /// # ;
309    /// ```
310    pub session: Option<crate::Session>,
311}
312
313pub(crate) type ShareFn = Arc<
314    dyn Fn(
315            ViewContext,
316        )
317            -> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Result<Value>> + Send>>
318        + Send
319        + Sync,
320>;
321
322pub(crate) fn share_fn<F, Fut, T>(compute: F) -> ShareFn
323where
324    F: Fn(ViewContext) -> Fut + Send + Sync + 'static,
325    Fut: std::future::Future<Output = crate::Result<T>> + Send + 'static,
326    T: Serialize,
327{
328    let compute = Arc::new(compute);
329    Arc::new(move |ctx| {
330        let compute = compute.clone();
331        Box::pin(async move { Ok(Value::from_serialize(compute(ctx).await?)) })
332    })
333}
334
335/// The names `{% from … import … %}` and `{% import … as … %}` bind in
336/// `source` that are also keys of one of `values` (the handler's context, the
337/// shared values): inside the template those names are the macros.
338fn hidden_by_imports(source: &str, values: &[&Value]) -> Vec<String> {
339    static FROM: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
340        regex::Regex::new(
341            r#"(?s)\{%[-+]?\s*from\s+(?:"[^"]*"|'[^']*'|\S+)\s+import\s+(.*?)\s*[-+]?%\}"#,
342        )
343        .expect("valid regex")
344    });
345    static IMPORT: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
346        regex::Regex::new(r#"\{%[-+]?\s*import\s+(?:"[^"]*"|'[^']*'|\S+)\s+as\s+(\w+)"#)
347            .expect("valid regex")
348    });
349    let mut names: Vec<String> = Vec::new();
350    for found in FROM.captures_iter(source) {
351        let list = found[1]
352            .trim_end_matches("without context")
353            .trim_end_matches("with context");
354        for item in list.split(',') {
355            let name = item.rsplit(" as ").next().unwrap_or(item).trim();
356            if !name.is_empty() {
357                names.push(name.to_owned());
358            }
359        }
360    }
361    names.extend(
362        IMPORT
363            .captures_iter(source)
364            .map(|found| found[1].to_owned()),
365    );
366    names.retain(|name| {
367        values
368            .iter()
369            .any(|value| value.get_attr(name).is_ok_and(|v| !v.is_undefined()))
370    });
371    names.sort();
372    names.dedup();
373    names
374}
375
376/// Adds functions, filters or globals to the template environment; see
377/// `App::templates`.
378pub(crate) type TemplateHook = Arc<dyn Fn(&mut Environment<'static>) + Send + Sync>;
379
380thread_local! {
381    /// The components known while template hooks run, for [`add_template`].
382    static HOOK_COMPONENTS: std::cell::RefCell<Option<Arc<Vec<crate::components::Contract>>>> =
383        const { std::cell::RefCell::new(None) };
384}
385
386/// Makes the registered components visible to [`add_template`] until dropped.
387struct HookScope(Option<Arc<Vec<crate::components::Contract>>>);
388
389impl HookScope {
390    fn enter(contracts: Arc<Vec<crate::components::Contract>>) -> Self {
391        Self(HOOK_COMPONENTS.with(|c| c.borrow_mut().replace(contracts)))
392    }
393}
394
395impl Drop for HookScope {
396    fn drop(&mut self) {
397        let previous = self.0.take();
398        HOOK_COMPONENTS.with(|c| *c.borrow_mut() = previous);
399    }
400}
401
402pub use crate::components::{Component, Prop};
403
404/// Adds the template `name` to `env` after compiling its component tags
405/// (`<rx-…>`, `rx-if`, `rx-for`), as the app's own views are. For modules and
406/// plugins, inside [`Registry::templates`](crate::Registry::templates), where
407/// the components other modules registered are known too. A mistake in the
408/// source is an error naming the template and line.
409///
410/// ```
411/// use renox::view::add_template;
412///
413/// let mut env = minijinja::Environment::new();
414/// add_template(&mut env, "hi.html", "<p>{{ name }}</p>").unwrap();
415/// ```
416pub fn add_template(
417    env: &mut Environment<'static>,
418    name: impl Into<String>,
419    source: impl Into<String>,
420) -> Result<(), minijinja::Error> {
421    let name = name.into();
422    let source = source.into();
423    let contracts = HOOK_COMPONENTS
424        .with(|c| c.borrow().clone())
425        .unwrap_or_else(|| Arc::new(crate::components::BUILTIN.to_vec()));
426    let catalog = crate::components::Catalog {
427        contracts: &contracts,
428        lookup: &|_| None,
429    };
430    let compiled = crate::components::compile(&name, &source, &catalog).map_err(|e| {
431        minijinja::Error::new(
432            ErrorKind::SyntaxError,
433            format!("{name}:{}: {}", e.line, e.message),
434        )
435    })?;
436    env.add_template_owned(name, compiled)
437}
438
439impl Views {
440    /// `embedded`: templates compiled into the binary, used instead of
441    /// `VIEWS_PATH` when given.
442    #[allow(clippy::too_many_arguments)]
443    pub(crate) fn new(
444        config: &Config,
445        routes: Arc<RouteTable>,
446        storage: Storage,
447        embedded: Option<&'static [(&'static str, &'static str)]>,
448        hooks: Arc<Vec<TemplateHook>>,
449        components: Arc<Vec<crate::components::Contract>>,
450        zone: crate::timezone::Zone,
451        versions: Arc<crate::embedded::AssetVersions>,
452    ) -> Self {
453        let plugin_components = components.clone();
454        let dir = config.views_path.clone();
455        let watch = config.debug && embedded.is_none() && dir.is_dir();
456        let debug = config.debug;
457        let currency = config.currency.clone();
458        let reloader = AutoReloader::new(move |notifier| {
459            let mut env = Environment::new();
460            env.set_formatter(format_value);
461            // While developing, printing a misspelled variable is an error
462            // instead of an empty string (`{% if x %}` on a missing one is fine).
463            if debug {
464                env.set_undefined_behavior(minijinja::UndefinedBehavior::SemiStrict);
465            }
466            let loader_dir = dir.clone();
467            let contracts: Arc<Vec<crate::components::Contract>> = Arc::new(
468                crate::components::BUILTIN
469                    .iter()
470                    .chain(components.iter())
471                    .copied()
472                    .collect(),
473            );
474            let loader_contracts = contracts.clone();
475            env.set_loader(move |name| {
476                let Some(src) = load(&loader_dir, embedded, name)? else {
477                    return Ok(None);
478                };
479                let lookup = |n: &str| load(&loader_dir, embedded, n).ok().flatten();
480                let catalog = crate::components::Catalog {
481                    contracts: &loader_contracts,
482                    lookup: &lookup,
483                };
484                crate::components::compile(name, &src, &catalog)
485                    .map(Some)
486                    .map_err(|e| {
487                        minijinja::Error::new(
488                            ErrorKind::SyntaxError,
489                            format!("{name}:{}: {}", e.line, e.message),
490                        )
491                    })
492            });
493
494            let routes = routes.clone();
495            env.add_function(
496                "route",
497                move |name: String, params: Rest<Value>| -> Result<Value, minijinja::Error> {
498                    // `route('products.index', page=2)`: named arguments are
499                    // the query string (`?page=2`).
500                    let (query, params): (Vec<&Value>, Vec<&Value>) =
501                        params.iter().partition(|p| p.is_kwargs());
502                    let params: Vec<&dyn std::fmt::Display> = params
503                        .iter()
504                        .map(|p| *p as &dyn std::fmt::Display)
505                        .collect();
506                    // Percent-encoded, so safe to use in HTML without escaping `/`.
507                    let mut url = routes.url(&name, &params).map_err(|err| {
508                        minijinja::Error::new(ErrorKind::InvalidOperation, err.to_string())
509                    })?;
510                    if let Some(kwargs) = query.first() {
511                        let mut pairs = form_urlencoded::Serializer::new(String::new());
512                        for key in kwargs.try_iter()? {
513                            let value = kwargs.get_item(&key)?;
514                            if value.is_none() || value.is_undefined() {
515                                continue;
516                            }
517                            pairs.append_pair(&key.to_string(), &value.to_string());
518                        }
519                        let pairs = pairs.finish();
520                        if !pairs.is_empty() {
521                            url.push(if url.contains('?') { '&' } else { '?' });
522                            url.push_str(&pairs.replace('&', "&amp;"));
523                        }
524                    }
525                    Ok(Value::from_safe_string(url))
526                },
527            );
528            // The current URL's query string with `page` set to `page`, for
529            // pagination links that keep filters such as `?q=coffee`.
530            env.add_function("page_url", |state: &minijinja::State, page: u32| -> Value {
531                let query = state
532                    .lookup("request")
533                    .and_then(|request| request.get_attr("query").ok())
534                    .and_then(|query| query.as_str().map(str::to_owned))
535                    .unwrap_or_default();
536                let mut url = form_urlencoded::Serializer::new(String::new());
537                for (key, value) in form_urlencoded::parse(query.as_bytes()) {
538                    if key != "page" {
539                        url.append_pair(&key, &value);
540                    }
541                }
542                url.append_pair("page", &page.to_string());
543                Value::from(format!("?{}", url.finish()))
544            });
545            // The current URL's query string with some keys set (or removed
546            // with `none`), and `page` dropped: `query_with(period="7d")`
547            // for filters that keep the others.
548            env.add_function(
549                "query_with",
550                |state: &minijinja::State,
551                 kwargs: minijinja::value::Kwargs|
552                 -> Result<Value, minijinja::Error> {
553                    let query = state
554                        .lookup("request")
555                        .and_then(|request| request.get_attr("query").ok())
556                        .and_then(|query| query.as_str().map(str::to_owned))
557                        .unwrap_or_default();
558                    let keys: Vec<String> = kwargs.args().map(str::to_owned).collect();
559                    let mut url = form_urlencoded::Serializer::new(String::new());
560                    for (key, value) in form_urlencoded::parse(query.as_bytes()) {
561                        if key != "page" && !keys.iter().any(|k| *k == key) {
562                            url.append_pair(&key, &value);
563                        }
564                    }
565                    for key in &keys {
566                        let value: Value = kwargs.get(key)?;
567                        if !value.is_none() && !value.is_undefined() {
568                            url.append_pair(key, &value.to_string());
569                        }
570                    }
571                    kwargs.assert_all_used()?;
572                    Ok(Value::from(format!("?{}", url.finish())))
573                },
574            );
575            // The current URL's query string as hidden inputs, without `page`
576            // and the keys named: `query_fields("period", "from", "to")`, so
577            // a GET form keeps the page's other filters.
578            env.add_function(
579                "query_fields",
580                |state: &minijinja::State, except: minijinja::value::Rest<String>| -> Value {
581                    let query = state
582                        .lookup("request")
583                        .and_then(|request| request.get_attr("query").ok())
584                        .and_then(|query| query.as_str().map(str::to_owned))
585                        .unwrap_or_default();
586                    let mut html = String::new();
587                    for (key, value) in form_urlencoded::parse(query.as_bytes()) {
588                        if key != "page" && !except.iter().any(|k| *k == key) {
589                            html.push_str(&format!(
590                                r#"<input type="hidden" name="{}" value="{}">"#,
591                                crate::toast::escape(&key),
592                                crate::toast::escape(&value)
593                            ));
594                        }
595                    }
596                    Value::from_safe_string(html)
597                },
598            );
599            env.add_function("method_field", |method: String| {
600                let method: String = method.chars().filter(char::is_ascii_alphabetic).collect();
601                Value::from_safe_string(format!(
602                    "<input type=\"hidden\" name=\"{}\" value=\"{}\">",
603                    crate::method::METHOD_FIELD,
604                    method.to_ascii_uppercase()
605                ))
606            });
607            // `/app.css?v=1a2b3c4d`: a new URL whenever the file changes.
608            let versions = versions.clone();
609            env.add_function("asset", move |path: String| {
610                let mut url = String::from("/");
611                crate::routing::encode(&mut url, path.trim_start_matches('/'), true);
612                if let Some(version) = versions.version(&path) {
613                    url.push_str("?v=");
614                    url.push_str(&version);
615                }
616                Value::from_safe_string(url)
617            });
618            let storage = storage.clone();
619            env.add_function("storage_url", move |key: String| {
620                Value::from_safe_string(storage.url(&key))
621            });
622            // The request's values for components: `old`, `error`, `t`, `can`,
623            // `csrf_field`, `auth`, `request`, `flash`… work inside imported
624            // macros too, not only in the rendered template.
625            for name in REQUEST_GLOBALS {
626                env.add_global(*name, Value::from_object(RequestGlobal(name)));
627            }
628            crate::view_stack::register(&mut env);
629            env.add_function("renox_ui", |kwargs: minijinja::value::Kwargs| {
630                let styles: Option<bool> = kwargs.get("styles")?;
631                kwargs.assert_all_used()?;
632                Ok::<_, minijinja::Error>(Value::from_safe_string(crate::assets::ui_tags(
633                    styles.unwrap_or(true),
634                )))
635            });
636            // The request's brand stylesheet (`App::theme`, `App::theme_for`):
637            // a `<link>` to the hashed route (`/_renox/theme/{hash}.css`, so
638            // nothing to escape), and nothing without a theme.
639            env.add_function("renox_theme", |state: &minijinja::State| {
640                let url = state
641                    .lookup(THEME_KEY)
642                    .and_then(|v| v.as_str().map(str::to_owned));
643                Value::from_safe_string(match url {
644                    Some(url) => format!("<link rel=\"stylesheet\" href=\"{url}\">"),
645                    None => String::new(),
646                })
647            });
648            env.add_function("renox_calendar", || {
649                Value::from_safe_string(crate::assets::calendar_tags())
650            });
651            // Until the live component script ships (#435): nothing.
652            env.add_function("renox_live", || {
653                Value::from_safe_string(crate::assets::live_tags())
654            });
655            env.add_function("renox_offline", || {
656                Value::from_safe_string(crate::assets::offline_tags())
657            });
658            // The kit's `icon(…)` macro: a Lucide icon as inline SVG.
659            env.add_function(
660                "renox_icon",
661                |name: String, kwargs: minijinja::value::Kwargs| {
662                    let size: Option<u32> = kwargs.get("size")?;
663                    let label: Option<String> = kwargs.get("label")?;
664                    let class: Option<String> = kwargs.get("class")?;
665                    kwargs.assert_all_used()?;
666                    Ok::<_, minijinja::Error>(Value::from_safe_string(crate::icons::svg(
667                        &name,
668                        size.unwrap_or(20),
669                        label.as_deref(),
670                        class.as_deref(),
671                    )))
672                },
673            );
674            env.add_function("renox_grid", || {
675                Value::from_safe_string(crate::assets::grid_tags())
676            });
677            env.add_function("sparkline", crate::view_filters::sparkline);
678            env.add_filter("number", crate::view_filters::number);
679            env.add_filter("date", crate::view_filters::date(zone));
680            env.add_filter("since", crate::view_filters::since(zone));
681            env.add_filter("money", crate::view_filters::money(currency.clone()));
682            env.add_filter("quantity", crate::view_filters::quantity);
683            env.add_filter("words", crate::view_filters::words);
684            env.add_filter("markdown", crate::view_filters::markdown);
685            env.add_function("chart", crate::chart::chart(currency.clone()));
686            env.add_function("class_names", crate::view_filters::class_names);
687            env.add_function("money_input", {
688                let app_currency = currency.clone();
689                move |code: Option<String>| {
690                    crate::view_filters::money_input(code.as_deref().unwrap_or(&app_currency))
691                }
692            });
693            env.add_function("quantity_input", crate::view_filters::quantity_input);
694            env.add_function("rx_attr", crate::view_filters::rx_attr);
695            env.add_function("rx_attr_value", crate::view_filters::attr_value);
696            // The app's own functions and filters (`App::templates`).
697            let _scope = HookScope::enter(contracts.clone());
698            for hook in hooks.iter() {
699                hook(&mut env);
700            }
701
702            if watch {
703                notifier.watch_path(&dir, true);
704            }
705            Ok(env)
706        });
707        Self {
708            reloader: Arc::new(reloader),
709            debug,
710            dir: config.views_path.clone(),
711            embedded,
712            plugin_components,
713            typed: Arc::new(Vec::new()),
714            shared: Arc::new(Vec::new()),
715        }
716    }
717
718    /// The name of every template: the app's files (or the embedded ones),
719    /// the built-in ones and those added to the environment, sorted.
720    pub(crate) fn names(&self) -> Vec<String> {
721        let mut names = Vec::new();
722        match self.embedded {
723            Some(files) => names.extend(files.iter().map(|(name, _)| (*name).to_owned())),
724            None => walk(&self.dir, "", &mut names),
725        }
726        names.extend(BUILTIN.iter().map(|(name, _)| (*name).to_owned()));
727        if let Ok(env) = self.reloader.acquire_env() {
728            names.extend(env.templates().map(|(name, _)| name.to_owned()));
729        }
730        names.sort();
731        names.dedup();
732        names
733    }
734
735    /// The editor data file (VS Code's `html.customData`): the built-in and plugin components
736    /// and the app's own (`components/*.html` files that declare `<rx-props>`).
737    pub(crate) fn custom_data(&self) -> serde_json::Value {
738        let contracts: Vec<crate::components::Contract> = crate::components::BUILTIN
739            .iter()
740            .chain(self.plugin_components.iter())
741            .copied()
742            .collect();
743        let sources: Vec<(String, String)> = self
744            .names()
745            .into_iter()
746            .filter(|n| n.starts_with("components/") && n.ends_with(".html"))
747            .filter_map(|n| {
748                let src = load(&self.dir, self.embedded, &n).ok().flatten()?;
749                src.contains("<rx-props").then_some((n, src))
750            })
751            .collect();
752        crate::components::custom_data_for(&contracts, &sources)
753    }
754
755    /// Compiles every template and returns those that fail, in name order.
756    pub(crate) fn check(&self, routes: &RouteTable) -> Vec<ViewProblem> {
757        let names = self.names();
758        let env = match self.reloader.acquire_env() {
759            Ok(env) => env,
760            Err(err) => {
761                return vec![ViewProblem {
762                    template: String::new(),
763                    line: None,
764                    message: err.to_string(),
765                }];
766            }
767        };
768        let mut problems = Vec::new();
769        let known: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
770        for name in &names {
771            match env.get_template(name) {
772                Err(err) => problems.push(problem(name, &err)),
773                // The framework's own templates show example names in their docs.
774                Ok(template) if !name.starts_with("renox/") => {
775                    check_route_names(name, template.source(), routes, &mut problems);
776                    check_includes(name, template.source(), &known, &mut problems);
777                }
778                Ok(_) => {}
779            }
780        }
781        for typed in self.typed.iter() {
782            self.check_typed(&env, typed, &mut problems);
783        }
784        problems
785    }
786
787    /// Records the page structs (`App::view_data`) and the shared keys, for [`Views::check`].
788    pub(crate) fn with_typed(mut self, typed: Vec<TypedView>, shared: Vec<String>) -> Self {
789        self.typed = Arc::new(typed);
790        self.shared = Arc::new(shared);
791        self
792    }
793
794    /// Reports the variables `typed`'s template uses that its struct doesn't have. The
795    /// template is the one MiniJinja loads, after the `rx-*` components are compiled.
796    fn check_typed(
797        &self,
798        env: &minijinja::Environment<'_>,
799        typed: &TypedView,
800        problems: &mut Vec<ViewProblem>,
801    ) {
802        let template = match env.get_template(typed.template) {
803            Ok(template) => template,
804            // A template that doesn't compile is already reported.
805            Err(err) if err.kind() != ErrorKind::TemplateNotFound => return,
806            Err(_) => {
807                problems.push(ViewProblem {
808                    template: typed.template.to_owned(),
809                    line: None,
810                    message: format!("not found, but {} renders it", typed.name),
811                });
812                return;
813            }
814        };
815        let globals: std::collections::HashSet<&str> =
816            env.globals().map(|(name, _)| name).collect();
817        let mut unknown: Vec<String> = template
818            .undeclared_variables(false)
819            .into_iter()
820            .filter(|var| {
821                !typed.fields.contains(&var.as_str())
822                    && !REQUEST_GLOBALS.contains(&var.as_str())
823                    && !globals.contains(var.as_str())
824                    && !self.shared.iter().any(|key| key == var)
825                    // Names the component compiler makes up (`__rx_slot_1`).
826                    && !var.starts_with("__rx")
827            })
828            .collect();
829        unknown.sort();
830        for var in unknown {
831            problems.push(ViewProblem {
832                template: typed.template.to_owned(),
833                line: first_use(template.source(), &var),
834                message: format!("\"{var}\" isn't a field of {}", typed.name),
835            });
836        }
837    }
838
839    /// The navigation menus the template `name` and the templates it reaches
840    /// (layouts, includes, imports) ask for with `nav("…")` or `menu="…"`.
841    /// `layout` is the page context's `layout`, for a page that extends a
842    /// layout named by a variable (`{% extends layout %}`, as Renox's own
843    /// signed-in pages do with the app's `layouts/app.html`, #88). Renox's
844    /// own templates are not read, unless the app replaces one with a file
845    /// of the same name: they get the menu name from the caller.
846    pub(crate) fn menus_used(&self, name: &str, layout: Option<&str>) -> crate::nav::MenusUsed {
847        let mut used = crate::nav::MenusUsed::default();
848        let Ok(env) = self.reloader.acquire_env() else {
849            return used;
850        };
851        let mut seen = std::collections::HashSet::new();
852        let mut queue = vec![name.to_owned()];
853        queue.extend(layout.map(str::to_owned));
854        while let Some(next) = queue.pop() {
855            if !seen.insert(next.clone())
856                || (BUILTIN.iter().any(|(n, _)| *n == next) && !self.app_has(&next))
857            {
858                continue;
859            }
860            let Ok(template) = env.get_template(&next) else {
861                continue;
862            };
863            let source = template.source();
864            used.scan(source);
865            // Every quoted `….html` name is a layout, an include or an
866            // import (or text that happens to match). Found from the end of
867            // the name, so an apostrophe in a comment cannot pair the quotes
868            // wrongly.
869            let mut from = 0;
870            while let Some(at) = source[from..].find(".html") {
871                let end = from + at + ".html".len();
872                from = end;
873                let Some(quote) = source[end..]
874                    .chars()
875                    .next()
876                    .filter(|c| matches!(c, '"' | '\''))
877                else {
878                    continue;
879                };
880                let line_start = source[..end].rfind('\n').map_or(0, |i| i + 1);
881                if let Some(open) = source[line_start..end].rfind(quote) {
882                    queue.push(source[line_start + open + 1..end].to_owned());
883                }
884            }
885        }
886        used
887    }
888
889    /// Whether the app has a template file of this name (its own, or one
890    /// that replaces a built-in).
891    fn app_has(&self, name: &str) -> bool {
892        match self.embedded {
893            Some(files) => files.iter().any(|(file, _)| *file == name),
894            None => safe_join(&self.dir, name).is_some_and(|path| path.is_file()),
895        }
896    }
897
898    /// Whether a template of this name exists (the app's or a built-in).
899    pub fn exists(&self, name: &str) -> bool {
900        self.reloader
901            .acquire_env()
902            .is_ok_and(|env| env.get_template(name).is_ok())
903    }
904
905    /// Renders a template with the given context and no request globals.
906    pub fn render(&self, name: &str, ctx: impl Serialize) -> anyhow::Result<String> {
907        let env = self.reloader.acquire_env()?;
908        Ok(env.get_template(name)?.render(ctx)?)
909    }
910
911    fn render_view(
912        &self,
913        view: &View,
914        shared: Value,
915        globals: Value,
916        htmx: &Htmx,
917    ) -> anyhow::Result<String> {
918        let env = self.reloader.acquire_env()?;
919        let template = env.get_template(&view.name)?;
920        // Components (macros imported from other templates) don't see this
921        // context; they reach the same values through `RequestGlobal`s.
922        let _current = CurrentGlobals::set(globals.clone());
923        // The last map wins: shared values, then the handler's, then Renox's.
924        // A value named like a macro the template imports is hidden by the
925        // macro, which fails far from the cause (#312): say so while debugging.
926        let hidden = if self.debug {
927            hidden_by_imports(template.source(), &[&shared, &view.ctx])
928        } else {
929            Vec::new()
930        };
931        for name in &hidden {
932            tracing::warn!(
933                template = %view.name,
934                name = %name,
935                "the view gets a value named like a macro the template imports; the macro hides it (rename one)"
936            );
937        }
938        // `nav('menu')` is a request global, but a page that already passes its
939        // own `nav` value keeps it (the global would otherwise hide it).
940        let own_nav = [&view.ctx, &shared]
941            .iter()
942            .find_map(|layer| layer.get_attr("nav").ok().filter(|n| !n.is_undefined()))
943            .map_or_else(
944                || Value::from_serialize(serde_json::Map::new()),
945                |nav| context! { nav },
946            );
947        let ctx = merge_maps([shared, view.ctx.clone(), globals, own_nav]);
948        let stacks = crate::view_stack::Scope::begin();
949        let rendered = match &view.fragment {
950            Some(block) if htmx.wants_fragment() => (|| {
951                let mut captured = template.render_captured_to(ctx, std::io::sink())?;
952                let mut out = captured.with_state_mut(|state| state.render_block(block))?;
953                for extra in &view.also {
954                    out.push_str(&captured.with_state_mut(|state| state.render_block(extra))?);
955                }
956                Ok::<_, minijinja::Error>(out)
957            })(),
958            _ => template.render(ctx),
959        };
960        let html = rendered.map_err(|err| {
961            let err = anyhow::Error::from(err);
962            match hidden.as_slice() {
963                [] => err,
964                names => err.context(format!(
965                    "{} imports a macro named like a value the view gets ({}): \
966                     inside the template the name is the macro; rename the value or import the macro `as` another name",
967                    view.name,
968                    names.join(", ")
969                )),
970            }
971        })?;
972        Ok(stacks.finish(html))
973    }
974
975    /// The error page: the app's `errors/{status}.html`, else its
976    /// `errors/default.html`, else Renox's. With `globals` (a request's), an
977    /// app's page can extend its layout; a page that fails falls back to
978    /// Renox's, so an error in the layout doesn't hide the first error.
979    fn render_error(
980        &self,
981        page: &ErrorPage,
982        debug: bool,
983        request: &str,
984        globals: Option<Value>,
985    ) -> anyhow::Result<String> {
986        let env = self.reloader.acquire_env()?;
987        let ctx = context! {
988            status => page.status.as_u16(),
989            reason => reason(page.status),
990            detail => page.shown_detail(debug),
991            // Only while developing: what was asked, and where a template failed.
992            debug => debug,
993            request_line => debug.then_some(request),
994            template => page.template.as_deref().filter(|_| debug),
995        };
996        for name in [
997            format!("errors/{}.html", page.status.as_u16()),
998            "errors/default.html".to_owned(),
999        ] {
1000            let template = match env.get_template(&name) {
1001                Ok(template) => template,
1002                Err(err) if err.kind() == ErrorKind::TemplateNotFound => continue,
1003                // One that doesn't parse fails like one that doesn't render.
1004                Err(err) => {
1005                    tracing::error!(error = ?err, template = %name, "the error page failed; showing Renox's");
1006                    break;
1007                }
1008            };
1009            let rendered = match &globals {
1010                Some(globals) => {
1011                    let _current = CurrentGlobals::set(globals.clone());
1012                    let stacks = crate::view_stack::Scope::begin();
1013                    template
1014                        .render(merge_maps([globals.clone(), ctx.clone()]))
1015                        .map(|html| stacks.finish(html))
1016                }
1017                None => template.render(ctx.clone()),
1018            };
1019            match rendered {
1020                Ok(html) => return Ok(html),
1021                Err(err) => {
1022                    tracing::error!(error = ?err, template = %name, "the error page failed; showing Renox's");
1023                    break;
1024                }
1025            }
1026        }
1027        Ok(env.get_template("renox/error.html")?.render(ctx)?)
1028    }
1029}
1030
1031/// The template a response was rendered from.
1032#[derive(Debug, Clone)]
1033pub(crate) struct RenderedView(pub String);
1034
1035/// The globals Renox gives each rendered page (see `globals`), which
1036/// components reach through the environment.
1037pub(crate) const REQUEST_GLOBALS: &[&str] = &[
1038    "app",
1039    "auth",
1040    "t",
1041    "can",
1042    "request",
1043    "route_is",
1044    "nav",
1045    "csrf_token",
1046    "csrf_field",
1047    "flash",
1048    "errors",
1049    "errors_in",
1050    "error",
1051    "old",
1052    "has_old",
1053    "renox_head",
1054    "renox_pwa",
1055    "seo",
1056    "csp_nonce",
1057    "toasts",
1058    "once",
1059];
1060
1061thread_local! {
1062    /// The globals of the page being rendered on this thread.
1063    static CURRENT: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
1064}
1065
1066/// Makes `globals` the current page's while alive (rendering is synchronous).
1067struct CurrentGlobals(Option<Value>);
1068
1069impl CurrentGlobals {
1070    fn set(globals: Value) -> Self {
1071        Self(CURRENT.with(|c| c.borrow_mut().replace(globals)))
1072    }
1073}
1074
1075impl Drop for CurrentGlobals {
1076    fn drop(&mut self) {
1077        let previous = self.0.take();
1078        CURRENT.with(|c| *c.borrow_mut() = previous);
1079    }
1080}
1081
1082/// A request global as seen from the environment: forwards to the value of
1083/// the page being rendered, so an imported macro gets the same `old()`,
1084/// `auth`, `t()`… as the template that called it.
1085#[derive(Debug)]
1086struct RequestGlobal(&'static str);
1087
1088impl RequestGlobal {
1089    fn current(&self) -> Option<Value> {
1090        CURRENT
1091            .with(|c| c.borrow().clone())
1092            .and_then(|globals| globals.get_attr(self.0).ok())
1093            .filter(|v| !v.is_undefined())
1094    }
1095}
1096
1097impl minijinja::value::Object for RequestGlobal {
1098    fn repr(self: &Arc<Self>) -> minijinja::value::ObjectRepr {
1099        minijinja::value::ObjectRepr::Map
1100    }
1101
1102    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
1103        self.current()?
1104            .get_item(key)
1105            .ok()
1106            .filter(|v| !v.is_undefined())
1107    }
1108
1109    fn enumerate(self: &Arc<Self>) -> minijinja::value::Enumerator {
1110        match self
1111            .current()
1112            .and_then(|v| v.try_iter().ok().map(|keys| keys.collect::<Vec<_>>()))
1113        {
1114            Some(keys)
1115                if self
1116                    .current()
1117                    .is_some_and(|v| v.kind() == minijinja::value::ValueKind::Map) =>
1118            {
1119                minijinja::value::Enumerator::Values(keys)
1120            }
1121            _ => minijinja::value::Enumerator::Empty,
1122        }
1123    }
1124
1125    fn is_true(self: &Arc<Self>) -> bool {
1126        self.current().is_some_and(|v| v.is_true())
1127    }
1128
1129    fn call(
1130        self: &Arc<Self>,
1131        state: &minijinja::State<'_, '_>,
1132        args: &[Value],
1133    ) -> Result<Value, minijinja::Error> {
1134        match self.current() {
1135            Some(value) => value.call(state, args),
1136            None => Err(minijinja::Error::new(
1137                ErrorKind::InvalidOperation,
1138                format!("`{}` is only available while rendering a page", self.0),
1139            )),
1140        }
1141    }
1142
1143    fn render(self: &Arc<Self>, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1144        match self.current() {
1145            Some(value) => std::fmt::Display::fmt(&value, f),
1146            None => Ok(()),
1147        }
1148    }
1149}
1150
1151/// Like MiniJinja's default formatter, but HTML escaping leaves `/` alone:
1152/// escaping `& < > " '` is enough for text and quoted attributes, and URLs
1153/// (links in pages and mail) stay readable.
1154fn format_value(
1155    out: &mut minijinja::Output,
1156    state: &minijinja::State,
1157    value: &Value,
1158) -> Result<(), minijinja::Error> {
1159    use std::fmt::Write;
1160    if let (minijinja::AutoEscape::Html, false, Some(text)) =
1161        (state.auto_escape(), value.is_safe(), value.as_str())
1162    {
1163        for c in text.chars() {
1164            let written = match c {
1165                '&' => out.write_str("&amp;"),
1166                '<' => out.write_str("&lt;"),
1167                '>' => out.write_str("&gt;"),
1168                '"' => out.write_str("&quot;"),
1169                '\'' => out.write_str("&#39;"),
1170                c => out.write_char(c),
1171            };
1172            written.map_err(|_| {
1173                minijinja::Error::new(ErrorKind::WriteFailure, "could not write output")
1174            })?;
1175        }
1176        return Ok(());
1177    }
1178    minijinja::escape_formatter(out, state, value)
1179}
1180
1181fn load(
1182    dir: &Path,
1183    embedded: Option<&'static [(&'static str, &'static str)]>,
1184    name: &str,
1185) -> Result<Option<String>, minijinja::Error> {
1186    if let Some(files) = embedded {
1187        if let Some((_, source)) = files.iter().find(|(file, _)| *file == name) {
1188            return Ok(Some((*source).to_owned()));
1189        }
1190    } else if let Some(path) = safe_join(dir, name) {
1191        match std::fs::read_to_string(&path) {
1192            Ok(source) => return Ok(Some(source)),
1193            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
1194            Err(err) => {
1195                return Err(minijinja::Error::new(
1196                    ErrorKind::InvalidOperation,
1197                    format!("could not read template {}", path.display()),
1198                )
1199                .with_source(err));
1200            }
1201        }
1202    }
1203    Ok(BUILTIN
1204        .iter()
1205        .find(|(builtin, _)| *builtin == name)
1206        .map(|(_, source)| (*source).to_owned()))
1207}
1208
1209/// Reports every literal `route('name')` in the compiled `source` that no route has.
1210fn check_route_names(
1211    template: &str,
1212    source: &str,
1213    routes: &RouteTable,
1214    problems: &mut Vec<ViewProblem>,
1215) {
1216    static ROUTE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1217        regex::Regex::new(r#"\broute\(\s*["']([^"']+)["']"#).expect("valid regex")
1218    });
1219    for caps in ROUTE.captures_iter(source) {
1220        let name = &caps[1];
1221        if routes.path(name).is_some() {
1222            continue;
1223        }
1224        let hint = crate::components::suggest::did_you_mean(name, routes.names())
1225            .map(|x| format!("; did you mean \"{x}\"?"))
1226            .unwrap_or_default();
1227        let offset = caps.get(0).map_or(0, |m| m.start());
1228        problems.push(ViewProblem {
1229            template: template.to_owned(),
1230            line: Some(source[..offset].matches('\n').count() + 1),
1231            message: format!("unknown route \"{name}\"{hint}"),
1232        });
1233    }
1234}
1235
1236/// Reports `{% include "name" %}` (what `<rx-include template="name"/>` compiles to) of a template
1237/// that does not exist. An include with `ignore missing`, or whose name is worked out at run
1238/// time, is not checked.
1239fn check_includes(
1240    template: &str,
1241    source: &str,
1242    known: &std::collections::HashSet<&str>,
1243    problems: &mut Vec<ViewProblem>,
1244) {
1245    static INCLUDE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1246        regex::Regex::new(r#"\{%-?\s*include\s+["']([^"']+)["']\s*-?%\}"#).expect("valid regex")
1247    });
1248    for caps in INCLUDE.captures_iter(source) {
1249        let name = &caps[1];
1250        if known.contains(name) {
1251            continue;
1252        }
1253        let hint = crate::components::suggest::did_you_mean(name, known.iter().copied())
1254            .map(|x| format!("; did you mean \"{x}\"?"))
1255            .unwrap_or_default();
1256        let offset = caps.get(0).map_or(0, |m| m.start());
1257        problems.push(ViewProblem {
1258            template: template.to_owned(),
1259            line: Some(source[..offset].matches('\n').count() + 1),
1260            message: format!(
1261                "<rx-include> (or include) names a template that does not exist: \"{name}\"{hint}"
1262            ),
1263        });
1264    }
1265}
1266
1267/// A [`ViewProblem`] from a compile error. The component compiler's details
1268/// already start with `name:line: `, which is taken out of the message.
1269fn problem(name: &str, err: &minijinja::Error) -> ViewProblem {
1270    let detail = err.detail().unwrap_or("could not be compiled");
1271    if let Some(rest) = detail.strip_prefix(name).and_then(|r| r.strip_prefix(':'))
1272        && let Some((line, message)) = rest.split_once(": ")
1273        && let Ok(line) = line.parse::<usize>()
1274    {
1275        return ViewProblem {
1276            template: name.to_owned(),
1277            line: Some(line),
1278            message: message.to_owned(),
1279        };
1280    }
1281    ViewProblem {
1282        template: name.to_owned(),
1283        line: err.line(),
1284        message: detail.to_owned(),
1285    }
1286}
1287
1288fn safe_join(dir: &Path, name: &str) -> Option<PathBuf> {
1289    let mut path = dir.to_path_buf();
1290    for component in Path::new(name).components() {
1291        match component {
1292            PathPart::Normal(part) => path.push(part),
1293            _ => return None,
1294        }
1295    }
1296    Some(path)
1297}
1298
1299/// A template response, rendered by Renox with the request's globals:
1300/// `app` (with the request's `app.locale`), `request`, `auth` (`auth.check`,
1301/// `auth.user`), `t()`, `can()`, `flash`, `errors`, `error()`, `old()`,
1302/// `csrf_token`, `csrf_field()` and `renox_head()`.
1303///
1304/// ```
1305/// # use renox::prelude::*;
1306/// # let list: Vec<String> = Vec::new();
1307/// # let _ = move || {
1308/// async fn index() -> View {
1309/// #   let list: Vec<String> = Vec::new();
1310///     view("products/index.html", context! { products => list }).fragment("list")
1311/// }
1312/// # };
1313/// ```
1314#[derive(Clone)]
1315pub struct View {
1316    name: String,
1317    ctx: Value,
1318    fragment: Option<String>,
1319    /// More blocks sent with the fragment, for out-of-band swaps.
1320    also: Vec<String>,
1321    status: StatusCode,
1322}
1323
1324/// The line of the first `{{ … }}` or `{% … %}` tag that names `var`, if any.
1325fn first_use(source: &str, var: &str) -> Option<usize> {
1326    let word = regex::Regex::new(&format!(r"\b{}\b", regex::escape(var))).ok()?;
1327    let mut rest = source;
1328    let mut offset = 0;
1329    while let Some(open) = rest.find('{') {
1330        let after = &rest[open..];
1331        let close = match after.get(..2) {
1332            Some("{{") => "}}",
1333            Some("{%") => "%}",
1334            _ => {
1335                offset += open + 1;
1336                rest = &rest[open + 1..];
1337                continue;
1338            }
1339        };
1340        let end = after.find(close).map_or(after.len(), |i| i + 2);
1341        if word.is_match(&after[..end]) {
1342            return Some(source[..offset + open].matches('\n').count() + 1);
1343        }
1344        offset += open + end;
1345        rest = &rest[open + end..];
1346    }
1347    None
1348}
1349
1350/// Renders `name` from the views directory with `ctx` (anything serializable,
1351/// usually `context! { ... }`).
1352pub fn view(name: impl Into<String>, ctx: impl Serialize) -> View {
1353    View {
1354        name: name.into(),
1355        ctx: Value::from_serialize(ctx),
1356        fragment: None,
1357        also: Vec::new(),
1358        status: StatusCode::OK,
1359    }
1360}
1361
1362impl View {
1363    /// Renders a page struct in its own template ([`ViewData::TEMPLATE`]): the typed
1364    /// form of [`view`]. Register the struct with `App::view_data::<T>()` so
1365    /// `view:check` reports the template's variables the struct lacks.
1366    ///
1367    /// ```
1368    /// # use renox::prelude::*;
1369    /// #[derive(serde::Serialize, ViewData)]
1370    /// #[view(template = "orders/show.html")]
1371    /// struct OrderPage {
1372    ///     number: String,
1373    /// }
1374    ///
1375    /// async fn show() -> View {
1376    ///     View::typed(OrderPage { number: "A-1".into() }).fragment("summary")
1377    /// }
1378    /// ```
1379    pub fn typed<T: ViewData>(page: T) -> View {
1380        view(T::TEMPLATE, page)
1381    }
1382
1383    /// For HTMX requests (except `hx-boost`), render only this `{% block %}`.
1384    pub fn fragment(mut self, block: impl Into<String>) -> Self {
1385        self.fragment = Some(block.into());
1386        self
1387    }
1388
1389    /// For the same HTMX requests, also render `block` after the fragment,
1390    /// to update other parts of the page in one response: give the block's
1391    /// root element an `id` and `hx-swap-oob="true"` and htmx swaps it into
1392    /// the element with that id.
1393    ///
1394    /// ```html
1395    /// {% block row %}<tr id="order-{{ order.id }}">…</tr>{% endblock %}
1396    /// {% block count %}<span id="order-count" hx-swap-oob="true">{{ count }}</span>{% endblock %}
1397    /// ```
1398    ///
1399    /// `view("orders/index.html", ctx).fragment("row").also("count")`
1400    pub fn also(mut self, block: impl Into<String>) -> Self {
1401        self.also.push(block.into());
1402        self
1403    }
1404
1405    /// The response status (200 by default).
1406    pub fn status(mut self, status: StatusCode) -> Self {
1407        self.status = status;
1408        self
1409    }
1410}
1411
1412impl IntoResponse for View {
1413    fn into_response(self) -> Response {
1414        let mut res = self.status.into_response();
1415        res.extensions_mut().insert(self);
1416        res
1417    }
1418}
1419
1420/// Renders `View` and error responses once the handler has returned, and
1421/// turns validation errors into a redirect back for regular form posts.
1422pub(crate) async fn middleware(
1423    State(state): State<AppState>,
1424    req: Request,
1425    next: Next,
1426) -> Response {
1427    let session = req.extensions().get::<Session>().cloned();
1428    let current_user = req.extensions().get::<CurrentUser>().cloned();
1429    let htmx = Htmx::from_headers(req.headers());
1430    let method = req.method().clone();
1431    let path = req.uri().path().to_owned();
1432    let query = req.uri().query().unwrap_or_default().to_owned();
1433    let route = crate::routing::CurrentRoute::of(req.method(), req.extensions(), &state)
1434        .name()
1435        .map(str::to_owned);
1436    let host = crate::domain::host(&req).unwrap_or_default();
1437    let nonce = req
1438        .extensions()
1439        .get::<crate::security::CspNonce>()
1440        .map(|n| n.0.clone())
1441        .unwrap_or_default();
1442    let (wants_json, referer) = {
1443        let header = |name| req.headers().get(name).and_then(|v| v.to_str().ok());
1444        let wants_json = header(ACCEPT).is_some_and(|v| v.contains("application/json"))
1445            || header(CONTENT_TYPE).is_some_and(|v| v.starts_with("application/json"));
1446        // Back to the form's page, but never to another site.
1447        (wants_json, crate::htmx::same_site_referer(req.headers()))
1448    };
1449
1450    let request_line = if query.is_empty() {
1451        format!("{method} {path}")
1452    } else {
1453        format!("{method} {path}?{query}")
1454    };
1455    let mut res = next.run(req).await;
1456    // A layer may have switched the language (`RequestLocale::switch`).
1457    let locale = crate::i18n::current_locale(&state);
1458
1459    if let Some(crate::toast::PendingToasts(toasts)) =
1460        res.extensions_mut().remove::<crate::toast::PendingToasts>()
1461    {
1462        // An htmx swap shows them now; a page, an htmx redirect or refresh
1463        // on the next page, from the session (the reload would lose them).
1464        if htmx.request
1465            && !res.headers().contains_key("hx-redirect")
1466            && !res.headers().contains_key("hx-refresh")
1467        {
1468            crate::htmx::add_trigger(
1469                &mut res,
1470                crate::toast::EVENT,
1471                serde_json::json!({ "toasts": toasts }),
1472            );
1473        } else if let Some(session) = &session {
1474            let mut waiting: Vec<crate::Toast> =
1475                session.get(crate::toast::SESSION_KEY).unwrap_or_default();
1476            waiting.extend(toasts);
1477            if let Err(err) = session.put(crate::toast::SESSION_KEY, &waiting) {
1478                return err.into_response();
1479            }
1480        }
1481    }
1482
1483    if let Some(failed) = res.extensions_mut().remove::<ValidationError>() {
1484        if htmx.request || wants_json {
1485            return res;
1486        }
1487        if let Some(session) = &session {
1488            let bag = failed.bag().map(str::to_owned);
1489            // A `ValidationError` made after `Valid` (a model hook, the
1490            // handler) carries no input: refill with what `Valid` read.
1491            let input = if failed.input.is_empty() {
1492                crate::context::get::<crate::validation::extract::SubmittedInput>()
1493                    .map(|submitted| submitted.0)
1494                    .unwrap_or_default()
1495            } else {
1496                failed.input
1497            };
1498            let flashed = match &bag {
1499                Some(bag) => session.flash_errors_in(bag, &failed.errors),
1500                None => session.flash_errors(&failed.errors),
1501            }
1502            .and_then(|()| session.flash_input(&input));
1503            if let Err(err) = flashed {
1504                return err.into_response();
1505            }
1506        }
1507        return Redirect::to(referer.as_deref().unwrap_or("/")).into_response();
1508    }
1509
1510    // Analytics events: with an htmx swap, in its HX-Trigger; with a page,
1511    // in its head (below); otherwise they wait for the next page.
1512    if let Some(session) = &session
1513        && crate::analytics::has_pending(session)
1514        && htmx.request
1515        && crate::analytics::deliverable_by_htmx(&res)
1516    {
1517        crate::analytics::add_trigger(&mut res, crate::analytics::take(session));
1518    }
1519
1520    if let Some(view) = res.extensions_mut().remove::<View>() {
1521        let mut shared = std::collections::BTreeMap::new();
1522        for (key, compute) in state.shares.iter() {
1523            let ctx = ViewContext {
1524                state: state.clone(),
1525                user: current_user.as_ref().and_then(|c| c.user.clone()),
1526                locale: locale.clone(),
1527                path: path.clone(),
1528                session: session.clone(),
1529            };
1530            match compute(ctx).await {
1531                Ok(value) => {
1532                    shared.insert(key.clone(), value);
1533                }
1534                Err(err) => {
1535                    let err = match err {
1536                        Error::Internal(err) => err,
1537                        other => anyhow::anyhow!("{other:?}"),
1538                    };
1539                    // Shown like any error: the error page, with the detail
1540                    // while debugging.
1541                    let mut failed =
1542                        Error::Internal(err.context(format!("sharing `{key}` with views")))
1543                            .into_response();
1544                    return match failed.extensions_mut().remove::<ErrorPage>() {
1545                        Some(page) => error_response(
1546                            &state,
1547                            page,
1548                            failed,
1549                            wants_json,
1550                            &htmx,
1551                            &request_line,
1552                            None,
1553                        ),
1554                        None => failed,
1555                    };
1556                }
1557            }
1558        }
1559        add_theme(
1560            &mut shared,
1561            &state,
1562            &host,
1563            &path,
1564            &locale,
1565            current_user.as_ref(),
1566        )
1567        .await;
1568        let events = match &session {
1569            Some(session) if !htmx.request => crate::analytics::take(session),
1570            _ => Vec::new(),
1571        };
1572        let menus = request_menus(
1573            &state,
1574            current_user.as_ref(),
1575            &locale,
1576            route.as_deref(),
1577            &path,
1578            state.views.menus_used(
1579                &view.name,
1580                view.ctx
1581                    .get_attr("layout")
1582                    .ok()
1583                    .as_ref()
1584                    .and_then(Value::as_str),
1585            ),
1586        )
1587        .await;
1588        let globals = globals(
1589            &state,
1590            session.as_ref(),
1591            current_user.clone(),
1592            &htmx,
1593            &Requested {
1594                path: &path,
1595                query: &query,
1596                route: route.as_deref(),
1597                nonce: &nonce,
1598                events: &events,
1599            },
1600            &locale,
1601            menus,
1602        );
1603        return match state
1604            .views
1605            .render_view(&view, Value::from_serialize(&shared), globals, &htmx)
1606        {
1607            Ok(html) => {
1608                let mut page = with_html(res, html);
1609                // For `TestResponse::assert_view`.
1610                page.extensions_mut()
1611                    .insert(RenderedView(view.name.clone()));
1612                page
1613            }
1614            Err(err) => {
1615                let mut failed = Error::Internal(err.context(format!("rendering {}", view.name)))
1616                    .into_response();
1617                match failed.extensions_mut().remove::<ErrorPage>() {
1618                    Some(page) => {
1619                        error_response(&state, page, failed, wants_json, &htmx, &request_line, None)
1620                    }
1621                    None => failed,
1622                }
1623            }
1624        };
1625    }
1626
1627    if let Some(page) = res.extensions_mut().remove::<ErrorPage>() {
1628        // The app's error pages may extend its layout: give them what pages
1629        // get, the values `App::share`s included (a layout's cart count).
1630        let globals = if !wants_json || htmx.request {
1631            let mut shared = std::collections::BTreeMap::new();
1632            for (key, compute) in state.shares.iter() {
1633                let ctx = ViewContext {
1634                    state: state.clone(),
1635                    user: current_user.as_ref().and_then(|c| c.user.clone()),
1636                    locale: locale.clone(),
1637                    path: path.clone(),
1638                    session: session.clone(),
1639                };
1640                // A share that fails here only leaves its value out: the page
1641                // is about another error, which it mustn't hide.
1642                match compute(ctx).await {
1643                    Ok(value) => {
1644                        shared.insert(key.clone(), value);
1645                    }
1646                    Err(err) => {
1647                        tracing::warn!(error = ?err, key = %key, "a shared view value failed on an error page")
1648                    }
1649                }
1650            }
1651            add_theme(
1652                &mut shared,
1653                &state,
1654                &host,
1655                &path,
1656                &locale,
1657                current_user.as_ref(),
1658            )
1659            .await;
1660            // The app's error page may extend a layout with a menu: build
1661            // every menu, as the page that extends is not known here.
1662            let menus = request_menus(
1663                &state,
1664                current_user.as_ref(),
1665                &locale,
1666                route.as_deref(),
1667                &path,
1668                crate::nav::MenusUsed {
1669                    names: Vec::new(),
1670                    dynamic: true,
1671                },
1672            )
1673            .await;
1674            let page_globals = globals(
1675                &state,
1676                session.as_ref(),
1677                current_user,
1678                &htmx,
1679                &Requested {
1680                    path: &path,
1681                    query: &query,
1682                    route: route.as_deref(),
1683                    nonce: &nonce,
1684                    events: &[],
1685                },
1686                &locale,
1687                menus,
1688            );
1689            Some(merge_maps([page_globals, Value::from_serialize(&shared)]))
1690        } else {
1691            None
1692        };
1693        return error_response(&state, page, res, wants_json, &htmx, &request_line, globals);
1694    }
1695    res
1696}
1697
1698/// The key a request's brand stylesheet URL is shared under, for `renox_theme()` (not named like the function: a value would hide it).
1699pub(crate) const THEME_KEY: &str = "renox_theme_url";
1700
1701/// Resolves the request's brand (`App::theme`, `App::theme_for`) and shares
1702/// the URL of its stylesheet with the views; nothing is shared when the app
1703/// has no theme for this request.
1704async fn add_theme(
1705    shared: &mut std::collections::BTreeMap<String, Value>,
1706    state: &AppState,
1707    host: &str,
1708    path: &str,
1709    locale: &str,
1710    user: Option<&CurrentUser>,
1711) {
1712    if !state.themes.is_set() {
1713        return;
1714    }
1715    let url = state
1716        .themes
1717        .resolve(crate::theme::ThemeRequest {
1718            host: host.to_owned(),
1719            path: path.to_owned(),
1720            locale: locale.to_owned(),
1721            user: user.and_then(|c| c.user.clone()),
1722            state: state.clone(),
1723        })
1724        .await;
1725    if let Some(url) = url {
1726        shared.insert(THEME_KEY.to_owned(), Value::from(url));
1727    }
1728}
1729
1730/// The error page (or JSON for API clients) for `page`.
1731fn error_response(
1732    state: &AppState,
1733    page: ErrorPage,
1734    res: Response,
1735    wants_json: bool,
1736    htmx: &Htmx,
1737    request_line: &str,
1738    globals: Option<Value>,
1739) -> Response {
1740    let debug = state.config.debug;
1741    if wants_json && !htmx.request {
1742        // Keep what the error response carried (`Retry-After` on a 429, …).
1743        let mut json = page.json(debug);
1744        for (name, value) in res.headers() {
1745            if name != CONTENT_TYPE && name != CONTENT_LENGTH {
1746                json.headers_mut().insert(name.clone(), value.clone());
1747            }
1748        }
1749        return json;
1750    }
1751    let html = state
1752        .views
1753        .render_error(&page, debug, request_line, globals)
1754        .unwrap_or_else(|err| {
1755            tracing::error!(error = ?err, "could not render the error page");
1756            crate::error::error_page(page.status, page.shown_detail(debug))
1757        });
1758    with_html(res, html)
1759}
1760
1761fn with_html(mut res: Response, html: String) -> Response {
1762    let headers = res.headers_mut();
1763    headers.insert(
1764        CONTENT_TYPE,
1765        HeaderValue::from_static("text/html; charset=utf-8"),
1766    );
1767    headers.remove(CONTENT_LENGTH);
1768    *res.body_mut() = Body::from(html);
1769    res
1770}
1771
1772/// Flashed values; a key that wasn't flashed reads as `""`, so
1773/// `{{ flash.status }}` needs no `if`, even with strict templates.
1774#[derive(Debug)]
1775struct Flashed(serde_json::Map<String, serde_json::Value>);
1776
1777impl minijinja::value::Object for Flashed {
1778    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
1779        let key = key.as_str()?;
1780        Some(
1781            self.0
1782                .get(key)
1783                .map(Value::from_serialize)
1784                .unwrap_or_else(|| Value::from("")),
1785        )
1786    }
1787
1788    fn enumerate(self: &Arc<Self>) -> minijinja::value::Enumerator {
1789        minijinja::value::Enumerator::Values(
1790            self.0.keys().map(|k| Value::from(k.as_str())).collect(),
1791        )
1792    }
1793
1794    fn repr(self: &Arc<Self>) -> minijinja::value::ObjectRepr {
1795        minijinja::value::ObjectRepr::Map
1796    }
1797}
1798
1799/// Builds the menus `used` names for the request's user.
1800async fn request_menus(
1801    state: &AppState,
1802    current_user: Option<&CurrentUser>,
1803    locale: &str,
1804    route: Option<&str>,
1805    path: &str,
1806    used: crate::nav::MenusUsed,
1807) -> std::collections::HashMap<String, Vec<crate::nav::MenuGroup>> {
1808    if state.nav.menus.is_empty() || (used.names.is_empty() && !used.dynamic) {
1809        return Default::default();
1810    }
1811    let user = current_user.and_then(|c| crate::auth::auth_user_of(c, state));
1812    crate::nav::build_for_request(state, user.as_ref(), locale, route, path, &used).await
1813}
1814
1815/// What templates see of the request, besides the session and user.
1816struct Requested<'a> {
1817    path: &'a str,
1818    query: &'a str,
1819    /// The matched route's name, if it has one.
1820    route: Option<&'a str>,
1821    nonce: &'a str,
1822    /// Analytics events for this page's head.
1823    events: &'a [crate::analytics::Event],
1824}
1825
1826/// The templates' `t(key, name=…, count=…)` in `locale`.
1827pub(crate) fn translate_function(state: &AppState, locale: &str) -> Value {
1828    let translator = state.translator.clone();
1829    let (locale, fallback) = (locale.to_owned(), state.config.fallback_locale.clone());
1830    Value::from_function(
1831        move |key: String, kwargs: minijinja::value::Kwargs| -> Result<Value, minijinja::Error> {
1832            let mut params = Vec::new();
1833            let mut count = None;
1834            for name in kwargs.args() {
1835                let value: Value = kwargs.get(name)?;
1836                if name == "count" {
1837                    match i64::try_from(value.clone()) {
1838                        Ok(whole) => count = Some(whole),
1839                        // Not a whole number (a fraction, or text such as
1840                        // "1,204"): `:count` shows it as given, and a plural
1841                        // form is still picked by its value when it has one.
1842                        Err(_) => {
1843                            let shown = value.to_string();
1844                            let number = f64::try_from(value)
1845                                .ok()
1846                                .or_else(|| shown.trim().parse::<f64>().ok());
1847                            count = number.map(plural_count);
1848                            params.push((name.to_owned(), shown));
1849                        }
1850                    }
1851                } else {
1852                    params.push((name.to_owned(), value.to_string()));
1853                }
1854            }
1855            kwargs.assert_all_used()?;
1856            let params: Vec<(&str, String)> = params
1857                .iter()
1858                .map(|(k, v)| (k.as_str(), v.clone()))
1859                .collect();
1860            let text = translator.get(&locale, &fallback, &key);
1861            Ok(Value::from(crate::i18n::format(&text, &params, count)))
1862        },
1863    )
1864}
1865
1866/// The count a number stands for when picking a plural form: one only for
1867/// exactly 1 (so 1.5 or 0.5 kilos are plural), else the nearest whole one
1868/// (for ranges such as `[2,5]`).
1869fn plural_count(number: f64) -> i64 {
1870    if number == 1.0 {
1871        1
1872    } else {
1873        match number.round() as i64 {
1874            1 => 2,
1875            other => other,
1876        }
1877    }
1878}
1879
1880fn globals(
1881    state: &AppState,
1882    session: Option<&Session>,
1883    current_user: Option<CurrentUser>,
1884    htmx: &Htmx,
1885    requested: &Requested,
1886    locale: &str,
1887    menus: std::collections::HashMap<String, Vec<crate::nav::MenuGroup>>,
1888) -> Value {
1889    let config = &state.config;
1890    let token = session.map(Session::token).unwrap_or_default();
1891
1892    let strict = state.security.mode == crate::CspMode::Strict;
1893    let head = Value::from_safe_string(format!(
1894        "{}\n{}",
1895        assets::head_tags(&token, state.live.is_some(), strict),
1896        crate::seo::head_tags(&state.config, requested.nonce, requested.events)
1897    ));
1898    let seo = {
1899        let (config, path, locale) = (
1900            state.config.clone(),
1901            requested.path.to_owned(),
1902            locale.to_owned(),
1903        );
1904        Value::from_function(
1905            move |kwargs: minijinja::value::Kwargs| -> Result<Value, minijinja::Error> {
1906                crate::seo::tags(&config, &path, &locale, &kwargs).map(Value::from_safe_string)
1907            },
1908        )
1909    };
1910    let nonce = requested.nonce.to_owned();
1911    // `<rx-pwa/>`: the manifest link, colours, icon and registration script
1912    // (with the CSP nonce); nothing without `App::pwa`.
1913    let pwa = Value::from_safe_string(
1914        state
1915            .pwa
1916            .as_ref()
1917            .map(|pwa| pwa.head_tags(requested.nonce))
1918            .unwrap_or_default(),
1919    );
1920    let field = Value::from_safe_string(format!(
1921        "<input type=\"hidden\" name=\"{}\" value=\"{token}\">",
1922        crate::csrf::CSRF_FIELD
1923    ));
1924    let old_input = session.cloned();
1925    let has_old = session.is_some_and(Session::has_old_input);
1926    let toast_session = session.cloned();
1927    let toast_texts = crate::toast::RegionTexts {
1928        dismiss: state
1929            .translator
1930            .get(locale, &state.config.fallback_locale, "ui.dismiss"),
1931        failed: state
1932            .translator
1933            .get(locale, &state.config.fallback_locale, "ui.request_failed"),
1934    };
1935    let seen = std::sync::Mutex::new(std::collections::HashSet::<String>::new());
1936    let user = current_user.as_ref().and_then(|c| c.user.clone());
1937    let roles = current_user
1938        .as_ref()
1939        .map(|c| c.grants.roles())
1940        .unwrap_or_default();
1941    let gate_user = current_user.and_then(|c| Some((c.user?, c.gates, c.grants)));
1942    // Errors flashed in a named bag (`Validate::ERROR_BAG`) are shown only
1943    // by `error(field, bag=…)` and `errors_in(bag)`.
1944    let error_bag = session.and_then(Session::error_bag);
1945    let flashed_errors = match (session, &error_bag) {
1946        (Some(session), Some(bag)) => session.errors_in(bag),
1947        (Some(session), None) => session.errors(),
1948        (None, _) => Default::default(),
1949    };
1950    let errors = if error_bag.is_none() {
1951        flashed_errors.clone()
1952    } else {
1953        Default::default()
1954    };
1955    let first_errors: std::collections::BTreeMap<String, String> = flashed_errors
1956        .iter()
1957        .filter_map(|(field, messages)| {
1958            messages
1959                .get(0)
1960                .and_then(|m| m.as_str())
1961                .map(|m| (field.clone(), m.to_owned()))
1962        })
1963        .collect();
1964
1965    context! {
1966        app => context! {
1967            name => config.name,
1968            env => format!("{:?}", config.env).to_lowercase(),
1969            debug => config.debug,
1970            url => config.url,
1971            locale => locale,
1972            dir => state.direction(locale).as_str(),
1973            currency => config.currency,
1974        },
1975        auth => context! {
1976            check => user.is_some(),
1977            user => user.as_deref(),
1978            roles => roles,
1979        },
1980        t => translate_function(state, locale),
1981        // `can('admin')` asks a gate; `can('update', product)` reads the
1982        // abilities `auth::Can` attached to the model in the handler.
1983        can => Value::from_function(move |ability: String, target: Option<Value>| {
1984            match target {
1985                Some(target) => target
1986                    .get_attr("_can")
1987                    .and_then(|can| can.get_attr(&ability))
1988                    .is_ok_and(|allowed| allowed.is_true()),
1989                None => gate_user
1990                    .as_ref()
1991                    .is_some_and(|(user, gates, grants)| gates.check(user, grants, &ability)),
1992            }
1993        }),
1994        request => context! {
1995            path => requested.path,
1996            query => requested.query,
1997            route => requested.route,
1998            htmx => htmx.request,
1999            boosted => htmx.boosted,
2000        },
2001        // `route_is('admin.*')`, `route_is('products.index', 'products.show')`.
2002        route_is => {
2003            let route = requested.route.map(str::to_owned);
2004            Value::from_function(move |patterns: minijinja::value::Rest<String>| {
2005                route.as_deref().is_some_and(|name| {
2006                    patterns
2007                        .iter()
2008                        .any(|pattern| crate::routing::route_name_matches(name, pattern))
2009                })
2010            })
2011        },
2012        // `nav('staff')`: the groups of a menu the app's modules contributed
2013        // to, for this request's user (built before rendering, only for the
2014        // menus the page's templates name).
2015        nav => Value::from_function(move |menu: String| {
2016            Value::from_serialize(menus.get(&menu).map(Vec::as_slice).unwrap_or_default())
2017        }),
2018        csrf_token => token,
2019        flash => Value::from_object(Flashed(session.map(Session::flashed).unwrap_or_default())),
2020        errors => errors,
2021        // `errors_in('login')`: every error of a named bag.
2022        errors_in => {
2023            let bag = error_bag.clone();
2024            Value::from_function(move |name: String| {
2025                if bag.as_deref() == Some(name.as_str()) {
2026                    Value::from_serialize(&flashed_errors)
2027                } else {
2028                    Value::from_serialize(serde_json::Map::new())
2029                }
2030            })
2031        },
2032        // `error('photos')` also shows the first error of an item (`photos.1`);
2033        // `error('email', bag='login')` reads a named bag.
2034        error => Value::from_function(move |field: String, kwargs: minijinja::value::Kwargs| {
2035            let bag: Option<String> = kwargs.get("bag")?;
2036            kwargs.assert_all_used()?;
2037            if bag != error_bag {
2038                return Ok::<_, minijinja::Error>(String::new());
2039            }
2040            // `items[0][name]`'s errors are keyed `items.0.name`.
2041            // Custom fields are keyed as they are named (`extra[passport_no]`).
2042            let raw = field.clone();
2043            let field = crate::validation::nested::normalize(&field);
2044            Ok(first_errors
2045                .get(&raw)
2046                .or_else(|| first_errors.get(&field))
2047                .or_else(|| {
2048                    let prefix = format!("{field}.");
2049                    first_errors
2050                        .iter()
2051                        .find(|(key, _)| key.starts_with(&prefix))
2052                        .map(|(_, message)| message)
2053                })
2054                .cloned()
2055                .unwrap_or_default())
2056        }),
2057        renox_head => Value::from_function(move || head.clone()),
2058        renox_pwa => Value::from_function(move || pwa.clone()),
2059        seo => seo,
2060        csp_nonce => Value::from_function(move || nonce.clone()),
2061        csrf_field => Value::from_function(move || field.clone()),
2062        // `{{ toasts() }}`: the toast region, with the toasts waiting for
2063        // this page (taken from the session: shown once).
2064        // `toasts(position="bottom-end")` moves them (see toast::POSITIONS).
2065        toasts => Value::from_function(move |kwargs: minijinja::value::Kwargs| {
2066            let position: Option<String> = kwargs.get("position")?;
2067            kwargs.assert_all_used()?;
2068            let waiting: Vec<crate::Toast> = toast_session
2069                .as_ref()
2070                .and_then(|s| s.pull(crate::toast::SESSION_KEY))
2071                .unwrap_or_default();
2072            Ok::<_, minijinja::Error>(Value::from_safe_string(crate::toast::region(
2073                &waiting,
2074                &toast_texts,
2075                position.as_deref().unwrap_or("top"),
2076            )))
2077        }),
2078        // `{% if once('date-picker') %}…{% endif %}`: true the first time a key
2079        // is asked for on a page, e.g. for a component's script.
2080        once => Value::from_function(move |key: String| {
2081            seen.lock().unwrap_or_else(|e| e.into_inner()).insert(key)
2082        }),
2083        // `has_old()`: the previous request was a failed submit, so a field
2084        // missing from `old()` was sent empty (an unticked checkbox).
2085        has_old => Value::from_function(move || has_old),
2086        old => Value::from_function(move |field: String, default: Option<Value>| {
2087            old_input
2088                .as_ref()
2089                .and_then(|s| s.old(&field))
2090                .map(Value::from_serialize)
2091                .or(default)
2092                .unwrap_or_else(|| Value::from(""))
2093        }),
2094    }
2095}
2096
2097#[cfg(test)]
2098mod tests {
2099    use super::*;
2100
2101    fn views_in(dir: &Path) -> Views {
2102        let config = Config {
2103            views_path: dir.to_path_buf(),
2104            ..Config::default()
2105        };
2106        Views::new(
2107            &config,
2108            Arc::new(RouteTable::default()),
2109            Storage::from_config(&config).unwrap(),
2110            None,
2111            Arc::new(Vec::new()),
2112            Arc::new(Vec::new()),
2113            config.timezone,
2114            Arc::new(crate::embedded::AssetVersions::new(dir, None)),
2115        )
2116    }
2117
2118    #[test]
2119    fn check_finds_every_broken_template_with_its_line() {
2120        let dir = tempfile::tempdir().unwrap();
2121        let write = |name: &str, body: &str| {
2122            let path = dir.path().join(name);
2123            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2124            std::fs::write(path, body).unwrap();
2125        };
2126        write("good.html", "<h1>{{ 1 + 1 }}</h1>");
2127        write("sub/typo.html", "<p>x</p>\n<rx-tabel>y</rx-tabel>\n");
2128        write("bad.html", "a\nb\n{% if x %}\nc\n");
2129        write(".hidden.html", "{% if %}");
2130        write("notes.md", "{% if %}");
2131        let views = views_in(dir.path());
2132
2133        let names = views.names();
2134        assert!(names.contains(&"good.html".to_owned()));
2135        assert!(names.contains(&"sub/typo.html".to_owned()));
2136        assert!(names.contains(&"renox/error.html".to_owned()));
2137        assert!(
2138            !names
2139                .iter()
2140                .any(|n| n.contains("hidden") || n.ends_with(".md"))
2141        );
2142        assert!(names.windows(2).all(|w| w[0] < w[1]));
2143
2144        let problems = views.check(&RouteTable::default());
2145        assert_eq!(problems.len(), 2, "{problems:?}");
2146        assert_eq!(problems[0].template, "bad.html");
2147        assert!(problems[0].line.is_some_and(|l| l >= 3), "{problems:?}");
2148        assert_eq!(problems[1].template, "sub/typo.html");
2149        assert_eq!(problems[1].line, Some(2));
2150        assert!(problems[1].message.contains("rx-tabel"), "{problems:?}");
2151        assert!(
2152            problems[1]
2153                .to_string()
2154                .starts_with("sub/typo.html:2: unknown component"),
2155        );
2156    }
2157
2158    #[test]
2159    fn check_reports_unknown_route_names_with_a_suggestion() {
2160        let dir = tempfile::tempdir().unwrap();
2161        std::fs::write(
2162            dir.path().join("p.html"),
2163            "<a href=\"{{ route('products.index') }}\">ok</a>\n\
2164             <a href=\"{{ route('products.indx') }}\">typo</a>\n\
2165             <a href=\"{{ route('shop.home') }}\">domain</a>\n\
2166             <a href=\"{{ route('nothing.like.it') }}\">far</a>\n",
2167        )
2168        .unwrap();
2169        let mut routes = RouteTable::default();
2170        routes
2171            .insert("products.index".into(), "/products".into())
2172            .unwrap();
2173        // A route defined inside `Routes::domain` is in the table as well.
2174        routes.insert("shop.home".into(), "/".into()).unwrap();
2175        routes.set_domain("shop.home", "shop.example.com");
2176        let problems = views_in(dir.path()).check(&routes);
2177        assert_eq!(problems.len(), 2, "{problems:?}");
2178        assert_eq!(problems[0].line, Some(2));
2179        assert_eq!(
2180            problems[0].to_string(),
2181            "p.html:2: unknown route \"products.indx\"; did you mean \"products.index\"?"
2182        );
2183        assert_eq!(problems[1].line, Some(4));
2184        assert!(!problems[1].message.contains("did you mean"));
2185    }
2186
2187    fn env() -> Environment<'static> {
2188        let mut env = Environment::new();
2189        for name in REQUEST_GLOBALS {
2190            env.add_global(*name, Value::from_object(RequestGlobal(name)));
2191        }
2192        env
2193    }
2194
2195    /// A template rendered while a page renders (a component a Rust
2196    /// template function renders, say) reads the page's request values
2197    /// through the `RequestGlobal`s; outside a page they are empty.
2198    #[test]
2199    fn request_globals_read_the_page_being_rendered() {
2200        let env = env();
2201        let page = "{% if auth %}[{{ auth.name }}]{% endif %}\
2202                    {% for key in flash %}{{ key }}={{ flash[key] }};{% endfor %}\
2203                    {{ t('hi') }}|{{ request }}|{% for e in errors %}{{ e }}{% endfor %}.";
2204
2205        let outside = env
2206            .render_str(
2207                "{% if auth %}in{% endif %}[{{ request }}]{% for k in flash %}{{ k }}{% endfor %}",
2208                (),
2209            )
2210            .unwrap();
2211        assert_eq!(outside, "[]");
2212        let err = env.render_str("{{ t('hi') }}", ()).unwrap_err();
2213        assert!(
2214            err.to_string()
2215                .contains("`t` is only available while rendering a page"),
2216            "{err}"
2217        );
2218
2219        let globals = minijinja::context! {
2220            auth => minijinja::context! { name => "Ann" },
2221            flash => minijinja::context! { status => "Saved" },
2222            t => Value::from_function(|key: String| format!("({key})")),
2223            request => "GET /",
2224            // A list: not a map, so it lists no keys.
2225            errors => vec!["a"],
2226        };
2227        let current = CurrentGlobals::set(globals);
2228        assert_eq!(
2229            env.render_str(page, ()).unwrap(),
2230            "[Ann]status=Saved;(hi)|GET /|."
2231        );
2232        drop(current);
2233        assert_eq!(env.render_str("{{ request }}", ()).unwrap(), "");
2234    }
2235}