✨ (auth): Añade idioma y tema preferidos al usuario
- CurrentUser pasa de enum a struct con `id` opcional (anónimo = None) y preferencias de idioma, zona horaria y tema validadas en `with_*()`. - `RequestLocale` tiene en cuenta el idioma preferido del usuario, y Context usa su tema si lo tiene (`default_theme()` en otro caso). - Nuevos componentes `form::SelectLanguage`, `form::SelectTheme` y `form::SelectTimezone`, con `Timezone::supported_by_region()` para listar y validar las zonas IANA ofrecidas.
This commit is contained in:
parent
35f2b66161
commit
70744a51a5
25 changed files with 1162 additions and 190 deletions
|
|
@ -1,8 +1,7 @@
|
|||
use crate::auth::CurrentUser;
|
||||
use crate::core::TypeInfo;
|
||||
use crate::core::component::{ChildOp, Component, MessageLevel, StatusMessage};
|
||||
use crate::core::theme::all::DEFAULT_THEME;
|
||||
use crate::core::theme::{ChildrenInRegions, CoreRegions, CoreTemplates};
|
||||
use crate::core::theme::{ChildrenInRegions, CoreRegions, CoreTemplates, default_theme};
|
||||
use crate::core::theme::{RegionRef, TemplateRef, ThemeRef};
|
||||
use crate::datetime::Tz;
|
||||
use crate::html::{Assets, Favicon, JavaScript, Preload, ResponsiveStyles, StyleSheet};
|
||||
|
|
@ -32,7 +31,7 @@ pub use contextual::Contextual;
|
|||
/// [`Page::new()`](crate::response::Page::new) o [`Page::admin()`](crate::response::Page::admin)),
|
||||
/// y es la única vía por la que un componente, una acción o el tema activo conocen: la petición
|
||||
/// HTTP de origen, el idioma negociado y la zona horaria efectiva, el usuario autenticado
|
||||
/// ([`current_user()`](Contextual::current_user)), la plantilla y el tema en uso, y los recursos
|
||||
/// ([`current_user()`](Contextual::current_user)), el tema y la plantilla en uso, y los recursos
|
||||
/// (favicon, hojas de estilo, scripts) acumulados hasta ese momento. Otros datos que los
|
||||
/// componentes necesiten durante el renderizado pueden ser parámetros dinámicos tipados con
|
||||
/// [`with_param()`](Contextual::with_param)/[`param()`](Contextual::param).
|
||||
|
|
@ -99,8 +98,8 @@ pub struct Context {
|
|||
locale : RequestLocale, // Idioma asociado a la petición.
|
||||
current_user: CurrentUser, // Identidad del usuario actual.
|
||||
timezone : Tz, // Zona horaria efectiva del documento.
|
||||
template : TemplateRef, // Plantilla usada para renderizar.
|
||||
theme : ThemeRef, // Referencia al tema usado para renderizar.
|
||||
template : TemplateRef, // Plantilla usada para renderizar.
|
||||
favicon : Option<Favicon>, // Favicon, si se ha definido.
|
||||
preloads : Assets<Preload>, // Recursos para precarga.
|
||||
stylesheets : Assets<StyleSheet>, // Hojas de estilo CSS.
|
||||
|
|
@ -129,13 +128,14 @@ impl Context {
|
|||
let locale = RequestLocale::from_request(request.as_ref());
|
||||
let current_user = Self::resolve_current_user(request.as_ref());
|
||||
let timezone = current_user.timezone();
|
||||
let theme = current_user.theme().unwrap_or_else(default_theme);
|
||||
Context {
|
||||
request,
|
||||
locale,
|
||||
current_user,
|
||||
timezone,
|
||||
theme,
|
||||
template,
|
||||
theme : *DEFAULT_THEME,
|
||||
favicon : None,
|
||||
preloads : Assets::<Preload>::new(),
|
||||
stylesheets: Assets::<StyleSheet>::new(),
|
||||
|
|
@ -169,12 +169,12 @@ impl Context {
|
|||
}
|
||||
|
||||
// Extrae el `CurrentUser` inyectado por middleware en las extensiones de la petición, o
|
||||
// `CurrentUser::Anonymous` si no hay petición o ninguna extensión de autenticación está activa.
|
||||
// un usuario anónimo si no hay petición o ninguna extensión de autenticación está activa.
|
||||
fn resolve_current_user(request: Option<&HttpRequest>) -> CurrentUser {
|
||||
request
|
||||
.and_then(|r| r.extension::<CurrentUser>())
|
||||
.cloned()
|
||||
.unwrap_or(CurrentUser::Anonymous)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// **< Context RENDER >*************************************************************************
|
||||
|
|
@ -320,8 +320,9 @@ impl Context {
|
|||
|
||||
/// Permite a [`Context`] actuar como proveedor de idioma.
|
||||
///
|
||||
/// Internamente delega en [`RequestLocale`], que tiene en cuenta la petición HTTP, la configuración
|
||||
/// global de idioma de la aplicación, la cabecera `Accept-Language` y/o el idioma de respaldo.
|
||||
/// Internamente delega en [`RequestLocale`], que tiene en cuenta la petición HTTP (parámetro
|
||||
/// `?lang` e idioma preferido del usuario), la configuración global de idioma de la aplicación, la
|
||||
/// cabecera `Accept-Language` y/o el idioma de respaldo.
|
||||
///
|
||||
/// Todo ello según la negociación indicada en [`global::SETTINGS.app.lang_negotiation`]. Esto
|
||||
/// permite que el [`Context`] se use como fuente de idioma coherente en [`Lc::lookup()`] o
|
||||
|
|
@ -344,11 +345,12 @@ impl Contextual for Context {
|
|||
|
||||
fn with_request(mut self, request: Option<HttpRequest>) -> Self {
|
||||
self.request = request;
|
||||
// Recalcula el *locale*, el usuario actual y la zona horaria según la nueva petición y la
|
||||
// política de negociación configurada.
|
||||
// Recalcula el *locale*, el usuario actual, la zona horaria y el tema según la nueva
|
||||
// petición y la política de negociación configurada.
|
||||
self.locale = RequestLocale::from_request(self.request.as_ref());
|
||||
self.current_user = Self::resolve_current_user(self.request.as_ref());
|
||||
self.timezone = self.current_user.timezone();
|
||||
self.theme = self.current_user.theme().unwrap_or_else(default_theme);
|
||||
self
|
||||
}
|
||||
|
||||
|
|
@ -362,13 +364,13 @@ impl Contextual for Context {
|
|||
self
|
||||
}
|
||||
|
||||
fn with_template(mut self, template: TemplateRef) -> Self {
|
||||
self.template = template;
|
||||
fn with_theme(mut self, theme: ThemeRef) -> Self {
|
||||
self.theme = theme;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_theme(mut self, theme: ThemeRef) -> Self {
|
||||
self.theme = theme;
|
||||
fn with_template(mut self, template: TemplateRef) -> Self {
|
||||
self.template = template;
|
||||
self
|
||||
}
|
||||
|
||||
|
|
@ -452,14 +454,14 @@ impl Contextual for Context {
|
|||
self.timezone
|
||||
}
|
||||
|
||||
fn template(&self) -> TemplateRef {
|
||||
self.template
|
||||
}
|
||||
|
||||
fn theme(&self) -> ThemeRef {
|
||||
self.theme
|
||||
}
|
||||
|
||||
fn template(&self) -> TemplateRef {
|
||||
self.template
|
||||
}
|
||||
|
||||
fn param<T: 'static>(&self, key: &'static str) -> Result<&T, ContextError> {
|
||||
let (any, type_name) = self.params.get(key).ok_or(ContextError::ParamNotFound)?;
|
||||
any.downcast_ref::<T>()
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ const ISO_DATETIME: &str = "%Y-%m-%dT%H:%M:%S%:z";
|
|||
/// - Almacenar la **petición HTTP** de origen.
|
||||
/// - Conocer la **identidad del usuario actual** ([`current_user()`](Self::current_user)) y la
|
||||
/// **zona horaria efectiva** del documento ([`timezone()`](Self::timezone)).
|
||||
/// - Seleccionar la **plantilla** y el **tema** de renderizado.
|
||||
/// - Seleccionar el **tema** y la **plantilla** de renderizado.
|
||||
/// - Administrar **recursos** del documento como el icono [`Favicon`], las hojas de estilo
|
||||
/// [`StyleSheet`] o los scripts [`JavaScript`], directamente o mediante una operación
|
||||
/// [`AssetsOp`].
|
||||
|
|
@ -40,8 +40,8 @@ const ISO_DATETIME: &str = "%Y-%m-%dT%H:%M:%S%:z";
|
|||
/// # use pagetop_aliner::Aliner;
|
||||
/// fn prepare_context<C: Contextual>(cx: C) -> C {
|
||||
/// cx.with_langid(&Locale::resolve("es-ES"))
|
||||
/// .with_template(&CoreTemplates::Standard)
|
||||
/// .with_theme(&Aliner)
|
||||
/// .with_template(&CoreTemplates::Standard)
|
||||
/// .with_assets(Favicon::new().with_icon("/favicon.ico"))
|
||||
/// .with_assets(StyleSheet::from("/css/app.css"))
|
||||
/// .with_assets(JavaScript::defer("/js/app.js"))
|
||||
|
|
@ -67,22 +67,24 @@ pub trait Contextual: LangId {
|
|||
///
|
||||
/// Al asociar la petición, recalcula el idioma ([`RequestLocale::from_request()`]), establece
|
||||
/// el usuario actual ([`current_user()`]) y, a partir de éste, asigna la zona horaria efectiva
|
||||
/// ([`timezone()`]), descartando en el proceso cualquier idioma o zona horaria anteriores.
|
||||
/// ([`timezone()`]) y el tema ([`theme()`]), descartando en el proceso cualquier idioma, zona
|
||||
/// horaria o tema anteriores.
|
||||
///
|
||||
/// Si sabes que vas a forzar el idioma o la zona horaria, llama a `with_request()` primero en
|
||||
/// la cadena de construcción, nunca después.
|
||||
/// Si sabes que vas a forzar el idioma, la zona horaria o el tema, llama a `with_request()`
|
||||
/// primero en la cadena de construcción, nunca después.
|
||||
///
|
||||
/// [`RequestLocale::from_request()`]: crate::locale::RequestLocale::from_request
|
||||
/// [`current_user()`]: Self::current_user
|
||||
/// [`timezone()`]: Self::timezone
|
||||
/// [`theme()`]: Self::theme
|
||||
fn with_request(self, request: Option<HttpRequest>) -> Self;
|
||||
|
||||
/// Especifica la plantilla para renderizar el documento.
|
||||
fn with_template(self, template: TemplateRef) -> Self;
|
||||
|
||||
/// Especifica el tema para renderizar el documento.
|
||||
fn with_theme(self, theme: ThemeRef) -> Self;
|
||||
|
||||
/// Especifica la plantilla para renderizar el documento.
|
||||
fn with_template(self, template: TemplateRef) -> Self;
|
||||
|
||||
/// Añade o modifica un parámetro dinámico del contexto.
|
||||
///
|
||||
/// El valor se almacena junto con el nombre de su tipo, lo que permite generar mensajes de
|
||||
|
|
@ -125,7 +127,7 @@ pub trait Contextual: LangId {
|
|||
///
|
||||
/// Si ninguna extensión de autenticación ha inyectado un
|
||||
/// [`CurrentUser`](crate::auth::CurrentUser) en las extensiones de la petición HTTP, devuelve
|
||||
/// `&CurrentUser::Anonymous`.
|
||||
/// un usuario anónimo ([`CurrentUser::anonymous()`](crate::auth::CurrentUser::anonymous)).
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
|
|
@ -154,12 +156,12 @@ pub trait Contextual: LangId {
|
|||
/// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
||||
fn timezone(&self) -> Tz;
|
||||
|
||||
/// Devuelve la plantilla configurada para renderizar el documento.
|
||||
fn template(&self) -> TemplateRef;
|
||||
|
||||
/// Devuelve el tema que se usará para renderizar el documento.
|
||||
fn theme(&self) -> ThemeRef;
|
||||
|
||||
/// Devuelve la plantilla configurada para renderizar el documento.
|
||||
fn template(&self) -> TemplateRef;
|
||||
|
||||
/// Recupera una *referencia tipada* al parámetro solicitado.
|
||||
///
|
||||
/// Devuelve:
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use crate::core::action::publish_actions;
|
||||
use crate::core::extension::ExtensionRef;
|
||||
use crate::core::theme::ThemeRef;
|
||||
use crate::core::theme::all::THEMES;
|
||||
use crate::core::theme::all::register_theme;
|
||||
use crate::web::Router;
|
||||
use crate::{global, serve_static_files, trace, web};
|
||||
|
||||
|
|
@ -47,14 +47,7 @@ fn add_to_enabled(list: &mut Vec<ExtensionRef>, extension: ExtensionRef) {
|
|||
// Comprueba si la extensión tiene un tema asociado que deba registrarse.
|
||||
if let Some(theme) = extension.theme() {
|
||||
check_theme_parent_chain(theme);
|
||||
|
||||
let mut registered_themes = THEMES.write();
|
||||
// Asegura que el tema no esté ya registrado para evitar duplicados.
|
||||
if !registered_themes
|
||||
.iter()
|
||||
.any(|t| t.type_id() == theme.type_id())
|
||||
{
|
||||
registered_themes.push(theme);
|
||||
if register_theme(theme) {
|
||||
trace::debug!("Enabling \"{}\" theme", theme.short_name());
|
||||
}
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -170,3 +170,4 @@ pub(crate) use regions::ChildrenInRegions;
|
|||
pub use regions::InRegion;
|
||||
|
||||
pub(crate) mod all;
|
||||
pub use all::{default_theme, enabled_themes, theme_by_short_name};
|
||||
|
|
|
|||
|
|
@ -7,27 +7,50 @@ use std::sync::LazyLock;
|
|||
|
||||
// **< TEMAS >**************************************************************************************
|
||||
|
||||
pub static THEMES: LazyLock<RwLock<Vec<ThemeRef>>> = LazyLock::new(|| RwLock::new(Vec::new()));
|
||||
static THEMES: LazyLock<RwLock<Vec<ThemeRef>>> = LazyLock::new(|| RwLock::new(Vec::new()));
|
||||
|
||||
// Registra el tema si no lo estaba ya, para evitar duplicados. Devuelve `true` si lo ha añadido.
|
||||
pub(crate) fn register_theme(theme: ThemeRef) -> bool {
|
||||
let mut themes = THEMES.write();
|
||||
if themes.iter().any(|t| t.type_id() == theme.type_id()) {
|
||||
return false;
|
||||
}
|
||||
themes.push(theme);
|
||||
true
|
||||
}
|
||||
|
||||
/// Devuelve los temas habilitados en la aplicación, en el orden en que se registraron.
|
||||
pub fn enabled_themes() -> Vec<ThemeRef> {
|
||||
THEMES.read().clone()
|
||||
}
|
||||
|
||||
/// Devuelve el tema identificado por su [`short_name()`](crate::core::AnyInfo::short_name), si está
|
||||
/// habilitado, sin distinguir mayúsculas y minúsculas.
|
||||
pub fn theme_by_short_name(short_name: &str) -> Option<ThemeRef> {
|
||||
THEMES
|
||||
.read()
|
||||
.iter()
|
||||
.find(|t| t.short_name().eq_ignore_ascii_case(short_name))
|
||||
.copied()
|
||||
}
|
||||
|
||||
// **< TEMA PREDETERMINADO >************************************************************************
|
||||
|
||||
pub static DEFAULT_THEME: LazyLock<ThemeRef> =
|
||||
static DEFAULT_THEME: LazyLock<ThemeRef> =
|
||||
LazyLock::new(|| match theme_by_short_name(&global::SETTINGS.app.theme) {
|
||||
Some(theme) => theme,
|
||||
None => &crate::base::theme::Basic,
|
||||
});
|
||||
|
||||
// **< TEMA POR NOMBRE >****************************************************************************
|
||||
|
||||
/// Devuelve el tema identificado por su [`short_name()`](AnyInfo::short_name).
|
||||
pub fn theme_by_short_name(short_name: &'static str) -> Option<ThemeRef> {
|
||||
let short_name = short_name.to_lowercase();
|
||||
match THEMES
|
||||
.read()
|
||||
.iter()
|
||||
.find(|t| t.short_name().to_lowercase() == short_name)
|
||||
{
|
||||
Some(theme) => Some(*theme),
|
||||
_ => None,
|
||||
}
|
||||
/// Devuelve el tema predeterminado de la aplicación: el configurado en `app.theme` si está
|
||||
/// habilitado o, en otro caso, [`Basic`](crate::base::theme::Basic).
|
||||
///
|
||||
/// Es el tema del sitio, no necesariamente el que se usa en una petición concreta: para renderizar,
|
||||
/// el tema efectivo es el de [`Contextual::theme()`], que tiene en cuenta el tema preferido del
|
||||
/// usuario ([`CurrentUser::theme()`]).
|
||||
///
|
||||
/// [`Contextual::theme()`]: crate::core::component::Contextual::theme
|
||||
/// [`CurrentUser::theme()`]: crate::auth::CurrentUser::theme
|
||||
pub fn default_theme() -> ThemeRef {
|
||||
*DEFAULT_THEME
|
||||
}
|
||||
|
|
|
|||
|
|
@ -431,6 +431,12 @@ pub trait Theme: Extension + Send + Sync {
|
|||
/// Referencia estática a un tema.
|
||||
pub type ThemeRef = &'static dyn Theme;
|
||||
|
||||
impl std::fmt::Debug for dyn Theme {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.short_name())
|
||||
}
|
||||
}
|
||||
|
||||
// **< setup_component! >***************************************************************************
|
||||
|
||||
/// Modifica un componente dentro de [`Theme::setup_component()`].
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue