From 6701fb3e90b2a5c2223011aaf878cb1b353f38c7 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sun, 22 Dec 2024 14:54:05 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=AC=20Apps=20como=20"Sample"=20e=20Int?= =?UTF-8?q?egra=20macro=20join=5Fstring!?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/predefined.toml | 2 +- pagetop/config/common.toml | 6 --- pagetop/examples/hello-name.rs | 3 +- pagetop/src/config.rs | 11 +++-- pagetop/src/core/component/context.rs | 5 +-- pagetop/src/global.rs | 4 +- pagetop/src/html/assets/javascript.rs | 12 +++-- pagetop/src/html/assets/stylesheet.rs | 6 +-- pagetop/src/lib.rs | 2 +- pagetop/src/prelude.rs | 2 +- pagetop/src/util.rs | 64 +++++++++++++++++---------- 11 files changed, 60 insertions(+), 57 deletions(-) delete mode 100644 pagetop/config/common.toml diff --git a/config/predefined.toml b/config/predefined.toml index 08571a92..abe24e7b 100644 --- a/config/predefined.toml +++ b/config/predefined.toml @@ -1,5 +1,5 @@ [app] -name = "My App" +name = "Sample" description = "Developed with the amazing PageTop framework." # Default theme. theme = "Default" diff --git a/pagetop/config/common.toml b/pagetop/config/common.toml deleted file mode 100644 index d6b30e57..00000000 --- a/pagetop/config/common.toml +++ /dev/null @@ -1,6 +0,0 @@ -[app] -name = "Samples" -#language = "es-ES" - -[log] -tracing = "Debug" diff --git a/pagetop/examples/hello-name.rs b/pagetop/examples/hello-name.rs index 3a03e8b1..92ca467c 100644 --- a/pagetop/examples/hello-name.rs +++ b/pagetop/examples/hello-name.rs @@ -4,11 +4,10 @@ struct HelloName; impl PackageTrait for HelloName { fn configure_service(&self, scfg: &mut service::web::ServiceConfig) { - scfg.service(hello_name); + scfg.route("/hello/{name}", service::web::get().to(hello_name)); } } -#[service::get("/hello/{name}")] async fn hello_name( request: HttpRequest, path: service::web::Path, diff --git a/pagetop/src/config.rs b/pagetop/src/config.rs index 65ce6e1c..7131d158 100644 --- a/pagetop/src/config.rs +++ b/pagetop/src/config.rs @@ -127,8 +127,7 @@ mod value; use crate::config::data::ConfigData; use crate::config::file::File; - -use concat_string::concat_string; +use crate::join_string; use std::sync::LazyLock; @@ -158,16 +157,16 @@ pub static CONFIG_VALUES: LazyLock = LazyLock::new(|| { // Merge (optional) configuration files and set the execution mode. values // First, add the common configuration for all environments. Defaults to 'common.toml'. - .merge(File::with_name(&concat_string!(config_dir, "/common.toml")).required(false)) + .merge(File::with_name(&join_string!(config_dir, "/common.toml")).required(false)) .expect("Failed to merge common configuration (common.toml)") // Add the environment-specific configuration. Defaults to 'default.toml'. - .merge(File::with_name(&concat_string!(config_dir, "/", rm, ".toml")).required(false)) + .merge(File::with_name(&join_string!(config_dir, "/", rm, ".toml")).required(false)) .expect(&format!("Failed to merge {rm}.toml configuration")) // Add reserved local configuration for the environment. Defaults to 'local.default.toml'. - .merge(File::with_name(&concat_string!(config_dir, "/local.", rm, ".toml")).required(false)) + .merge(File::with_name(&join_string!(config_dir, "/local.", rm, ".toml")).required(false)) .expect("Failed to merge reserved local environment configuration") // Add common reserved local configuration. Defaults to 'local.toml'. - .merge(File::with_name(&concat_string!(config_dir, "/local.toml")).required(false)) + .merge(File::with_name(&join_string!(config_dir, "/local.toml")).required(false)) .expect("Failed to merge general reserved local configuration") // Save the execution mode. .set("app.run_mode", rm) diff --git a/pagetop/src/core/component/context.rs b/pagetop/src/core/component/context.rs index b4459b28..8f53bf64 100644 --- a/pagetop/src/core/component/context.rs +++ b/pagetop/src/core/component/context.rs @@ -3,12 +3,11 @@ use crate::core::theme::all::{theme_by_short_name, DEFAULT_THEME}; use crate::core::theme::{ChildrenInRegions, ThemeRef}; use crate::html::{html, Markup}; use crate::html::{Assets, Favicon, JavaScript, StyleSheet}; +use crate::join_string; use crate::locale::{LanguageIdentifier, DEFAULT_LANGID}; use crate::service::HttpRequest; use crate::util::TypeInfo; -use concat_string::concat_string; - use std::collections::HashMap; use std::error::Error; use std::str::FromStr; @@ -198,7 +197,7 @@ impl Context { prefix }; self.id_counter += 1; - concat_string!(prefix, "-", self.id_counter.to_string()) + join_string!(prefix, "-", self.id_counter.to_string()) } } } diff --git a/pagetop/src/global.rs b/pagetop/src/global.rs index 1e795b83..b792367e 100644 --- a/pagetop/src/global.rs +++ b/pagetop/src/global.rs @@ -6,7 +6,7 @@ use serde::Deserialize; include_config!(SETTINGS: Settings => [ // [app] - "app.name" => "My App", + "app.name" => "Sample", "app.description" => "Developed with the amazing PageTop framework.", "app.theme" => "", "app.language" => "en-US", @@ -45,7 +45,7 @@ pub struct Settings { /// See [`Settings`]. pub struct App { /// The name of the application. - /// Default: *"My App"*. + /// Default: *"Sample"*. pub name: String, /// A brief description of the application. /// Default: *"Developed with the amazing PageTop framework."*. diff --git a/pagetop/src/html/assets/javascript.rs b/pagetop/src/html/assets/javascript.rs index 15c38c5f..cafe70fc 100644 --- a/pagetop/src/html/assets/javascript.rs +++ b/pagetop/src/html/assets/javascript.rs @@ -1,8 +1,6 @@ use crate::html::assets::AssetsTrait; use crate::html::{html, Markup}; -use crate::{AutoDefault, Weight}; - -use concat_string::concat_string; +use crate::{join_string, AutoDefault, Weight}; #[derive(AutoDefault)] enum Source { @@ -41,18 +39,18 @@ impl AssetsTrait for JavaScript { fn render(&self) -> Markup { match &self.source { Source::From(path) => html! { - script src=(concat_string!(path, self.prefix, self.version)) {}; + script src=(join_string!(path, self.prefix, self.version)) {}; }, Source::Defer(path) => html! { - script src=(concat_string!(path, self.prefix, self.version)) defer {}; + script src=(join_string!(path, self.prefix, self.version)) defer {}; }, Source::Async(path) => html! { - script src=(concat_string!(path, self.prefix, self.version)) async {}; + script src=(join_string!(path, self.prefix, self.version)) async {}; }, Source::Inline(_, code) => html! { script { (code) }; }, - Source::OnLoad(_, code) => html! { (concat_string!( + Source::OnLoad(_, code) => html! { (join_string!( "document.addEventListener('DOMContentLoaded',function(){", code, "});" diff --git a/pagetop/src/html/assets/stylesheet.rs b/pagetop/src/html/assets/stylesheet.rs index 09a0e96d..00c8c7a6 100644 --- a/pagetop/src/html/assets/stylesheet.rs +++ b/pagetop/src/html/assets/stylesheet.rs @@ -1,8 +1,6 @@ use crate::html::assets::AssetsTrait; use crate::html::{html, Markup, PreEscaped}; -use crate::{AutoDefault, Weight}; - -use concat_string::concat_string; +use crate::{join_string, AutoDefault, Weight}; #[derive(AutoDefault)] enum Source { @@ -45,7 +43,7 @@ impl AssetsTrait for StyleSheet { Source::From(path) => html! { link rel="stylesheet" - href=(concat_string!(path, self.prefix, self.version)) + href=(join_string!(path, self.prefix, self.version)) media=[self.media]; }, Source::Inline(_, code) => html! { diff --git a/pagetop/src/lib.rs b/pagetop/src/lib.rs index 2a830ad7..049b4939 100644 --- a/pagetop/src/lib.rs +++ b/pagetop/src/lib.rs @@ -121,6 +121,6 @@ pub mod base; // Prepara y ejecuta la aplicación. pub mod app; -// Prelude de PageTop ****************************************************************************** +// PRELUDE ***************************************************************************************** pub mod prelude; diff --git a/pagetop/src/prelude.rs b/pagetop/src/prelude.rs index 6569372c..5418fe02 100644 --- a/pagetop/src/prelude.rs +++ b/pagetop/src/prelude.rs @@ -9,7 +9,7 @@ pub use crate::{AutoDefault, ComponentClasses, StaticResources, UniqueId, Weight // MACROS. // crate::util -pub use crate::kv; +pub use crate::{join_string, kv}; // crate::config pub use crate::include_config; // crate::locale diff --git a/pagetop/src/util.rs b/pagetop/src/util.rs index 610a5e0f..1261079d 100644 --- a/pagetop/src/util.rs +++ b/pagetop/src/util.rs @@ -5,7 +5,7 @@ use crate::trace; use std::io; use std::path::PathBuf; -// USEFUL FUNCTIONS ******************************************************************************** +// FUNCIONES ÚTILES ******************************************************************************** pub enum TypeInfo { FullName, @@ -30,18 +30,18 @@ impl TypeInfo { fn partial(type_name: &'static str, start: isize, end: Option) -> &'static str { let maxlen = type_name.len(); let mut segments = Vec::new(); - let mut segment_start = 0; // Start position of the current segment. - let mut angle_brackets = 0; // Counter for tracking '<' and '>'. - let mut previous_char = '\0'; // Initializes to a null character, no previous character. + let mut segment_start = 0; // Posición de inicial del segmento actual. + let mut angle_brackets = 0; // Contador para seguimiento de '<' y '>'. + let mut previous_char = '\0'; // Se inicializa a carácter nulo, no hay aún carácter previo. for (idx, c) in type_name.char_indices() { match c { ':' if angle_brackets == 0 => { if previous_char == ':' { if segment_start < idx - 1 { - segments.push((segment_start, idx - 1)); // Do not include last '::'. + segments.push((segment_start, idx - 1)); // No incluye último '::'. } - segment_start = idx + 1; // Next segment starts after '::'. + segment_start = idx + 1; // El siguiente segmento comienza después de '::'. } } '<' => angle_brackets += 1, @@ -51,12 +51,12 @@ impl TypeInfo { previous_char = c; } - // Include the last segment if there's any. + // Incluye el último segmento si lo hubiese. if segment_start < maxlen { segments.push((segment_start, maxlen)); } - // Calculates the start position. + // Calcula la posición inicial. let start_pos = segments .get(if start >= 0 { start as usize @@ -65,7 +65,7 @@ impl TypeInfo { }) .map_or(0, |&(s, _)| s); - // Calculates the end position. + // Calcula la posición final. let end_pos = segments .get(if let Some(end) = end { if end >= 0 { @@ -78,30 +78,30 @@ impl TypeInfo { }) .map_or(maxlen, |&(_, e)| e); - // Returns the partial string based on the calculated positions. + // Devuelve la cadena parcial basada en las posiciones calculadas. &type_name[start_pos..end_pos] } } -/// Calculates the absolute directory given a root path and a relative path. +/// Calcula el directorio absoluto dado un directorio raíz y una ruta relativa. /// -/// # Arguments +/// # Argumentos /// -/// * `root_path` - A string slice that holds the root path. -/// * `relative_path` - A string slice that holds the relative path. +/// * `root_path` - Contiene el directorio raíz. +/// * `relative_path` - Contiene la ruta relativa. /// -/// # Returns +/// # Devuelve /// -/// * `Ok` - If the operation is successful, returns the absolute directory as a `String`. -/// * `Err` - If an I/O error occurs, returns an `io::Error`. +/// * `Ok` - Si la operación es correcta devuelve el directorio absoluto como un `String`. +/// * `Err` - Si ocurre un error de E/S, devuelve un `io::Error`. /// -/// # Errors +/// # Errores /// -/// This function will return an error if: -/// - The root path or relative path are invalid. -/// - There is an issue with file system operations, such as reading the directory. +/// Esta función devolverá un error si: +/// - El directorio raíz o la ruta relativa son inválidos. +/// - Hay un problema con las operaciones sobre el sistema de archivos, como leer el directorio. /// -/// # Examples +/// # Ejemplos /// /// ```rust#ignore /// let root = "/home/user"; @@ -138,11 +138,27 @@ pub fn absolute_dir( Ok(absolute_dir) } -// USEFUL MACROS *********************************************************************************** +// MACROS ÚTILES *********************************************************************************** -/// Flexible concatenation of identifiers in macros. +#[doc(hidden)] pub use paste::paste; +#[doc(hidden)] +pub use concat_string::concat_string; + +/// Concatena varios fragmentos de cadenas en una cadena *String*. +/// +/// Exporta la macro [`concat_string!`](https://docs.rs/concat-string), que permite concatenar de +/// forma eficiente fragmentos de cadenas (*string slices*) en una cadena *String*. Acepta cualquier +/// número de argumentos que implementen `AsRef` y crea una cadena `String` con el tamaño +/// adecuado, sin requerir cadenas de formato que puedan sobrecargar el rendimiento. +#[macro_export] +macro_rules! join_string { + ($($arg:tt)*) => { + crate::util::concat_string!($($arg)*) + }; +} + #[macro_export] /// Macro para construir grupos de pares clave-valor. ///