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    /// Renox's own templates are not read: they get the menu name from the
842    /// caller.
843    pub(crate) fn menus_used(&self, name: &str) -> crate::nav::MenusUsed {
844        let mut used = crate::nav::MenusUsed::default();
845        let Ok(env) = self.reloader.acquire_env() else {
846            return used;
847        };
848        let mut seen = std::collections::HashSet::new();
849        let mut queue = vec![name.to_owned()];
850        while let Some(next) = queue.pop() {
851            if !seen.insert(next.clone()) || BUILTIN.iter().any(|(n, _)| *n == next) {
852                continue;
853            }
854            let Ok(template) = env.get_template(&next) else {
855                continue;
856            };
857            let source = template.source();
858            used.scan(source);
859            // Every quoted `….html` name is a layout, an include or an
860            // import (or text that happens to match). Found from the end of
861            // the name, so an apostrophe in a comment cannot pair the quotes
862            // wrongly.
863            let mut from = 0;
864            while let Some(at) = source[from..].find(".html") {
865                let end = from + at + ".html".len();
866                from = end;
867                let Some(quote) = source[end..]
868                    .chars()
869                    .next()
870                    .filter(|c| matches!(c, '"' | '\''))
871                else {
872                    continue;
873                };
874                let line_start = source[..end].rfind('\n').map_or(0, |i| i + 1);
875                if let Some(open) = source[line_start..end].rfind(quote) {
876                    queue.push(source[line_start + open + 1..end].to_owned());
877                }
878            }
879        }
880        used
881    }
882
883    /// Whether a template of this name exists (the app's or a built-in).
884    pub fn exists(&self, name: &str) -> bool {
885        self.reloader
886            .acquire_env()
887            .is_ok_and(|env| env.get_template(name).is_ok())
888    }
889
890    /// Renders a template with the given context and no request globals.
891    pub fn render(&self, name: &str, ctx: impl Serialize) -> anyhow::Result<String> {
892        let env = self.reloader.acquire_env()?;
893        Ok(env.get_template(name)?.render(ctx)?)
894    }
895
896    fn render_view(
897        &self,
898        view: &View,
899        shared: Value,
900        globals: Value,
901        htmx: &Htmx,
902    ) -> anyhow::Result<String> {
903        let env = self.reloader.acquire_env()?;
904        let template = env.get_template(&view.name)?;
905        // Components (macros imported from other templates) don't see this
906        // context; they reach the same values through `RequestGlobal`s.
907        let _current = CurrentGlobals::set(globals.clone());
908        // The last map wins: shared values, then the handler's, then Renox's.
909        // A value named like a macro the template imports is hidden by the
910        // macro, which fails far from the cause (#312): say so while debugging.
911        let hidden = if self.debug {
912            hidden_by_imports(template.source(), &[&shared, &view.ctx])
913        } else {
914            Vec::new()
915        };
916        for name in &hidden {
917            tracing::warn!(
918                template = %view.name,
919                name = %name,
920                "the view gets a value named like a macro the template imports; the macro hides it (rename one)"
921            );
922        }
923        // `nav('menu')` is a request global, but a page that already passes its
924        // own `nav` value keeps it (the global would otherwise hide it).
925        let own_nav = [&view.ctx, &shared]
926            .iter()
927            .find_map(|layer| layer.get_attr("nav").ok().filter(|n| !n.is_undefined()))
928            .map_or_else(
929                || Value::from_serialize(serde_json::Map::new()),
930                |nav| context! { nav },
931            );
932        let ctx = merge_maps([shared, view.ctx.clone(), globals, own_nav]);
933        let stacks = crate::view_stack::Scope::begin();
934        let rendered = match &view.fragment {
935            Some(block) if htmx.wants_fragment() => (|| {
936                let mut captured = template.render_captured_to(ctx, std::io::sink())?;
937                let mut out = captured.with_state_mut(|state| state.render_block(block))?;
938                for extra in &view.also {
939                    out.push_str(&captured.with_state_mut(|state| state.render_block(extra))?);
940                }
941                Ok::<_, minijinja::Error>(out)
942            })(),
943            _ => template.render(ctx),
944        };
945        let html = rendered.map_err(|err| {
946            let err = anyhow::Error::from(err);
947            match hidden.as_slice() {
948                [] => err,
949                names => err.context(format!(
950                    "{} imports a macro named like a value the view gets ({}): \
951                     inside the template the name is the macro; rename the value or import the macro `as` another name",
952                    view.name,
953                    names.join(", ")
954                )),
955            }
956        })?;
957        Ok(stacks.finish(html))
958    }
959
960    /// The error page: the app's `errors/{status}.html`, else its
961    /// `errors/default.html`, else Renox's. With `globals` (a request's), an
962    /// app's page can extend its layout; a page that fails falls back to
963    /// Renox's, so an error in the layout doesn't hide the first error.
964    fn render_error(
965        &self,
966        page: &ErrorPage,
967        debug: bool,
968        request: &str,
969        globals: Option<Value>,
970    ) -> anyhow::Result<String> {
971        let env = self.reloader.acquire_env()?;
972        let ctx = context! {
973            status => page.status.as_u16(),
974            reason => reason(page.status),
975            detail => page.shown_detail(debug),
976            // Only while developing: what was asked, and where a template failed.
977            debug => debug,
978            request_line => debug.then_some(request),
979            template => page.template.as_deref().filter(|_| debug),
980        };
981        for name in [
982            format!("errors/{}.html", page.status.as_u16()),
983            "errors/default.html".to_owned(),
984        ] {
985            let template = match env.get_template(&name) {
986                Ok(template) => template,
987                Err(err) if err.kind() == ErrorKind::TemplateNotFound => continue,
988                // One that doesn't parse fails like one that doesn't render.
989                Err(err) => {
990                    tracing::error!(error = ?err, template = %name, "the error page failed; showing Renox's");
991                    break;
992                }
993            };
994            let rendered = match &globals {
995                Some(globals) => {
996                    let _current = CurrentGlobals::set(globals.clone());
997                    let stacks = crate::view_stack::Scope::begin();
998                    template
999                        .render(merge_maps([globals.clone(), ctx.clone()]))
1000                        .map(|html| stacks.finish(html))
1001                }
1002                None => template.render(ctx.clone()),
1003            };
1004            match rendered {
1005                Ok(html) => return Ok(html),
1006                Err(err) => {
1007                    tracing::error!(error = ?err, template = %name, "the error page failed; showing Renox's");
1008                    break;
1009                }
1010            }
1011        }
1012        Ok(env.get_template("renox/error.html")?.render(ctx)?)
1013    }
1014}
1015
1016/// The template a response was rendered from.
1017#[derive(Debug, Clone)]
1018pub(crate) struct RenderedView(pub String);
1019
1020/// The globals Renox gives each rendered page (see `globals`), which
1021/// components reach through the environment.
1022pub(crate) const REQUEST_GLOBALS: &[&str] = &[
1023    "app",
1024    "auth",
1025    "t",
1026    "can",
1027    "request",
1028    "route_is",
1029    "nav",
1030    "csrf_token",
1031    "csrf_field",
1032    "flash",
1033    "errors",
1034    "errors_in",
1035    "error",
1036    "old",
1037    "has_old",
1038    "renox_head",
1039    "renox_pwa",
1040    "seo",
1041    "csp_nonce",
1042    "toasts",
1043    "once",
1044];
1045
1046thread_local! {
1047    /// The globals of the page being rendered on this thread.
1048    static CURRENT: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
1049}
1050
1051/// Makes `globals` the current page's while alive (rendering is synchronous).
1052struct CurrentGlobals(Option<Value>);
1053
1054impl CurrentGlobals {
1055    fn set(globals: Value) -> Self {
1056        Self(CURRENT.with(|c| c.borrow_mut().replace(globals)))
1057    }
1058}
1059
1060impl Drop for CurrentGlobals {
1061    fn drop(&mut self) {
1062        let previous = self.0.take();
1063        CURRENT.with(|c| *c.borrow_mut() = previous);
1064    }
1065}
1066
1067/// A request global as seen from the environment: forwards to the value of
1068/// the page being rendered, so an imported macro gets the same `old()`,
1069/// `auth`, `t()`… as the template that called it.
1070#[derive(Debug)]
1071struct RequestGlobal(&'static str);
1072
1073impl RequestGlobal {
1074    fn current(&self) -> Option<Value> {
1075        CURRENT
1076            .with(|c| c.borrow().clone())
1077            .and_then(|globals| globals.get_attr(self.0).ok())
1078            .filter(|v| !v.is_undefined())
1079    }
1080}
1081
1082impl minijinja::value::Object for RequestGlobal {
1083    fn repr(self: &Arc<Self>) -> minijinja::value::ObjectRepr {
1084        minijinja::value::ObjectRepr::Map
1085    }
1086
1087    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
1088        self.current()?
1089            .get_item(key)
1090            .ok()
1091            .filter(|v| !v.is_undefined())
1092    }
1093
1094    fn enumerate(self: &Arc<Self>) -> minijinja::value::Enumerator {
1095        match self
1096            .current()
1097            .and_then(|v| v.try_iter().ok().map(|keys| keys.collect::<Vec<_>>()))
1098        {
1099            Some(keys)
1100                if self
1101                    .current()
1102                    .is_some_and(|v| v.kind() == minijinja::value::ValueKind::Map) =>
1103            {
1104                minijinja::value::Enumerator::Values(keys)
1105            }
1106            _ => minijinja::value::Enumerator::Empty,
1107        }
1108    }
1109
1110    fn is_true(self: &Arc<Self>) -> bool {
1111        self.current().is_some_and(|v| v.is_true())
1112    }
1113
1114    fn call(
1115        self: &Arc<Self>,
1116        state: &minijinja::State<'_, '_>,
1117        args: &[Value],
1118    ) -> Result<Value, minijinja::Error> {
1119        match self.current() {
1120            Some(value) => value.call(state, args),
1121            None => Err(minijinja::Error::new(
1122                ErrorKind::InvalidOperation,
1123                format!("`{}` is only available while rendering a page", self.0),
1124            )),
1125        }
1126    }
1127
1128    fn render(self: &Arc<Self>, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1129        match self.current() {
1130            Some(value) => std::fmt::Display::fmt(&value, f),
1131            None => Ok(()),
1132        }
1133    }
1134}
1135
1136/// Like MiniJinja's default formatter, but HTML escaping leaves `/` alone:
1137/// escaping `& < > " '` is enough for text and quoted attributes, and URLs
1138/// (links in pages and mail) stay readable.
1139fn format_value(
1140    out: &mut minijinja::Output,
1141    state: &minijinja::State,
1142    value: &Value,
1143) -> Result<(), minijinja::Error> {
1144    use std::fmt::Write;
1145    if let (minijinja::AutoEscape::Html, false, Some(text)) =
1146        (state.auto_escape(), value.is_safe(), value.as_str())
1147    {
1148        for c in text.chars() {
1149            let written = match c {
1150                '&' => out.write_str("&amp;"),
1151                '<' => out.write_str("&lt;"),
1152                '>' => out.write_str("&gt;"),
1153                '"' => out.write_str("&quot;"),
1154                '\'' => out.write_str("&#39;"),
1155                c => out.write_char(c),
1156            };
1157            written.map_err(|_| {
1158                minijinja::Error::new(ErrorKind::WriteFailure, "could not write output")
1159            })?;
1160        }
1161        return Ok(());
1162    }
1163    minijinja::escape_formatter(out, state, value)
1164}
1165
1166fn load(
1167    dir: &Path,
1168    embedded: Option<&'static [(&'static str, &'static str)]>,
1169    name: &str,
1170) -> Result<Option<String>, minijinja::Error> {
1171    if let Some(files) = embedded {
1172        if let Some((_, source)) = files.iter().find(|(file, _)| *file == name) {
1173            return Ok(Some((*source).to_owned()));
1174        }
1175    } else if let Some(path) = safe_join(dir, name) {
1176        match std::fs::read_to_string(&path) {
1177            Ok(source) => return Ok(Some(source)),
1178            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
1179            Err(err) => {
1180                return Err(minijinja::Error::new(
1181                    ErrorKind::InvalidOperation,
1182                    format!("could not read template {}", path.display()),
1183                )
1184                .with_source(err));
1185            }
1186        }
1187    }
1188    Ok(BUILTIN
1189        .iter()
1190        .find(|(builtin, _)| *builtin == name)
1191        .map(|(_, source)| (*source).to_owned()))
1192}
1193
1194/// Reports every literal `route('name')` in the compiled `source` that no route has.
1195fn check_route_names(
1196    template: &str,
1197    source: &str,
1198    routes: &RouteTable,
1199    problems: &mut Vec<ViewProblem>,
1200) {
1201    static ROUTE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1202        regex::Regex::new(r#"\broute\(\s*["']([^"']+)["']"#).expect("valid regex")
1203    });
1204    for caps in ROUTE.captures_iter(source) {
1205        let name = &caps[1];
1206        if routes.path(name).is_some() {
1207            continue;
1208        }
1209        let hint = crate::components::suggest::did_you_mean(name, routes.names())
1210            .map(|x| format!("; did you mean \"{x}\"?"))
1211            .unwrap_or_default();
1212        let offset = caps.get(0).map_or(0, |m| m.start());
1213        problems.push(ViewProblem {
1214            template: template.to_owned(),
1215            line: Some(source[..offset].matches('\n').count() + 1),
1216            message: format!("unknown route \"{name}\"{hint}"),
1217        });
1218    }
1219}
1220
1221/// Reports `{% include "name" %}` (what `<rx-include template="name"/>` compiles to) of a template
1222/// that does not exist. An include with `ignore missing`, or whose name is worked out at run
1223/// time, is not checked.
1224fn check_includes(
1225    template: &str,
1226    source: &str,
1227    known: &std::collections::HashSet<&str>,
1228    problems: &mut Vec<ViewProblem>,
1229) {
1230    static INCLUDE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1231        regex::Regex::new(r#"\{%-?\s*include\s+["']([^"']+)["']\s*-?%\}"#).expect("valid regex")
1232    });
1233    for caps in INCLUDE.captures_iter(source) {
1234        let name = &caps[1];
1235        if known.contains(name) {
1236            continue;
1237        }
1238        let hint = crate::components::suggest::did_you_mean(name, known.iter().copied())
1239            .map(|x| format!("; did you mean \"{x}\"?"))
1240            .unwrap_or_default();
1241        let offset = caps.get(0).map_or(0, |m| m.start());
1242        problems.push(ViewProblem {
1243            template: template.to_owned(),
1244            line: Some(source[..offset].matches('\n').count() + 1),
1245            message: format!(
1246                "<rx-include> (or include) names a template that does not exist: \"{name}\"{hint}"
1247            ),
1248        });
1249    }
1250}
1251
1252/// A [`ViewProblem`] from a compile error. The component compiler's details
1253/// already start with `name:line: `, which is taken out of the message.
1254fn problem(name: &str, err: &minijinja::Error) -> ViewProblem {
1255    let detail = err.detail().unwrap_or("could not be compiled");
1256    if let Some(rest) = detail.strip_prefix(name).and_then(|r| r.strip_prefix(':'))
1257        && let Some((line, message)) = rest.split_once(": ")
1258        && let Ok(line) = line.parse::<usize>()
1259    {
1260        return ViewProblem {
1261            template: name.to_owned(),
1262            line: Some(line),
1263            message: message.to_owned(),
1264        };
1265    }
1266    ViewProblem {
1267        template: name.to_owned(),
1268        line: err.line(),
1269        message: detail.to_owned(),
1270    }
1271}
1272
1273fn safe_join(dir: &Path, name: &str) -> Option<PathBuf> {
1274    let mut path = dir.to_path_buf();
1275    for component in Path::new(name).components() {
1276        match component {
1277            PathPart::Normal(part) => path.push(part),
1278            _ => return None,
1279        }
1280    }
1281    Some(path)
1282}
1283
1284/// A template response, rendered by Renox with the request's globals:
1285/// `app` (with the request's `app.locale`), `request`, `auth` (`auth.check`,
1286/// `auth.user`), `t()`, `can()`, `flash`, `errors`, `error()`, `old()`,
1287/// `csrf_token`, `csrf_field()` and `renox_head()`.
1288///
1289/// ```
1290/// # use renox::prelude::*;
1291/// # let list: Vec<String> = Vec::new();
1292/// # let _ = move || {
1293/// async fn index() -> View {
1294/// #   let list: Vec<String> = Vec::new();
1295///     view("products/index.html", context! { products => list }).fragment("list")
1296/// }
1297/// # };
1298/// ```
1299#[derive(Clone)]
1300pub struct View {
1301    name: String,
1302    ctx: Value,
1303    fragment: Option<String>,
1304    /// More blocks sent with the fragment, for out-of-band swaps.
1305    also: Vec<String>,
1306    status: StatusCode,
1307}
1308
1309/// The line of the first `{{ … }}` or `{% … %}` tag that names `var`, if any.
1310fn first_use(source: &str, var: &str) -> Option<usize> {
1311    let word = regex::Regex::new(&format!(r"\b{}\b", regex::escape(var))).ok()?;
1312    let mut rest = source;
1313    let mut offset = 0;
1314    while let Some(open) = rest.find('{') {
1315        let after = &rest[open..];
1316        let close = match after.get(..2) {
1317            Some("{{") => "}}",
1318            Some("{%") => "%}",
1319            _ => {
1320                offset += open + 1;
1321                rest = &rest[open + 1..];
1322                continue;
1323            }
1324        };
1325        let end = after.find(close).map_or(after.len(), |i| i + 2);
1326        if word.is_match(&after[..end]) {
1327            return Some(source[..offset + open].matches('\n').count() + 1);
1328        }
1329        offset += open + end;
1330        rest = &rest[open + end..];
1331    }
1332    None
1333}
1334
1335/// Renders `name` from the views directory with `ctx` (anything serializable,
1336/// usually `context! { ... }`).
1337pub fn view(name: impl Into<String>, ctx: impl Serialize) -> View {
1338    View {
1339        name: name.into(),
1340        ctx: Value::from_serialize(ctx),
1341        fragment: None,
1342        also: Vec::new(),
1343        status: StatusCode::OK,
1344    }
1345}
1346
1347impl View {
1348    /// Renders a page struct in its own template ([`ViewData::TEMPLATE`]): the typed
1349    /// form of [`view`]. Register the struct with `App::view_data::<T>()` so
1350    /// `view:check` reports the template's variables the struct lacks.
1351    ///
1352    /// ```
1353    /// # use renox::prelude::*;
1354    /// #[derive(serde::Serialize, ViewData)]
1355    /// #[view(template = "orders/show.html")]
1356    /// struct OrderPage {
1357    ///     number: String,
1358    /// }
1359    ///
1360    /// async fn show() -> View {
1361    ///     View::typed(OrderPage { number: "A-1".into() }).fragment("summary")
1362    /// }
1363    /// ```
1364    pub fn typed<T: ViewData>(page: T) -> View {
1365        view(T::TEMPLATE, page)
1366    }
1367
1368    /// For HTMX requests (except `hx-boost`), render only this `{% block %}`.
1369    pub fn fragment(mut self, block: impl Into<String>) -> Self {
1370        self.fragment = Some(block.into());
1371        self
1372    }
1373
1374    /// For the same HTMX requests, also render `block` after the fragment,
1375    /// to update other parts of the page in one response: give the block's
1376    /// root element an `id` and `hx-swap-oob="true"` and htmx swaps it into
1377    /// the element with that id.
1378    ///
1379    /// ```html
1380    /// {% block row %}<tr id="order-{{ order.id }}">…</tr>{% endblock %}
1381    /// {% block count %}<span id="order-count" hx-swap-oob="true">{{ count }}</span>{% endblock %}
1382    /// ```
1383    ///
1384    /// `view("orders/index.html", ctx).fragment("row").also("count")`
1385    pub fn also(mut self, block: impl Into<String>) -> Self {
1386        self.also.push(block.into());
1387        self
1388    }
1389
1390    /// The response status (200 by default).
1391    pub fn status(mut self, status: StatusCode) -> Self {
1392        self.status = status;
1393        self
1394    }
1395}
1396
1397impl IntoResponse for View {
1398    fn into_response(self) -> Response {
1399        let mut res = self.status.into_response();
1400        res.extensions_mut().insert(self);
1401        res
1402    }
1403}
1404
1405/// Renders `View` and error responses once the handler has returned, and
1406/// turns validation errors into a redirect back for regular form posts.
1407pub(crate) async fn middleware(
1408    State(state): State<AppState>,
1409    req: Request,
1410    next: Next,
1411) -> Response {
1412    let session = req.extensions().get::<Session>().cloned();
1413    let current_user = req.extensions().get::<CurrentUser>().cloned();
1414    let htmx = Htmx::from_headers(req.headers());
1415    let method = req.method().clone();
1416    let path = req.uri().path().to_owned();
1417    let query = req.uri().query().unwrap_or_default().to_owned();
1418    let route = crate::routing::CurrentRoute::of(req.method(), req.extensions(), &state)
1419        .name()
1420        .map(str::to_owned);
1421    let host = crate::domain::host(&req).unwrap_or_default();
1422    let nonce = req
1423        .extensions()
1424        .get::<crate::security::CspNonce>()
1425        .map(|n| n.0.clone())
1426        .unwrap_or_default();
1427    let (wants_json, referer) = {
1428        let header = |name| req.headers().get(name).and_then(|v| v.to_str().ok());
1429        let wants_json = header(ACCEPT).is_some_and(|v| v.contains("application/json"))
1430            || header(CONTENT_TYPE).is_some_and(|v| v.starts_with("application/json"));
1431        // Back to the form's page, but never to another site.
1432        (wants_json, crate::htmx::same_site_referer(req.headers()))
1433    };
1434
1435    let request_line = if query.is_empty() {
1436        format!("{method} {path}")
1437    } else {
1438        format!("{method} {path}?{query}")
1439    };
1440    let mut res = next.run(req).await;
1441    // A layer may have switched the language (`RequestLocale::switch`).
1442    let locale = crate::i18n::current_locale(&state);
1443
1444    if let Some(crate::toast::PendingToasts(toasts)) =
1445        res.extensions_mut().remove::<crate::toast::PendingToasts>()
1446    {
1447        // An htmx swap shows them now; a page, an htmx redirect or refresh
1448        // on the next page, from the session (the reload would lose them).
1449        if htmx.request
1450            && !res.headers().contains_key("hx-redirect")
1451            && !res.headers().contains_key("hx-refresh")
1452        {
1453            crate::htmx::add_trigger(
1454                &mut res,
1455                crate::toast::EVENT,
1456                serde_json::json!({ "toasts": toasts }),
1457            );
1458        } else if let Some(session) = &session {
1459            let mut waiting: Vec<crate::Toast> =
1460                session.get(crate::toast::SESSION_KEY).unwrap_or_default();
1461            waiting.extend(toasts);
1462            if let Err(err) = session.put(crate::toast::SESSION_KEY, &waiting) {
1463                return err.into_response();
1464            }
1465        }
1466    }
1467
1468    if let Some(failed) = res.extensions_mut().remove::<ValidationError>() {
1469        if htmx.request || wants_json {
1470            return res;
1471        }
1472        if let Some(session) = &session {
1473            let bag = failed.bag().map(str::to_owned);
1474            // A `ValidationError` made after `Valid` (a model hook, the
1475            // handler) carries no input: refill with what `Valid` read.
1476            let input = if failed.input.is_empty() {
1477                crate::context::get::<crate::validation::extract::SubmittedInput>()
1478                    .map(|submitted| submitted.0)
1479                    .unwrap_or_default()
1480            } else {
1481                failed.input
1482            };
1483            let flashed = match &bag {
1484                Some(bag) => session.flash_errors_in(bag, &failed.errors),
1485                None => session.flash_errors(&failed.errors),
1486            }
1487            .and_then(|()| session.flash_input(&input));
1488            if let Err(err) = flashed {
1489                return err.into_response();
1490            }
1491        }
1492        return Redirect::to(referer.as_deref().unwrap_or("/")).into_response();
1493    }
1494
1495    // Analytics events: with an htmx swap, in its HX-Trigger; with a page,
1496    // in its head (below); otherwise they wait for the next page.
1497    if let Some(session) = &session
1498        && crate::analytics::has_pending(session)
1499        && htmx.request
1500        && crate::analytics::deliverable_by_htmx(&res)
1501    {
1502        crate::analytics::add_trigger(&mut res, crate::analytics::take(session));
1503    }
1504
1505    if let Some(view) = res.extensions_mut().remove::<View>() {
1506        let mut shared = std::collections::BTreeMap::new();
1507        for (key, compute) in state.shares.iter() {
1508            let ctx = ViewContext {
1509                state: state.clone(),
1510                user: current_user.as_ref().and_then(|c| c.user.clone()),
1511                locale: locale.clone(),
1512                path: path.clone(),
1513                session: session.clone(),
1514            };
1515            match compute(ctx).await {
1516                Ok(value) => {
1517                    shared.insert(key.clone(), value);
1518                }
1519                Err(err) => {
1520                    let err = match err {
1521                        Error::Internal(err) => err,
1522                        other => anyhow::anyhow!("{other:?}"),
1523                    };
1524                    // Shown like any error: the error page, with the detail
1525                    // while debugging.
1526                    let mut failed =
1527                        Error::Internal(err.context(format!("sharing `{key}` with views")))
1528                            .into_response();
1529                    return match failed.extensions_mut().remove::<ErrorPage>() {
1530                        Some(page) => error_response(
1531                            &state,
1532                            page,
1533                            failed,
1534                            wants_json,
1535                            &htmx,
1536                            &request_line,
1537                            None,
1538                        ),
1539                        None => failed,
1540                    };
1541                }
1542            }
1543        }
1544        add_theme(
1545            &mut shared,
1546            &state,
1547            &host,
1548            &path,
1549            &locale,
1550            current_user.as_ref(),
1551        )
1552        .await;
1553        let events = match &session {
1554            Some(session) if !htmx.request => crate::analytics::take(session),
1555            _ => Vec::new(),
1556        };
1557        let menus = request_menus(
1558            &state,
1559            current_user.as_ref(),
1560            &locale,
1561            route.as_deref(),
1562            &path,
1563            state.views.menus_used(&view.name),
1564        )
1565        .await;
1566        let globals = globals(
1567            &state,
1568            session.as_ref(),
1569            current_user.clone(),
1570            &htmx,
1571            &Requested {
1572                path: &path,
1573                query: &query,
1574                route: route.as_deref(),
1575                nonce: &nonce,
1576                events: &events,
1577            },
1578            &locale,
1579            menus,
1580        );
1581        return match state
1582            .views
1583            .render_view(&view, Value::from_serialize(&shared), globals, &htmx)
1584        {
1585            Ok(html) => {
1586                let mut page = with_html(res, html);
1587                // For `TestResponse::assert_view`.
1588                page.extensions_mut()
1589                    .insert(RenderedView(view.name.clone()));
1590                page
1591            }
1592            Err(err) => {
1593                let mut failed = Error::Internal(err.context(format!("rendering {}", view.name)))
1594                    .into_response();
1595                match failed.extensions_mut().remove::<ErrorPage>() {
1596                    Some(page) => {
1597                        error_response(&state, page, failed, wants_json, &htmx, &request_line, None)
1598                    }
1599                    None => failed,
1600                }
1601            }
1602        };
1603    }
1604
1605    if let Some(page) = res.extensions_mut().remove::<ErrorPage>() {
1606        // The app's error pages may extend its layout: give them what pages
1607        // get, the values `App::share`s included (a layout's cart count).
1608        let globals = if !wants_json || htmx.request {
1609            let mut shared = std::collections::BTreeMap::new();
1610            for (key, compute) in state.shares.iter() {
1611                let ctx = ViewContext {
1612                    state: state.clone(),
1613                    user: current_user.as_ref().and_then(|c| c.user.clone()),
1614                    locale: locale.clone(),
1615                    path: path.clone(),
1616                    session: session.clone(),
1617                };
1618                // A share that fails here only leaves its value out: the page
1619                // is about another error, which it mustn't hide.
1620                match compute(ctx).await {
1621                    Ok(value) => {
1622                        shared.insert(key.clone(), value);
1623                    }
1624                    Err(err) => {
1625                        tracing::warn!(error = ?err, key = %key, "a shared view value failed on an error page")
1626                    }
1627                }
1628            }
1629            add_theme(
1630                &mut shared,
1631                &state,
1632                &host,
1633                &path,
1634                &locale,
1635                current_user.as_ref(),
1636            )
1637            .await;
1638            // The app's error page may extend a layout with a menu: build
1639            // every menu, as the page that extends is not known here.
1640            let menus = request_menus(
1641                &state,
1642                current_user.as_ref(),
1643                &locale,
1644                route.as_deref(),
1645                &path,
1646                crate::nav::MenusUsed {
1647                    names: Vec::new(),
1648                    dynamic: true,
1649                },
1650            )
1651            .await;
1652            let page_globals = globals(
1653                &state,
1654                session.as_ref(),
1655                current_user,
1656                &htmx,
1657                &Requested {
1658                    path: &path,
1659                    query: &query,
1660                    route: route.as_deref(),
1661                    nonce: &nonce,
1662                    events: &[],
1663                },
1664                &locale,
1665                menus,
1666            );
1667            Some(merge_maps([page_globals, Value::from_serialize(&shared)]))
1668        } else {
1669            None
1670        };
1671        return error_response(&state, page, res, wants_json, &htmx, &request_line, globals);
1672    }
1673    res
1674}
1675
1676/// The key a request's brand stylesheet URL is shared under, for `renox_theme()` (not named like the function: a value would hide it).
1677pub(crate) const THEME_KEY: &str = "renox_theme_url";
1678
1679/// Resolves the request's brand (`App::theme`, `App::theme_for`) and shares
1680/// the URL of its stylesheet with the views; nothing is shared when the app
1681/// has no theme for this request.
1682async fn add_theme(
1683    shared: &mut std::collections::BTreeMap<String, Value>,
1684    state: &AppState,
1685    host: &str,
1686    path: &str,
1687    locale: &str,
1688    user: Option<&CurrentUser>,
1689) {
1690    if !state.themes.is_set() {
1691        return;
1692    }
1693    let url = state
1694        .themes
1695        .resolve(crate::theme::ThemeRequest {
1696            host: host.to_owned(),
1697            path: path.to_owned(),
1698            locale: locale.to_owned(),
1699            user: user.and_then(|c| c.user.clone()),
1700            state: state.clone(),
1701        })
1702        .await;
1703    if let Some(url) = url {
1704        shared.insert(THEME_KEY.to_owned(), Value::from(url));
1705    }
1706}
1707
1708/// The error page (or JSON for API clients) for `page`.
1709fn error_response(
1710    state: &AppState,
1711    page: ErrorPage,
1712    res: Response,
1713    wants_json: bool,
1714    htmx: &Htmx,
1715    request_line: &str,
1716    globals: Option<Value>,
1717) -> Response {
1718    let debug = state.config.debug;
1719    if wants_json && !htmx.request {
1720        // Keep what the error response carried (`Retry-After` on a 429, …).
1721        let mut json = page.json(debug);
1722        for (name, value) in res.headers() {
1723            if name != CONTENT_TYPE && name != CONTENT_LENGTH {
1724                json.headers_mut().insert(name.clone(), value.clone());
1725            }
1726        }
1727        return json;
1728    }
1729    let html = state
1730        .views
1731        .render_error(&page, debug, request_line, globals)
1732        .unwrap_or_else(|err| {
1733            tracing::error!(error = ?err, "could not render the error page");
1734            crate::error::error_page(page.status, page.shown_detail(debug))
1735        });
1736    with_html(res, html)
1737}
1738
1739fn with_html(mut res: Response, html: String) -> Response {
1740    let headers = res.headers_mut();
1741    headers.insert(
1742        CONTENT_TYPE,
1743        HeaderValue::from_static("text/html; charset=utf-8"),
1744    );
1745    headers.remove(CONTENT_LENGTH);
1746    *res.body_mut() = Body::from(html);
1747    res
1748}
1749
1750/// Flashed values; a key that wasn't flashed reads as `""`, so
1751/// `{{ flash.status }}` needs no `if`, even with strict templates.
1752#[derive(Debug)]
1753struct Flashed(serde_json::Map<String, serde_json::Value>);
1754
1755impl minijinja::value::Object for Flashed {
1756    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
1757        let key = key.as_str()?;
1758        Some(
1759            self.0
1760                .get(key)
1761                .map(Value::from_serialize)
1762                .unwrap_or_else(|| Value::from("")),
1763        )
1764    }
1765
1766    fn enumerate(self: &Arc<Self>) -> minijinja::value::Enumerator {
1767        minijinja::value::Enumerator::Values(
1768            self.0.keys().map(|k| Value::from(k.as_str())).collect(),
1769        )
1770    }
1771
1772    fn repr(self: &Arc<Self>) -> minijinja::value::ObjectRepr {
1773        minijinja::value::ObjectRepr::Map
1774    }
1775}
1776
1777/// Builds the menus `used` names for the request's user.
1778async fn request_menus(
1779    state: &AppState,
1780    current_user: Option<&CurrentUser>,
1781    locale: &str,
1782    route: Option<&str>,
1783    path: &str,
1784    used: crate::nav::MenusUsed,
1785) -> std::collections::HashMap<String, Vec<crate::nav::MenuGroup>> {
1786    if state.nav.menus.is_empty() || (used.names.is_empty() && !used.dynamic) {
1787        return Default::default();
1788    }
1789    let user = current_user.and_then(|c| crate::auth::auth_user_of(c, state));
1790    crate::nav::build_for_request(state, user.as_ref(), locale, route, path, &used).await
1791}
1792
1793/// What templates see of the request, besides the session and user.
1794struct Requested<'a> {
1795    path: &'a str,
1796    query: &'a str,
1797    /// The matched route's name, if it has one.
1798    route: Option<&'a str>,
1799    nonce: &'a str,
1800    /// Analytics events for this page's head.
1801    events: &'a [crate::analytics::Event],
1802}
1803
1804/// The templates' `t(key, name=…, count=…)` in `locale`.
1805pub(crate) fn translate_function(state: &AppState, locale: &str) -> Value {
1806    let translator = state.translator.clone();
1807    let (locale, fallback) = (locale.to_owned(), state.config.fallback_locale.clone());
1808    Value::from_function(
1809        move |key: String, kwargs: minijinja::value::Kwargs| -> Result<Value, minijinja::Error> {
1810            let mut params = Vec::new();
1811            let mut count = None;
1812            for name in kwargs.args() {
1813                let value: Value = kwargs.get(name)?;
1814                if name == "count" {
1815                    match i64::try_from(value.clone()) {
1816                        Ok(whole) => count = Some(whole),
1817                        // Not a whole number (a fraction, or text such as
1818                        // "1,204"): `:count` shows it as given, and a plural
1819                        // form is still picked by its value when it has one.
1820                        Err(_) => {
1821                            let shown = value.to_string();
1822                            let number = f64::try_from(value)
1823                                .ok()
1824                                .or_else(|| shown.trim().parse::<f64>().ok());
1825                            count = number.map(plural_count);
1826                            params.push((name.to_owned(), shown));
1827                        }
1828                    }
1829                } else {
1830                    params.push((name.to_owned(), value.to_string()));
1831                }
1832            }
1833            kwargs.assert_all_used()?;
1834            let params: Vec<(&str, String)> = params
1835                .iter()
1836                .map(|(k, v)| (k.as_str(), v.clone()))
1837                .collect();
1838            let text = translator.get(&locale, &fallback, &key);
1839            Ok(Value::from(crate::i18n::format(&text, &params, count)))
1840        },
1841    )
1842}
1843
1844/// The count a number stands for when picking a plural form: one only for
1845/// exactly 1 (so 1.5 or 0.5 kilos are plural), else the nearest whole one
1846/// (for ranges such as `[2,5]`).
1847fn plural_count(number: f64) -> i64 {
1848    if number == 1.0 {
1849        1
1850    } else {
1851        match number.round() as i64 {
1852            1 => 2,
1853            other => other,
1854        }
1855    }
1856}
1857
1858fn globals(
1859    state: &AppState,
1860    session: Option<&Session>,
1861    current_user: Option<CurrentUser>,
1862    htmx: &Htmx,
1863    requested: &Requested,
1864    locale: &str,
1865    menus: std::collections::HashMap<String, Vec<crate::nav::MenuGroup>>,
1866) -> Value {
1867    let config = &state.config;
1868    let token = session.map(Session::token).unwrap_or_default();
1869
1870    let strict = state.security.mode == crate::CspMode::Strict;
1871    let head = Value::from_safe_string(format!(
1872        "{}\n{}",
1873        assets::head_tags(&token, state.live.is_some(), strict),
1874        crate::seo::head_tags(&state.config, requested.nonce, requested.events)
1875    ));
1876    let seo = {
1877        let (config, path, locale) = (
1878            state.config.clone(),
1879            requested.path.to_owned(),
1880            locale.to_owned(),
1881        );
1882        Value::from_function(
1883            move |kwargs: minijinja::value::Kwargs| -> Result<Value, minijinja::Error> {
1884                crate::seo::tags(&config, &path, &locale, &kwargs).map(Value::from_safe_string)
1885            },
1886        )
1887    };
1888    let nonce = requested.nonce.to_owned();
1889    // `<rx-pwa/>`: the manifest link, colours, icon and registration script
1890    // (with the CSP nonce); nothing without `App::pwa`.
1891    let pwa = Value::from_safe_string(
1892        state
1893            .pwa
1894            .as_ref()
1895            .map(|pwa| pwa.head_tags(requested.nonce))
1896            .unwrap_or_default(),
1897    );
1898    let field = Value::from_safe_string(format!(
1899        "<input type=\"hidden\" name=\"{}\" value=\"{token}\">",
1900        crate::csrf::CSRF_FIELD
1901    ));
1902    let old_input = session.cloned();
1903    let has_old = session.is_some_and(Session::has_old_input);
1904    let toast_session = session.cloned();
1905    let toast_texts = crate::toast::RegionTexts {
1906        dismiss: state
1907            .translator
1908            .get(locale, &state.config.fallback_locale, "ui.dismiss"),
1909        failed: state
1910            .translator
1911            .get(locale, &state.config.fallback_locale, "ui.request_failed"),
1912    };
1913    let seen = std::sync::Mutex::new(std::collections::HashSet::<String>::new());
1914    let user = current_user.as_ref().and_then(|c| c.user.clone());
1915    let roles = current_user
1916        .as_ref()
1917        .map(|c| c.grants.roles())
1918        .unwrap_or_default();
1919    let gate_user = current_user.and_then(|c| Some((c.user?, c.gates, c.grants)));
1920    // Errors flashed in a named bag (`Validate::ERROR_BAG`) are shown only
1921    // by `error(field, bag=…)` and `errors_in(bag)`.
1922    let error_bag = session.and_then(Session::error_bag);
1923    let flashed_errors = match (session, &error_bag) {
1924        (Some(session), Some(bag)) => session.errors_in(bag),
1925        (Some(session), None) => session.errors(),
1926        (None, _) => Default::default(),
1927    };
1928    let errors = if error_bag.is_none() {
1929        flashed_errors.clone()
1930    } else {
1931        Default::default()
1932    };
1933    let first_errors: std::collections::BTreeMap<String, String> = flashed_errors
1934        .iter()
1935        .filter_map(|(field, messages)| {
1936            messages
1937                .get(0)
1938                .and_then(|m| m.as_str())
1939                .map(|m| (field.clone(), m.to_owned()))
1940        })
1941        .collect();
1942
1943    context! {
1944        app => context! {
1945            name => config.name,
1946            env => format!("{:?}", config.env).to_lowercase(),
1947            debug => config.debug,
1948            url => config.url,
1949            locale => locale,
1950            dir => state.direction(locale).as_str(),
1951            currency => config.currency,
1952        },
1953        auth => context! {
1954            check => user.is_some(),
1955            user => user.as_deref(),
1956            roles => roles,
1957        },
1958        t => translate_function(state, locale),
1959        // `can('admin')` asks a gate; `can('update', product)` reads the
1960        // abilities `auth::Can` attached to the model in the handler.
1961        can => Value::from_function(move |ability: String, target: Option<Value>| {
1962            match target {
1963                Some(target) => target
1964                    .get_attr("_can")
1965                    .and_then(|can| can.get_attr(&ability))
1966                    .is_ok_and(|allowed| allowed.is_true()),
1967                None => gate_user
1968                    .as_ref()
1969                    .is_some_and(|(user, gates, grants)| gates.check(user, grants, &ability)),
1970            }
1971        }),
1972        request => context! {
1973            path => requested.path,
1974            query => requested.query,
1975            route => requested.route,
1976            htmx => htmx.request,
1977            boosted => htmx.boosted,
1978        },
1979        // `route_is('admin.*')`, `route_is('products.index', 'products.show')`.
1980        route_is => {
1981            let route = requested.route.map(str::to_owned);
1982            Value::from_function(move |patterns: minijinja::value::Rest<String>| {
1983                route.as_deref().is_some_and(|name| {
1984                    patterns
1985                        .iter()
1986                        .any(|pattern| crate::routing::route_name_matches(name, pattern))
1987                })
1988            })
1989        },
1990        // `nav('staff')`: the groups of a menu the app's modules contributed
1991        // to, for this request's user (built before rendering, only for the
1992        // menus the page's templates name).
1993        nav => Value::from_function(move |menu: String| {
1994            Value::from_serialize(menus.get(&menu).map(Vec::as_slice).unwrap_or_default())
1995        }),
1996        csrf_token => token,
1997        flash => Value::from_object(Flashed(session.map(Session::flashed).unwrap_or_default())),
1998        errors => errors,
1999        // `errors_in('login')`: every error of a named bag.
2000        errors_in => {
2001            let bag = error_bag.clone();
2002            Value::from_function(move |name: String| {
2003                if bag.as_deref() == Some(name.as_str()) {
2004                    Value::from_serialize(&flashed_errors)
2005                } else {
2006                    Value::from_serialize(serde_json::Map::new())
2007                }
2008            })
2009        },
2010        // `error('photos')` also shows the first error of an item (`photos.1`);
2011        // `error('email', bag='login')` reads a named bag.
2012        error => Value::from_function(move |field: String, kwargs: minijinja::value::Kwargs| {
2013            let bag: Option<String> = kwargs.get("bag")?;
2014            kwargs.assert_all_used()?;
2015            if bag != error_bag {
2016                return Ok::<_, minijinja::Error>(String::new());
2017            }
2018            // `items[0][name]`'s errors are keyed `items.0.name`.
2019            // Custom fields are keyed as they are named (`extra[passport_no]`).
2020            let raw = field.clone();
2021            let field = crate::validation::nested::normalize(&field);
2022            Ok(first_errors
2023                .get(&raw)
2024                .or_else(|| first_errors.get(&field))
2025                .or_else(|| {
2026                    let prefix = format!("{field}.");
2027                    first_errors
2028                        .iter()
2029                        .find(|(key, _)| key.starts_with(&prefix))
2030                        .map(|(_, message)| message)
2031                })
2032                .cloned()
2033                .unwrap_or_default())
2034        }),
2035        renox_head => Value::from_function(move || head.clone()),
2036        renox_pwa => Value::from_function(move || pwa.clone()),
2037        seo => seo,
2038        csp_nonce => Value::from_function(move || nonce.clone()),
2039        csrf_field => Value::from_function(move || field.clone()),
2040        // `{{ toasts() }}`: the toast region, with the toasts waiting for
2041        // this page (taken from the session: shown once).
2042        // `toasts(position="bottom-end")` moves them (see toast::POSITIONS).
2043        toasts => Value::from_function(move |kwargs: minijinja::value::Kwargs| {
2044            let position: Option<String> = kwargs.get("position")?;
2045            kwargs.assert_all_used()?;
2046            let waiting: Vec<crate::Toast> = toast_session
2047                .as_ref()
2048                .and_then(|s| s.pull(crate::toast::SESSION_KEY))
2049                .unwrap_or_default();
2050            Ok::<_, minijinja::Error>(Value::from_safe_string(crate::toast::region(
2051                &waiting,
2052                &toast_texts,
2053                position.as_deref().unwrap_or("top"),
2054            )))
2055        }),
2056        // `{% if once('date-picker') %}…{% endif %}`: true the first time a key
2057        // is asked for on a page, e.g. for a component's script.
2058        once => Value::from_function(move |key: String| {
2059            seen.lock().unwrap_or_else(|e| e.into_inner()).insert(key)
2060        }),
2061        // `has_old()`: the previous request was a failed submit, so a field
2062        // missing from `old()` was sent empty (an unticked checkbox).
2063        has_old => Value::from_function(move || has_old),
2064        old => Value::from_function(move |field: String, default: Option<Value>| {
2065            old_input
2066                .as_ref()
2067                .and_then(|s| s.old(&field))
2068                .map(Value::from_serialize)
2069                .or(default)
2070                .unwrap_or_else(|| Value::from(""))
2071        }),
2072    }
2073}
2074
2075#[cfg(test)]
2076mod tests {
2077    use super::*;
2078
2079    fn views_in(dir: &Path) -> Views {
2080        let config = Config {
2081            views_path: dir.to_path_buf(),
2082            ..Config::default()
2083        };
2084        Views::new(
2085            &config,
2086            Arc::new(RouteTable::default()),
2087            Storage::from_config(&config).unwrap(),
2088            None,
2089            Arc::new(Vec::new()),
2090            Arc::new(Vec::new()),
2091            config.timezone,
2092            Arc::new(crate::embedded::AssetVersions::new(dir, None)),
2093        )
2094    }
2095
2096    #[test]
2097    fn check_finds_every_broken_template_with_its_line() {
2098        let dir = tempfile::tempdir().unwrap();
2099        let write = |name: &str, body: &str| {
2100            let path = dir.path().join(name);
2101            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2102            std::fs::write(path, body).unwrap();
2103        };
2104        write("good.html", "<h1>{{ 1 + 1 }}</h1>");
2105        write("sub/typo.html", "<p>x</p>\n<rx-tabel>y</rx-tabel>\n");
2106        write("bad.html", "a\nb\n{% if x %}\nc\n");
2107        write(".hidden.html", "{% if %}");
2108        write("notes.md", "{% if %}");
2109        let views = views_in(dir.path());
2110
2111        let names = views.names();
2112        assert!(names.contains(&"good.html".to_owned()));
2113        assert!(names.contains(&"sub/typo.html".to_owned()));
2114        assert!(names.contains(&"renox/error.html".to_owned()));
2115        assert!(
2116            !names
2117                .iter()
2118                .any(|n| n.contains("hidden") || n.ends_with(".md"))
2119        );
2120        assert!(names.windows(2).all(|w| w[0] < w[1]));
2121
2122        let problems = views.check(&RouteTable::default());
2123        assert_eq!(problems.len(), 2, "{problems:?}");
2124        assert_eq!(problems[0].template, "bad.html");
2125        assert!(problems[0].line.is_some_and(|l| l >= 3), "{problems:?}");
2126        assert_eq!(problems[1].template, "sub/typo.html");
2127        assert_eq!(problems[1].line, Some(2));
2128        assert!(problems[1].message.contains("rx-tabel"), "{problems:?}");
2129        assert!(
2130            problems[1]
2131                .to_string()
2132                .starts_with("sub/typo.html:2: unknown component"),
2133        );
2134    }
2135
2136    #[test]
2137    fn check_reports_unknown_route_names_with_a_suggestion() {
2138        let dir = tempfile::tempdir().unwrap();
2139        std::fs::write(
2140            dir.path().join("p.html"),
2141            "<a href=\"{{ route('products.index') }}\">ok</a>\n\
2142             <a href=\"{{ route('products.indx') }}\">typo</a>\n\
2143             <a href=\"{{ route('shop.home') }}\">domain</a>\n\
2144             <a href=\"{{ route('nothing.like.it') }}\">far</a>\n",
2145        )
2146        .unwrap();
2147        let mut routes = RouteTable::default();
2148        routes
2149            .insert("products.index".into(), "/products".into())
2150            .unwrap();
2151        // A route defined inside `Routes::domain` is in the table as well.
2152        routes.insert("shop.home".into(), "/".into()).unwrap();
2153        routes.set_domain("shop.home", "shop.example.com");
2154        let problems = views_in(dir.path()).check(&routes);
2155        assert_eq!(problems.len(), 2, "{problems:?}");
2156        assert_eq!(problems[0].line, Some(2));
2157        assert_eq!(
2158            problems[0].to_string(),
2159            "p.html:2: unknown route \"products.indx\"; did you mean \"products.index\"?"
2160        );
2161        assert_eq!(problems[1].line, Some(4));
2162        assert!(!problems[1].message.contains("did you mean"));
2163    }
2164
2165    fn env() -> Environment<'static> {
2166        let mut env = Environment::new();
2167        for name in REQUEST_GLOBALS {
2168            env.add_global(*name, Value::from_object(RequestGlobal(name)));
2169        }
2170        env
2171    }
2172
2173    /// A template rendered while a page renders (a component a Rust
2174    /// template function renders, say) reads the page's request values
2175    /// through the `RequestGlobal`s; outside a page they are empty.
2176    #[test]
2177    fn request_globals_read_the_page_being_rendered() {
2178        let env = env();
2179        let page = "{% if auth %}[{{ auth.name }}]{% endif %}\
2180                    {% for key in flash %}{{ key }}={{ flash[key] }};{% endfor %}\
2181                    {{ t('hi') }}|{{ request }}|{% for e in errors %}{{ e }}{% endfor %}.";
2182
2183        let outside = env
2184            .render_str(
2185                "{% if auth %}in{% endif %}[{{ request }}]{% for k in flash %}{{ k }}{% endfor %}",
2186                (),
2187            )
2188            .unwrap();
2189        assert_eq!(outside, "[]");
2190        let err = env.render_str("{{ t('hi') }}", ()).unwrap_err();
2191        assert!(
2192            err.to_string()
2193                .contains("`t` is only available while rendering a page"),
2194            "{err}"
2195        );
2196
2197        let globals = minijinja::context! {
2198            auth => minijinja::context! { name => "Ann" },
2199            flash => minijinja::context! { status => "Saved" },
2200            t => Value::from_function(|key: String| format!("({key})")),
2201            request => "GET /",
2202            // A list: not a map, so it lists no keys.
2203            errors => vec!["a"],
2204        };
2205        let current = CurrentGlobals::set(globals);
2206        assert_eq!(
2207            env.render_str(page, ()).unwrap(),
2208            "[Ann]status=Saved;(hi)|GET /|."
2209        );
2210        drop(current);
2211        assert_eq!(env.render_str("{{ request }}", ()).unwrap(), "");
2212    }
2213}