🎨 [macros] Redefine #[fn_builder] con coherencia

La macro genera automáticamente un método "alter_", que modifica la
instancia actual usando "&mut self", y redefine el método "with_" para
delegar la lógica en el nuevo método "alter_".
This commit is contained in:
Manuel Cillero 2025-01-02 09:24:56 +01:00
parent 4db4d791a5
commit febb9bc9cb
13 changed files with 176 additions and 137 deletions

View file

@ -1,6 +1,6 @@
//! Configuration settings for package.
//! Opciones de configuración.
//!
//! Example:
//! Ejemplo:
//!
//! ```toml
//! [hljs]
@ -9,14 +9,16 @@
//! tabsize = 8
//! ```
//!
//! Usage:
//! Uso:
//!
//! ```rust
//! use pagetop_hljs::config;
//!
//! assert_eq!(config::SETTINGS.hljs.theme, "zenburn");
//! ```
//! See [`pagetop::config`] to learn how PageTop reads configuration files and uses settings.
//!
//! Consulta [`pagetop::config`] para aprender cómo `PageTop` lee los archivos de opciones y aplica
//! los valores de configuración.
use pagetop::prelude::*;
@ -33,26 +35,27 @@ include_config!(SETTINGS: Settings => [
]);
#[derive(Debug, Deserialize)]
/// Configuration settings for the [`[hljs]`](Hljs) section (see [`SETTINGS`] package).
/// Opciones de configuración para la sección [`[hljs]`](Hljs) (ver [`SETTINGS`]).
pub struct Settings {
pub hljs: Hljs,
}
#[derive(Debug, Deserialize)]
/// Section `[hljs]` of the configuration settings.
/// Sección `[hljs]` de la configuración.
///
/// See [`Settings`].
/// Ver [`Settings`].
pub struct Hljs {
/// Use ***core*** to import a minimal library and load only the languages added via
/// [`add_hljs_language()`](crate::hljs_context::HljsContext::add_hljs_language). Alternatively,
/// ***common*** imports an extended library containing around 40 popular languages (see
/// [`HljsLang`](crate::hljs_lang::HljsLang)). Note that using the *common* library restricts
/// you to the languages that are preloaded.
/// Default value: *"core"*
/// Usa ***core*** para importar una librería mínima y cargar solo los lenguajes añadidos vía
/// [`add_hljs_language()`](crate::context::HljsContext::add_hljs_language). Por otro lado, usa
/// ***common*** para importar una librería extendida con los 40 lenguajes más habituales según
/// [`HljsLang`](crate::lang::HljsLang). Ten en cuenta que al usar la librería *common* te
/// limitas a los lenguajes que vienen precargados.
/// Valor por defecto: *"core"*
pub mode: HljsMode,
/// Default theme in kebab-case used to display code snippets on web pages (see [`HljsTheme`]).
/// Default value: *"default"*
/// Tema por defecto en formato *kebab-case* para mostrar los fragmentos de código en las
/// páginas web (ver [`HljsTheme`]).
/// Valor por defecto: *"default"*
pub theme: HljsTheme,
/// Number of spaces for *tab* character.
/// Default value: *4*
/// Número de espacios para el carácter tabulador.
/// Valor por defecto: *4*
pub tabsize: usize,
}

View file

@ -7,32 +7,33 @@ use crate::theme::HljsTheme;
use std::collections::HashSet;
// Context parameters.
// Parámetros para el contexto.
const PARAM_HLJS_ENABLED: &str = "hljs.enabled";
const PARAM_HLJS_MODE: &str = "hljs.mode";
const PARAM_HLJS_LANGS: &str = "hljs.langs";
const PARAM_HLJS_THEME: &str = "hljs.theme";
/// Extend Context with HighlightJS features.
/// Extiende el contexto de renderizado con funcionalidades de HighlightJS.
pub trait HljsContext {
/// Enable syntax highlighting in current context.
/// Habilita el resaltado de sintaxis en el contexto actual.
fn enable_hljs(&mut self);
/// Preventing syntax highlighting in current context.
/// Deshabilita el resaltado de sintaxis en el contexto actual.
fn disable_hljs(&mut self);
/// Force the use of the *highlight.js* ***core*** or ***common*** mode in current context,
/// ignoring the [`config::SETTINGS.hljs.mode`](crate::config::Hljs#structfield.mode)
/// configuration setting.
/// Fuerza el uso del modo ***core*** o ***common*** de *highlight.js* en el contexto actual,
/// ignorando [`config::SETTINGS.hljs.mode`](crate::config::Hljs#structfield.mode) de las
/// opciones de configuración.
fn force_hljs_mode(&mut self, mode: &HljsMode);
/// Add a new language to the context for processing code snippets. It is necessary to add at
/// least one language to load the *highlight.js* library. Each
/// [`Snippet`](crate::snippet::Snippet) component automatically adds its required language.
/// Añade un nuevo lenguaje al contexto actual para el resaltado de fragmentos de código. Se
/// requiere al menos un lenguaje para cargar la librería *highlight.js*. Recuerda que cada
/// componente [`Snippet`](crate::snippet::HljsSnippet) añade automáticamente el lenguaje que
/// necesita. Solo aplica cuando el contexto está configurado en el modo ***core***.
fn add_hljs_language(&mut self, language: &HljsLang);
/// Change the theme in current context for displaying code snippets. The same theme is used for
/// all snippets in the given context.
/// Cambia el tema del contexto actual para mostrar los fragmentos de código. Ten en cuenta que
/// *highlight.js* utilizará el mismo tema para todos los framentos en este contexto.
fn set_hljs_theme(&mut self, theme: &HljsTheme);
fn is_hljs_enabled(&self) -> bool;

View file

@ -42,13 +42,13 @@ impl HljsSnippet {
// Hljs BUILDER.
#[fn_builder]
pub fn alter_language(&mut self, language: HljsLang) -> &mut Self {
pub fn with_language(mut self, language: HljsLang) -> Self {
self.language = language;
self
}
#[fn_builder]
pub fn alter_snippet(&mut self, snippet: impl Into<String>) -> &mut Self {
pub fn with_snippet(mut self, snippet: impl Into<String>) -> Self {
self.snippet = snippet.into().trim().to_string();
self
}