Compare commits
No commits in common. "430ecada413cbb98b0e0f84e69d36f4fd5b569fb" and "d8ae452ec209027f1ca6e83d4df0a25da8cf8a52" have entirely different histories.
430ecada41
...
d8ae452ec2
3 changed files with 93 additions and 105 deletions
|
@ -103,16 +103,32 @@ pub fn builder_fn(_: TokenStream, item: TokenStream) -> TokenStream {
|
||||||
};
|
};
|
||||||
return expanded.into();
|
return expanded.into();
|
||||||
}
|
}
|
||||||
// Valida que el método es público.
|
// Valida que el método sea público.
|
||||||
if !matches!(fn_with.vis, syn::Visibility::Public(_)) {
|
if !matches!(fn_with.vis, syn::Visibility::Public(_)) {
|
||||||
return quote_spanned! {
|
return quote_spanned! {
|
||||||
fn_with.sig.ident.span() => compile_error!("expected method to be `pub`");
|
fn_with.sig.ident.span() => compile_error!("expected method to be `pub`");
|
||||||
}
|
}
|
||||||
.into();
|
.into();
|
||||||
}
|
}
|
||||||
// Valida que el primer argumento es exactamente `mut self`.
|
// Valida que el método devuelva el tipo `Self`.
|
||||||
|
if let syn::ReturnType::Type(_, ty) = &fn_with.sig.output {
|
||||||
|
if let syn::Type::Path(type_path) = &**ty {
|
||||||
|
let ident = &type_path.path.segments.last().unwrap().ident;
|
||||||
|
if ident != "Self" {
|
||||||
|
return quote_spanned! {
|
||||||
|
fn_with.sig.output.span() => compile_error!("expected return type to be `Self`");
|
||||||
|
}.into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return quote_spanned! {
|
||||||
|
fn_with.sig.output.span() => compile_error!("expected method to return `Self`");
|
||||||
|
}
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
// Valida que el primer argumento sea `mut self`.
|
||||||
if let Some(syn::FnArg::Receiver(receiver)) = fn_with.sig.inputs.first() {
|
if let Some(syn::FnArg::Receiver(receiver)) = fn_with.sig.inputs.first() {
|
||||||
if receiver.mutability.is_none() || receiver.reference.is_some() {
|
if receiver.mutability.is_none() {
|
||||||
return quote_spanned! {
|
return quote_spanned! {
|
||||||
receiver.span() => compile_error!("expected `mut self` as the first argument");
|
receiver.span() => compile_error!("expected `mut self` as the first argument");
|
||||||
}
|
}
|
||||||
|
@ -124,27 +140,6 @@ pub fn builder_fn(_: TokenStream, item: TokenStream) -> TokenStream {
|
||||||
}
|
}
|
||||||
.into();
|
.into();
|
||||||
}
|
}
|
||||||
// Valida que el método devuelve exactamente `Self`.
|
|
||||||
if let syn::ReturnType::Type(_, ty) = &fn_with.sig.output {
|
|
||||||
if let syn::Type::Path(type_path) = ty.as_ref() {
|
|
||||||
if type_path.qself.is_some() || !type_path.path.is_ident("Self") {
|
|
||||||
return quote_spanned! { ty.span() =>
|
|
||||||
compile_error!("expected return type to be exactly `Self`");
|
|
||||||
}
|
|
||||||
.into();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return quote_spanned! { ty.span() =>
|
|
||||||
compile_error!("expected return type to be exactly `Self`");
|
|
||||||
}
|
|
||||||
.into();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return quote_spanned! {
|
|
||||||
fn_with.sig.output.span() => compile_error!("expected method to return `Self`");
|
|
||||||
}
|
|
||||||
.into();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Genera el nombre del método alter_...().
|
// Genera el nombre del método alter_...().
|
||||||
let fn_alter_name_str = fn_with_name_str.replace("with_", "alter_");
|
let fn_alter_name_str = fn_with_name_str.replace("with_", "alter_");
|
||||||
|
|
|
@ -10,7 +10,7 @@ pub use assets::stylesheet::{StyleSheet, TargetMedia};
|
||||||
pub(crate) use assets::Assets;
|
pub(crate) use assets::Assets;
|
||||||
|
|
||||||
mod context;
|
mod context;
|
||||||
pub use context::{AssetsOp, Context, ErrorParam};
|
pub use context::{Context, ContextOp, ErrorParam};
|
||||||
|
|
||||||
mod opt_id;
|
mod opt_id;
|
||||||
pub use opt_id::OptionId;
|
pub use opt_id::OptionId;
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
use crate::core::theme::all::{theme_by_short_name, DEFAULT_THEME};
|
use crate::core::theme::all::{theme_by_short_name, DEFAULT_THEME};
|
||||||
use crate::core::theme::ThemeRef;
|
use crate::core::theme::ThemeRef;
|
||||||
use crate::core::TypeInfo;
|
use crate::core::TypeInfo;
|
||||||
use crate::html::{html, Markup};
|
use crate::html::{html, Markup, Render};
|
||||||
use crate::html::{Assets, Favicon, JavaScript, StyleSheet};
|
use crate::html::{Assets, Favicon, JavaScript, StyleSheet};
|
||||||
|
use crate::join;
|
||||||
use crate::locale::{LanguageIdentifier, DEFAULT_LANGID};
|
use crate::locale::{LanguageIdentifier, DEFAULT_LANGID};
|
||||||
use crate::service::HttpRequest;
|
use crate::service::HttpRequest;
|
||||||
use crate::{builder_fn, join};
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
@ -14,7 +14,17 @@ use std::str::FromStr;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
/// Operaciones para modificar el contexto ([`Context`]) del documento.
|
/// Operaciones para modificar el contexto ([`Context`]) del documento.
|
||||||
pub enum AssetsOp {
|
pub enum ContextOp {
|
||||||
|
/// Modifica el identificador de idioma del documento.
|
||||||
|
LangId(&'static LanguageIdentifier),
|
||||||
|
/// Establece el tema que se usará para renderizar el documento.
|
||||||
|
///
|
||||||
|
/// Localiza el tema por su [`short_name`](crate::core::AnyInfo::short_name), y si no aplica
|
||||||
|
/// ninguno entonces usará el tema por defecto.
|
||||||
|
Theme(&'static str),
|
||||||
|
/// Define el tipo de composición usado para renderizar el documento.
|
||||||
|
Layout(&'static str),
|
||||||
|
|
||||||
// Favicon.
|
// Favicon.
|
||||||
/// Define el *favicon* del documento. Sobrescribe cualquier valor anterior.
|
/// Define el *favicon* del documento. Sobrescribe cualquier valor anterior.
|
||||||
SetFavicon(Option<Favicon>),
|
SetFavicon(Option<Favicon>),
|
||||||
|
@ -66,35 +76,38 @@ impl Error for ErrorParam {}
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use pagetop::prelude::*;
|
/// use pagetop::prelude::*;
|
||||||
///
|
///
|
||||||
/// fn configure_context(cx: &mut Context) {
|
/// fn configure_context(mut cx: Context) {
|
||||||
/// // Establece el idioma del documento a español.
|
/// // Establece el idioma del documento a español.
|
||||||
/// cx.alter_langid(LangMatch::langid_or_default("es-ES"))
|
/// cx.alter_assets(ContextOp::LangId(
|
||||||
|
/// LangMatch::langid_or_default("es-ES")
|
||||||
|
/// ))
|
||||||
/// // Selecciona un tema (por su nombre corto).
|
/// // Selecciona un tema (por su nombre corto).
|
||||||
/// .alter_theme("aliner")
|
/// .alter_assets(ContextOp::Theme("aliner"))
|
||||||
/// // Añade un parámetro dinámico al contexto.
|
|
||||||
/// .alter_param("usuario_id", 42)
|
|
||||||
/// // Asigna un favicon.
|
/// // Asigna un favicon.
|
||||||
/// .alter_assets(AssetsOp::SetFavicon(Some(
|
/// .alter_assets(ContextOp::SetFavicon(Some(
|
||||||
/// Favicon::new().with_icon("/icons/favicon.ico")
|
/// Favicon::new().with_icon("/icons/favicon.ico")
|
||||||
/// )))
|
/// )))
|
||||||
/// // Añade una hoja de estilo externa.
|
/// // Añade una hoja de estilo externa.
|
||||||
/// .alter_assets(AssetsOp::AddStyleSheet(
|
/// .alter_assets(ContextOp::AddStyleSheet(
|
||||||
/// StyleSheet::from("/css/style.css")
|
/// StyleSheet::from("/css/style.css")
|
||||||
/// ))
|
/// ))
|
||||||
/// // Añade un script JavaScript.
|
/// // Añade un script JavaScript.
|
||||||
/// .alter_assets(AssetsOp::AddJavaScript(
|
/// .alter_assets(ContextOp::AddJavaScript(
|
||||||
/// JavaScript::defer("/js/main.js")
|
/// JavaScript::defer("/js/main.js")
|
||||||
/// ));
|
/// ));
|
||||||
///
|
///
|
||||||
|
/// // Añade un parámetro dinámico al contexto.
|
||||||
|
/// cx.set_param("usuario_id", 42);
|
||||||
|
///
|
||||||
|
/// // Recupera el parámetro y lo convierte a su tipo original.
|
||||||
|
/// let id: i32 = cx.get_param("usuario_id").unwrap();
|
||||||
|
/// assert_eq!(id, 42);
|
||||||
|
///
|
||||||
/// // Recupera el tema seleccionado.
|
/// // Recupera el tema seleccionado.
|
||||||
/// let active_theme = cx.theme();
|
/// let active_theme = cx.theme();
|
||||||
/// assert_eq!(active_theme.short_name(), "aliner");
|
/// assert_eq!(active_theme.short_name(), "aliner");
|
||||||
///
|
///
|
||||||
/// // Recupera el parámetro a su tipo original.
|
/// // Genera un identificador único para un componente de tipo `Menu`.
|
||||||
/// let id: i32 = cx.param("usuario_id").unwrap();
|
|
||||||
/// assert_eq!(id, 42);
|
|
||||||
///
|
|
||||||
/// // Genera un identificador para un componente de tipo `Menu`.
|
|
||||||
/// struct Menu;
|
/// struct Menu;
|
||||||
/// let unique_id = cx.required_id::<Menu>(None);
|
/// let unique_id = cx.required_id::<Menu>(None);
|
||||||
/// assert_eq!(unique_id, "menu-1"); // Si es el primero generado.
|
/// assert_eq!(unique_id, "menu-1"); // Si es el primero generado.
|
||||||
|
@ -106,10 +119,10 @@ pub struct Context {
|
||||||
langid : &'static LanguageIdentifier, // Identificador del idioma.
|
langid : &'static LanguageIdentifier, // Identificador del idioma.
|
||||||
theme : ThemeRef, // Referencia al tema para renderizar.
|
theme : ThemeRef, // Referencia al tema para renderizar.
|
||||||
layout : &'static str, // Composición del documento para renderizar.
|
layout : &'static str, // Composición del documento para renderizar.
|
||||||
params : HashMap<String, String>, // Parámetros definidos en tiempo de ejecución.
|
|
||||||
favicon : Option<Favicon>, // Favicon, si se ha definido.
|
favicon : Option<Favicon>, // Favicon, si se ha definido.
|
||||||
stylesheets: Assets<StyleSheet>, // Hojas de estilo CSS.
|
stylesheets: Assets<StyleSheet>, // Hojas de estilo CSS.
|
||||||
javascripts: Assets<JavaScript>, // Scripts JavaScript.
|
javascripts: Assets<JavaScript>, // Scripts JavaScript.
|
||||||
|
params : HashMap<String, String>, // Parámetros definidos en tiempo de ejecución.
|
||||||
id_counter : usize, // Contador para generar identificadores únicos.
|
id_counter : usize, // Contador para generar identificadores únicos.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -124,84 +137,60 @@ impl Context {
|
||||||
langid : &DEFAULT_LANGID,
|
langid : &DEFAULT_LANGID,
|
||||||
theme : *DEFAULT_THEME,
|
theme : *DEFAULT_THEME,
|
||||||
layout : "default",
|
layout : "default",
|
||||||
params : HashMap::<String, String>::new(),
|
|
||||||
favicon : None,
|
favicon : None,
|
||||||
stylesheets: Assets::<StyleSheet>::new(),
|
stylesheets: Assets::<StyleSheet>::new(),
|
||||||
javascripts: Assets::<JavaScript>::new(),
|
javascripts: Assets::<JavaScript>::new(),
|
||||||
|
params : HashMap::<String, String>::new(),
|
||||||
id_counter : 0,
|
id_counter : 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Context BUILDER *****************************************************************************
|
/// Modifica información o recursos del contexto usando [`ContextOp`].
|
||||||
|
pub fn alter_assets(&mut self, op: ContextOp) -> &mut Self {
|
||||||
/// Modifica el identificador de idioma del documento.
|
|
||||||
#[builder_fn]
|
|
||||||
pub fn with_langid(mut self, langid: &'static LanguageIdentifier) -> Self {
|
|
||||||
self.langid = langid;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Establece el tema que se usará para renderizar el documento.
|
|
||||||
///
|
|
||||||
/// Localiza el tema por su [`short_name`](crate::core::AnyInfo::short_name), y si no aplica
|
|
||||||
/// ninguno entonces usará el tema por defecto.
|
|
||||||
#[builder_fn]
|
|
||||||
pub fn with_theme(mut self, theme_name: impl AsRef<str>) -> Self {
|
|
||||||
self.theme = theme_by_short_name(theme_name).unwrap_or(*DEFAULT_THEME);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Define el tipo de composición usado para renderizar el documento.
|
|
||||||
#[builder_fn]
|
|
||||||
pub fn with_layout(mut self, layout_name: &'static str) -> Self {
|
|
||||||
self.layout = layout_name;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Añade o modifica un parámetro del contexto almacenando el valor como [`String`].
|
|
||||||
#[builder_fn]
|
|
||||||
pub fn with_param<T: ToString>(mut self, key: impl AsRef<str>, value: T) -> Self {
|
|
||||||
self.params
|
|
||||||
.insert(key.as_ref().to_string(), value.to_string());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Elimina un parámetro del contexto. Devuelve `true` si existía y se eliminó.
|
|
||||||
pub fn remove_param(&mut self, key: impl AsRef<str>) -> bool {
|
|
||||||
self.params.remove(key.as_ref()).is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Modifica información o recursos del contexto usando [`AssetsOp`].
|
|
||||||
#[builder_fn]
|
|
||||||
pub fn with_assets(mut self, op: AssetsOp) -> Self {
|
|
||||||
match op {
|
match op {
|
||||||
|
ContextOp::LangId(langid) => {
|
||||||
|
self.langid = langid;
|
||||||
|
}
|
||||||
|
ContextOp::Theme(theme_name) => {
|
||||||
|
self.theme = theme_by_short_name(theme_name).unwrap_or(*DEFAULT_THEME);
|
||||||
|
}
|
||||||
|
ContextOp::Layout(layout) => {
|
||||||
|
self.layout = layout;
|
||||||
|
}
|
||||||
// Favicon.
|
// Favicon.
|
||||||
AssetsOp::SetFavicon(favicon) => {
|
ContextOp::SetFavicon(favicon) => {
|
||||||
self.favicon = favicon;
|
self.favicon = favicon;
|
||||||
}
|
}
|
||||||
AssetsOp::SetFaviconIfNone(icon) => {
|
ContextOp::SetFaviconIfNone(icon) => {
|
||||||
if self.favicon.is_none() {
|
if self.favicon.is_none() {
|
||||||
self.favicon = Some(icon);
|
self.favicon = Some(icon);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Stylesheets.
|
// Stylesheets.
|
||||||
AssetsOp::AddStyleSheet(css) => {
|
ContextOp::AddStyleSheet(css) => {
|
||||||
self.stylesheets.add(css);
|
self.stylesheets.add(css);
|
||||||
}
|
}
|
||||||
AssetsOp::RemoveStyleSheet(path) => {
|
ContextOp::RemoveStyleSheet(path) => {
|
||||||
self.stylesheets.remove(path);
|
self.stylesheets.remove(path);
|
||||||
}
|
}
|
||||||
// JavaScripts.
|
// JavaScripts.
|
||||||
AssetsOp::AddJavaScript(js) => {
|
ContextOp::AddJavaScript(js) => {
|
||||||
self.javascripts.add(js);
|
self.javascripts.add(js);
|
||||||
}
|
}
|
||||||
AssetsOp::RemoveJavaScript(path) => {
|
ContextOp::RemoveJavaScript(path) => {
|
||||||
self.javascripts.remove(path);
|
self.javascripts.remove(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Añade o modifica un parámetro del contexto almacenando el valor como [`String`].
|
||||||
|
pub fn set_param<T: ToString>(&mut self, key: impl AsRef<str>, value: T) -> &mut Self {
|
||||||
|
self.params
|
||||||
|
.insert(key.as_ref().to_string(), value.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
// Context GETTERS *****************************************************************************
|
// Context GETTERS *****************************************************************************
|
||||||
|
|
||||||
/// Devuelve la solicitud HTTP asociada al documento.
|
/// Devuelve la solicitud HTTP asociada al documento.
|
||||||
|
@ -229,28 +218,20 @@ impl Context {
|
||||||
///
|
///
|
||||||
/// Devuelve un error si el parámetro no existe ([`ErrorParam::NotFound`]) o la conversión falla
|
/// Devuelve un error si el parámetro no existe ([`ErrorParam::NotFound`]) o la conversión falla
|
||||||
/// ([`ErrorParam::ParseError`]).
|
/// ([`ErrorParam::ParseError`]).
|
||||||
pub fn param<T: FromStr>(&self, key: impl AsRef<str>) -> Result<T, ErrorParam> {
|
pub fn get_param<T: FromStr>(&self, key: impl AsRef<str>) -> Result<T, ErrorParam> {
|
||||||
self.params
|
self.params
|
||||||
.get(key.as_ref())
|
.get(key.as_ref())
|
||||||
.ok_or(ErrorParam::NotFound)
|
.ok_or(ErrorParam::NotFound)
|
||||||
.and_then(|v| T::from_str(v).map_err(|_| ErrorParam::ParseError(v.clone())))
|
.and_then(|v| T::from_str(v).map_err(|_| ErrorParam::ParseError(v.clone())))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Context RENDER ******************************************************************************
|
|
||||||
|
|
||||||
/// Renderiza los recursos del contexto.
|
|
||||||
pub fn render_assets(&self) -> Markup {
|
|
||||||
html! {
|
|
||||||
@if let Some(favicon) = &self.favicon {
|
|
||||||
(favicon)
|
|
||||||
}
|
|
||||||
(self.stylesheets)
|
|
||||||
(self.javascripts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Context EXTRAS ******************************************************************************
|
// Context EXTRAS ******************************************************************************
|
||||||
|
|
||||||
|
/// Elimina un parámetro del contexto. Devuelve `true` si existía y se eliminó.
|
||||||
|
pub fn remove_param(&mut self, key: impl AsRef<str>) -> bool {
|
||||||
|
self.params.remove(key.as_ref()).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
/// Genera un identificador único si no se proporciona uno explícito.
|
/// Genera un identificador único si no se proporciona uno explícito.
|
||||||
///
|
///
|
||||||
/// Si no se proporciona un `id`, se genera un identificador único en la forma `<tipo>-<número>`
|
/// Si no se proporciona un `id`, se genera un identificador único en la forma `<tipo>-<número>`
|
||||||
|
@ -275,3 +256,15 @@ impl Context {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Render for Context {
|
||||||
|
fn render(&self) -> Markup {
|
||||||
|
html! {
|
||||||
|
@if let Some(favicon) = &self.favicon {
|
||||||
|
(favicon)
|
||||||
|
}
|
||||||
|
(self.stylesheets)
|
||||||
|
(self.javascripts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue