Skip to main content

tablo_core/panel/
extension.rs

1//! What a crate that extends panels registers beside the app's own declarations: the hooks auth
2//! runs, the models its writes need, and its catalogs.
3
4use super::Panel;
5use crate::{AuthHook, auth::hook};
6
7impl Panel {
8    /// Runs the [`AuthHook`] `H` inside the transaction of each [`AuthEvent`](crate::AuthEvent)
9    /// of the panel: a sign-in, a refused one, a sign-out, a change of credentials, address or
10    /// second factor, a start or stop of impersonation. Several hooks run in the order they are
11    /// registered; registering `H` again changes nothing, so it never runs twice.
12    #[must_use]
13    pub fn auth_hook<H: AuthHook>(mut self) -> Self {
14        let id = std::any::TypeId::of::<H>();
15        if !self.auth_hooks.iter().any(|(hook, _)| *hook == id) {
16            self.auth_hooks.push((id, hook::erased::<H>));
17        }
18        self
19    }
20
21    /// Refuses to mount the panel over a `Db` that does not register the model `M`
22    /// ([`UnregisteredModel`](crate::DeclarationErrorKind::UnregisteredModel)), for a hook that
23    /// writes `M` on every request: without it, each write would fail as it commits.
24    #[must_use]
25    pub fn require_model<M: toasty::schema::Model>(mut self) -> Self {
26        let model = M::schema().name().upper_camel_case();
27        if !self.required_models.contains(&model) {
28            self.required_models.push(model);
29        }
30        self
31    }
32
33    /// Adds a catalog for `locale` under Tablo's and the app's
34    /// [`translations`](Self::translations): a crate that extends panels ships the messages its
35    /// [`Text`](crate::Text)s name through it, in every language it has, and rewords none of
36    /// Tablo's. Adding the same catalog again changes nothing.
37    ///
38    /// A catalog for a locale the panel does not offer is left out, where
39    /// [`translations`](Self::translations) refuses it: the app picks the locales, the crate
40    /// does not. A message both this catalog and the app's hold reads as the app's.
41    ///
42    /// ```rust,ignore
43    /// panel
44    ///     .default_translations(locale!("en"), include_str!("../locales/en.ftl"))
45    ///     .default_translations(locale!("fr"), include_str!("../locales/fr.ftl"))
46    /// ```
47    #[must_use]
48    pub fn default_translations(
49        mut self,
50        locale: topcoat::l10n::Locale,
51        catalog: impl Into<String>,
52    ) -> Self {
53        let catalog = (locale, catalog.into());
54        if !self.default_translations.contains(&catalog) {
55            self.default_translations.push(catalog);
56        }
57        self
58    }
59}