Compare commits

...

2 commits

Author SHA1 Message Date
1be3d88888 ♻️ Migra #[builder_fn] a #[builder_impl]
Sustituye las ~400 anotaciones `#[builder_fn]` método a método por un
único `#[builder_impl]` por `impl`/`trait`, en 74 ficheros de pagetop y
sus extensiones (admin, bootsier, menu, user).
2026-08-29 19:25:58 +02:00
c34dc02357 (macros): Añade #[builder_impl]
Aplica `#[builder_fn]` a todos los métodos `with_...()` de un bloque
`impl` o de una definición de trait de una vez, sin anotarlos uno a uno.
2026-08-29 19:19:58 +02:00
78 changed files with 633 additions and 669 deletions

View file

@ -68,16 +68,15 @@ impl Component for AdminFrame {
} }
} }
#[builder_impl]
impl AdminFrame { impl AdminFrame {
/// Establece el título de la página. /// Establece el título de la página.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
} }
/// Añade un componente hijo al contenido de la página. /// Añade un componente hijo al contenido de la página.
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -201,8 +201,10 @@ impl Component for ConfigForm {
} }
} }
#[builder_impl]
impl ConfigForm { impl ConfigForm {
/// Crea el componente con el [`SettingsSchema`] dado. /// Crea el componente con el [`SettingsSchema`] dado.
#[builder_skip]
pub fn with_schema(schema: SettingsSchema) -> Self { pub fn with_schema(schema: SettingsSchema) -> Self {
ConfigForm { ConfigForm {
schema: Some(schema), schema: Some(schema),
@ -210,7 +212,6 @@ impl ConfigForm {
} }
} }
#[builder_fn]
pub fn with_action_path(mut self, v: impl Into<Option<Route>>) -> Self { pub fn with_action_path(mut self, v: impl Into<Option<Route>>) -> Self {
if let Some(v) = v.into() { if let Some(v) = v.into() {
self.action_path = Some(v); self.action_path = Some(v);
@ -218,6 +219,7 @@ impl ConfigForm {
self self
} }
#[builder_skip]
pub(crate) fn with_saved(mut self, saved: bool, error: bool) -> Self { pub(crate) fn with_saved(mut self, saved: bool, error: bool) -> Self {
self.saved = saved; self.saved = saved;
self.error = error; self.error = error;

View file

@ -3,7 +3,7 @@
//! Proporciona una API async para leer y escribir valores JSON en la tabla `settings`. //! Proporciona una API async para leer y escribir valores JSON en la tabla `settings`.
use pagetop::datetime::Utc; use pagetop::datetime::Utc;
use pagetop::{Getters, builder_fn}; use pagetop::{Getters, builder_impl};
use pagetop_seaorm::db::{ use pagetop_seaorm::db::{
ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, QueryFilter, dbconn, ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, QueryFilter, dbconn,
}; };
@ -128,6 +128,7 @@ pub struct SettingField {
default_value: Option<String>, default_value: Option<String>,
} }
#[builder_impl]
impl SettingField { impl SettingField {
/// Crea un campo de texto con nombre y etiqueta. /// Crea un campo de texto con nombre y etiqueta.
pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self { pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self {
@ -185,21 +186,18 @@ impl SettingField {
} }
/// Establece si el campo es obligatorio. /// Establece si el campo es obligatorio.
#[builder_fn]
pub fn with_required(mut self, required: bool) -> Self { pub fn with_required(mut self, required: bool) -> Self {
self.required = required; self.required = required;
self self
} }
/// Añade texto de ayuda bajo el campo. /// Añade texto de ayuda bajo el campo.
#[builder_fn]
pub fn with_help(mut self, text: impl Into<String>) -> Self { pub fn with_help(mut self, text: impl Into<String>) -> Self {
self.help_text = Some(text.into()); self.help_text = Some(text.into());
self self
} }
/// Establece el valor por defecto (como valor JSON serializado). /// Establece el valor por defecto (como valor JSON serializado).
#[builder_fn]
pub fn with_default<T: Serialize>(mut self, value: &T) -> Self { pub fn with_default<T: Serialize>(mut self, value: &T) -> Self {
self.default_value = serde_json::to_string(value).ok(); self.default_value = serde_json::to_string(value).ok();
self self
@ -215,6 +213,7 @@ pub struct SettingsSchema {
fields: Vec<SettingField>, fields: Vec<SettingField>,
} }
#[builder_impl]
impl SettingsSchema { impl SettingsSchema {
/// Crea un nuevo esquema vacío para el `scope` dado. /// Crea un nuevo esquema vacío para el `scope` dado.
pub fn new(scope: impl Into<String>) -> Self { pub fn new(scope: impl Into<String>) -> Self {
@ -225,7 +224,6 @@ impl SettingsSchema {
} }
/// Añade un campo al esquema. /// Añade un campo al esquema.
#[builder_fn]
pub fn with_field(mut self, field: SettingField) -> Self { pub fn with_field(mut self, field: SettingField) -> Self {
self.fields.push(field); self.fields.push(field);
self self

View file

@ -18,15 +18,15 @@ const EXTRA_COLOR: &str = "bootsier.badge.color";
/// ///
/// let badge = bs::Badge::labeled(Lc::n("Beta")).with_color(BootsierColors::Dark); /// let badge = bs::Badge::labeled(Lc::n("Beta")).with_color(BootsierColors::Dark);
/// ``` /// ```
#[builder_impl]
pub trait BadgeBootsier { pub trait BadgeBootsier {
/// Fuerza un color de la paleta de Bootsier, ignorando el que le correspondería a la `Intent` /// Fuerza un color de la paleta de Bootsier, ignorando el que le correspondería a la `Intent`
/// del badge. `None` restablece el comportamiento por defecto (color derivado de la `Intent`). /// del badge. `None` restablece el comportamiento por defecto (color derivado de la `Intent`).
#[builder_fn]
fn with_color(self, color: impl Into<Option<BootsierColors>>) -> Self; fn with_color(self, color: impl Into<Option<BootsierColors>>) -> Self;
} }
#[builder_impl]
impl BadgeBootsier for Badge { impl BadgeBootsier for Badge {
#[builder_fn]
fn with_color(mut self, color: impl Into<Option<BootsierColors>>) -> Self { fn with_color(mut self, color: impl Into<Option<BootsierColors>>) -> Self {
match color.into() { match color.into() {
Some(color) => self.alter_prop(PropsOp::set_extra(EXTRA_COLOR, color)), Some(color) => self.alter_prop(PropsOp::set_extra(EXTRA_COLOR, color)),

View file

@ -33,36 +33,32 @@ const EXTRA_COLOR: &str = "bootsier.button.color";
/// .with_style(button::Style::Solid(Intent::Neutral)) /// .with_style(button::Style::Solid(Intent::Neutral))
/// .with_color(BootsierColors::Light); /// .with_color(BootsierColors::Light);
/// ``` /// ```
#[builder_impl]
pub trait ButtonBootsier { pub trait ButtonBootsier {
/// Marca el botón como activo (`.active`, `aria-pressed="true"`). /// Marca el botón como activo (`.active`, `aria-pressed="true"`).
#[builder_fn]
fn with_active(self, active: bool) -> Self; fn with_active(self, active: bool) -> Self;
/// Expande el botón al ancho completo de su contenedor (`w-100`). /// Expande el botón al ancho completo de su contenedor (`w-100`).
#[builder_fn]
fn with_full_width(self, full_width: bool) -> Self; fn with_full_width(self, full_width: bool) -> Self;
/// Fuerza un color de la paleta de Bootsier, ignorando el que le correspondería a la `Intent` /// Fuerza un color de la paleta de Bootsier, ignorando el que le correspondería a la `Intent`
/// del botón. `None` restablece el comportamiento por defecto (color derivado de la `Intent`). /// del botón. `None` restablece el comportamiento por defecto (color derivado de la `Intent`).
/// Sin efecto si el estilo del botón es [`Style::Link`] o [`Style::None`]. /// Sin efecto si el estilo del botón es [`Style::Link`] o [`Style::None`].
#[builder_fn]
fn with_color(self, color: impl Into<Option<BootsierColors>>) -> Self; fn with_color(self, color: impl Into<Option<BootsierColors>>) -> Self;
} }
#[builder_impl]
impl ButtonBootsier for Button { impl ButtonBootsier for Button {
#[builder_fn]
fn with_active(mut self, active: bool) -> Self { fn with_active(mut self, active: bool) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_ACTIVE, active)); self.alter_prop(PropsOp::set_extra(EXTRA_ACTIVE, active));
self self
} }
#[builder_fn]
fn with_full_width(mut self, full_width: bool) -> Self { fn with_full_width(mut self, full_width: bool) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_FULL_WIDTH, full_width)); self.alter_prop(PropsOp::set_extra(EXTRA_FULL_WIDTH, full_width));
self self
} }
#[builder_fn]
fn with_color(mut self, color: impl Into<Option<BootsierColors>>) -> Self { fn with_color(mut self, color: impl Into<Option<BootsierColors>>) -> Self {
match color.into() { match color.into() {
Some(color) => self.alter_prop(PropsOp::set_extra(EXTRA_COLOR, color)), Some(color) => self.alter_prop(PropsOp::set_extra(EXTRA_COLOR, color)),

View file

@ -32,18 +32,18 @@ const EXTRA_WIDTH: &str = "bootsier.container.width";
/// .with_prop(PropsOp::add_classes(class::Border::with(ScaleSize::One))) /// .with_prop(PropsOp::add_classes(class::Border::with(ScaleSize::One)))
/// .with_prop(PropsOp::add_classes(class::Rounded::new())); /// .with_prop(PropsOp::add_classes(class::Rounded::new()));
/// ``` /// ```
#[builder_impl]
pub trait ContainerBootsier { pub trait ContainerBootsier {
/// Establece el comportamiento del ancho para el contenedor. /// Establece el comportamiento del ancho para el contenedor.
/// ///
/// Determina si el contenedor aplica los anchos máximos predefinidos para cada punto de /// Determina si el contenedor aplica los anchos máximos predefinidos para cada punto de
/// ruptura, o si ocupa siempre el 100% del ancho disponible, o lo hace hasta un ancho máximo /// ruptura, o si ocupa siempre el 100% del ancho disponible, o lo hace hasta un ancho máximo
/// explícito. Ver [`Width`] para las variantes disponibles. /// explícito. Ver [`Width`] para las variantes disponibles.
#[builder_fn]
fn with_width(self, width: Width) -> Self; fn with_width(self, width: Width) -> Self;
} }
#[builder_impl]
impl ContainerBootsier for Container { impl ContainerBootsier for Container {
#[builder_fn]
fn with_width(mut self, width: Width) -> Self { fn with_width(mut self, width: Width) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_WIDTH, width)); self.alter_prop(PropsOp::set_extra(EXTRA_WIDTH, width));
self self

View file

@ -44,54 +44,46 @@ const EXTRA_MENU_POSITION: &str = "bootsier.dropdown.menu_position";
/// .with_item(bs::dropdown::Item::header(Lc::n("User session"))) /// .with_item(bs::dropdown::Item::header(Lc::n("User session")))
/// .with_item(bs::dropdown::Item::button(Lc::n("Sign out"))); /// .with_item(bs::dropdown::Item::button(Lc::n("Sign out")));
/// ``` /// ```
#[builder_impl]
pub trait DropdownBootsier { pub trait DropdownBootsier {
/// Indica si el botón del menú está integrado en un grupo de botones. /// Indica si el botón del menú está integrado en un grupo de botones.
#[builder_fn]
fn with_button_grouped(self, grouped: bool) -> Self; fn with_button_grouped(self, grouped: bool) -> Self;
/// Establece la política de cierre automático del menú desplegable. /// Establece la política de cierre automático del menú desplegable.
#[builder_fn]
fn with_auto_close(self, auto_close: AutoClose) -> Self; fn with_auto_close(self, auto_close: AutoClose) -> Self;
/// Establece la dirección de despliegue del menú. /// Establece la dirección de despliegue del menú.
#[builder_fn]
fn with_direction(self, direction: Direction) -> Self; fn with_direction(self, direction: Direction) -> Self;
/// Configura la alineación horizontal (con posible comportamiento *responsive* adicional). /// Configura la alineación horizontal (con posible comportamiento *responsive* adicional).
#[builder_fn]
fn with_menu_align(self, align: MenuAlign) -> Self; fn with_menu_align(self, align: MenuAlign) -> Self;
/// Configura la posición del menú. /// Configura la posición del menú.
#[builder_fn]
fn with_menu_position(self, position: MenuPosition) -> Self; fn with_menu_position(self, position: MenuPosition) -> Self;
} }
#[builder_impl]
impl DropdownBootsier for Dropdown { impl DropdownBootsier for Dropdown {
#[builder_fn]
fn with_button_grouped(mut self, grouped: bool) -> Self { fn with_button_grouped(mut self, grouped: bool) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_BUTTON_GROUPED, grouped)); self.alter_prop(PropsOp::set_extra(EXTRA_BUTTON_GROUPED, grouped));
self self
} }
#[builder_fn]
fn with_auto_close(mut self, auto_close: AutoClose) -> Self { fn with_auto_close(mut self, auto_close: AutoClose) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_AUTO_CLOSE, auto_close)); self.alter_prop(PropsOp::set_extra(EXTRA_AUTO_CLOSE, auto_close));
self self
} }
#[builder_fn]
fn with_direction(mut self, direction: Direction) -> Self { fn with_direction(mut self, direction: Direction) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_DIRECTION, direction)); self.alter_prop(PropsOp::set_extra(EXTRA_DIRECTION, direction));
self self
} }
#[builder_fn]
fn with_menu_align(mut self, align: MenuAlign) -> Self { fn with_menu_align(mut self, align: MenuAlign) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_MENU_ALIGN, align)); self.alter_prop(PropsOp::set_extra(EXTRA_MENU_ALIGN, align));
self self
} }
#[builder_fn]
fn with_menu_position(mut self, position: MenuPosition) -> Self { fn with_menu_position(mut self, position: MenuPosition) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_MENU_POSITION, position)); self.alter_prop(PropsOp::set_extra(EXTRA_MENU_POSITION, position));
self self

View file

@ -22,18 +22,18 @@ const EXTRA_FLOATING_LABEL: &str = "bootsier.form.input.floating_label";
/// .with_placeholder(Lc::n("Enter your name")) /// .with_placeholder(Lc::n("Enter your name"))
/// .with_floating_label(true); /// .with_floating_label(true);
/// ``` /// ```
#[builder_impl]
pub trait InputBootsier { pub trait InputBootsier {
/// Establece si la etiqueta se muestra flotante sobre el campo. /// Establece si la etiqueta se muestra flotante sobre el campo.
/// ///
/// Cuando está activo, la etiqueta se superpone al campo y asciende al enfocarlo o cuando tiene /// Cuando está activo, la etiqueta se superpone al campo y asciende al enfocarlo o cuando tiene
/// contenido. Requiere que el campo tenga un atributo `placeholder` definido; si no se /// contenido. Requiere que el campo tenga un atributo `placeholder` definido; si no se
/// especifica, se fuerza `placeholder=""` antes del renderizado. /// especifica, se fuerza `placeholder=""` antes del renderizado.
#[builder_fn]
fn with_floating_label(self, floating: bool) -> Self; fn with_floating_label(self, floating: bool) -> Self;
} }
#[builder_impl]
impl InputBootsier for Field { impl InputBootsier for Field {
#[builder_fn]
fn with_floating_label(mut self, floating: bool) -> Self { fn with_floating_label(mut self, floating: bool) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating)); self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating));
self self

View file

@ -24,6 +24,7 @@ const EXTRA_FLOATING_LABEL: &str = "bootsier.form.select.floating_label";
/// .with_item(bs::form::select::Item::new("es", Lc::n("Spanish"))) /// .with_item(bs::form::select::Item::new("es", Lc::n("Spanish")))
/// .with_item(bs::form::select::Item::new("en", Lc::n("English"))); /// .with_item(bs::form::select::Item::new("en", Lc::n("English")));
/// ``` /// ```
#[builder_impl]
pub trait SelectBootsier { pub trait SelectBootsier {
/// Establece si la etiqueta se muestra flotante sobre el campo. /// Establece si la etiqueta se muestra flotante sobre el campo.
/// ///
@ -33,12 +34,11 @@ pub trait SelectBootsier {
/// Si se usa la etiqueta flotante, se anulan los valores establecidos con /// Si se usa la etiqueta flotante, se anulan los valores establecidos con
/// [`with_multiple()`](form::select::Field::with_multiple) y /// [`with_multiple()`](form::select::Field::with_multiple) y
/// [`with_rows()`](form::select::Field::with_rows) antes del renderizado. /// [`with_rows()`](form::select::Field::with_rows) antes del renderizado.
#[builder_fn]
fn with_floating_label(self, floating: bool) -> Self; fn with_floating_label(self, floating: bool) -> Self;
} }
#[builder_impl]
impl SelectBootsier for Field { impl SelectBootsier for Field {
#[builder_fn]
fn with_floating_label(mut self, floating: bool) -> Self { fn with_floating_label(mut self, floating: bool) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating)); self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating));
self self

View file

@ -22,6 +22,7 @@ const EXTRA_FLOATING_LABEL: &str = "bootsier.form.textarea.floating_label";
/// .with_placeholder(Lc::n("Write here...")) /// .with_placeholder(Lc::n("Write here..."))
/// .with_floating_label(true); /// .with_floating_label(true);
/// ``` /// ```
#[builder_impl]
pub trait TextareaBootsier { pub trait TextareaBootsier {
/// Establece si la etiqueta se muestra flotante sobre el campo. /// Establece si la etiqueta se muestra flotante sobre el campo.
/// ///
@ -31,12 +32,11 @@ pub trait TextareaBootsier {
/// ///
/// Si se usa la etiqueta flotante, se anula el valor establecido con /// Si se usa la etiqueta flotante, se anula el valor establecido con
/// [`with_rows()`](form::Textarea::with_rows) antes del renderizado. /// [`with_rows()`](form::Textarea::with_rows) antes del renderizado.
#[builder_fn]
fn with_floating_label(self, floating: bool) -> Self; fn with_floating_label(self, floating: bool) -> Self;
} }
#[builder_impl]
impl TextareaBootsier for Textarea { impl TextareaBootsier for Textarea {
#[builder_fn]
fn with_floating_label(mut self, floating: bool) -> Self { fn with_floating_label(mut self, floating: bool) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating)); self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating));
self self

View file

@ -78,6 +78,7 @@ impl Component for Icon {
} }
} }
#[builder_impl]
impl Icon { impl Icon {
pub fn font() -> Self { pub fn font() -> Self {
Self::default().with_icon_kind(IconKind::Font(FontSize::default())) Self::default().with_icon_kind(IconKind::Font(FontSize::default()))
@ -104,26 +105,22 @@ impl Icon {
// **< Icon BUILDER >*************************************************************************** // **< Icon BUILDER >***************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
#[builder_fn]
pub fn with_icon_kind(mut self, icon_kind: IconKind) -> Self { pub fn with_icon_kind(mut self, icon_kind: IconKind) -> Self {
self.icon_kind = icon_kind; self.icon_kind = icon_kind;
self self
} }
#[builder_fn]
pub fn with_aria_label(mut self, label: Lc) -> Self { pub fn with_aria_label(mut self, label: Lc) -> Self {
self.aria_label.alter_value(label); self.aria_label.alter_value(label);
self self

View file

@ -46,14 +46,14 @@ pub(crate) const EXTRA_IN_NAVBAR: &str = "bootsier.nav.in_navbar";
/// )) /// ))
/// .with_item(bs::nav::Item::link_disabled(Lc::n("Disabled"), "#")); /// .with_item(bs::nav::Item::link_disabled(Lc::n("Disabled"), "#"));
/// ``` /// ```
#[builder_impl]
pub trait NavBootsier { pub trait NavBootsier {
/// Cambia el estilo del menú (*Tabs*, *Pills*, *Underline* o *Default*). /// Cambia el estilo del menú (*Tabs*, *Pills*, *Underline* o *Default*).
#[builder_fn]
fn with_kind(self, kind: Kind) -> Self; fn with_kind(self, kind: Kind) -> Self;
} }
#[builder_impl]
impl NavBootsier for Nav { impl NavBootsier for Nav {
#[builder_fn]
fn with_kind(mut self, kind: Kind) -> Self { fn with_kind(mut self, kind: Kind) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_KIND, kind)); self.alter_prop(PropsOp::set_extra(EXTRA_KIND, kind));
self self

View file

@ -140,6 +140,7 @@ const EXTRA_EXPAND: &str = "bootsier.navbar.expand";
/// .with_item(bs::nav::Item::link(Lc::n("Stock"), "/stock")) /// .with_item(bs::nav::Item::link(Lc::n("Stock"), "/stock"))
/// )); /// ));
/// ``` /// ```
#[builder_impl]
pub trait NavbarBootsier { pub trait NavbarBootsier {
/// Crea una barra de navegación cuyo contenido se muestra en un **offcanvas**. /// Crea una barra de navegación cuyo contenido se muestra en un **offcanvas**.
fn offcanvas(oc: bs::Offcanvas) -> Self; fn offcanvas(oc: bs::Offcanvas) -> Self;
@ -151,14 +152,13 @@ pub trait NavbarBootsier {
fn offcanvas_brand_right(brand: Brand, oc: bs::Offcanvas) -> Self; fn offcanvas_brand_right(brand: Brand, oc: bs::Offcanvas) -> Self;
/// Define a partir de qué punto de ruptura la barra de navegación deja de colapsar. /// Define a partir de qué punto de ruptura la barra de navegación deja de colapsar.
#[builder_fn]
fn with_expand(self, bp: BreakPoint) -> Self; fn with_expand(self, bp: BreakPoint) -> Self;
/// Define dónde se mostrará la barra de navegación dentro del documento. /// Define dónde se mostrará la barra de navegación dentro del documento.
#[builder_fn]
fn with_position(self, position: bs::navbar::Position) -> Self; fn with_position(self, position: bs::navbar::Position) -> Self;
} }
#[builder_impl]
impl NavbarBootsier for Navbar { impl NavbarBootsier for Navbar {
fn offcanvas(oc: bs::Offcanvas) -> Self { fn offcanvas(oc: bs::Offcanvas) -> Self {
let mut navbar = Self::new(); let mut navbar = Self::new();
@ -187,13 +187,11 @@ impl NavbarBootsier for Navbar {
navbar navbar
} }
#[builder_fn]
fn with_expand(mut self, bp: BreakPoint) -> Self { fn with_expand(mut self, bp: BreakPoint) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_EXPAND, bp)); self.alter_prop(PropsOp::set_extra(EXTRA_EXPAND, bp));
self self
} }
#[builder_fn]
fn with_position(mut self, position: bs::navbar::Position) -> Self { fn with_position(mut self, position: bs::navbar::Position) -> Self {
self.alter_prop(PropsOp::set_extra(EXTRA_POSITION, position)); self.alter_prop(PropsOp::set_extra(EXTRA_POSITION, position));
self self

View file

@ -90,25 +90,23 @@ impl Component for Offcanvas {
} }
} }
#[builder_impl]
impl Offcanvas { impl Offcanvas {
// **< Offcanvas BUILDER >********************************************************************** // **< Offcanvas BUILDER >**********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece el título del encabezado. /// Establece el título del encabezado.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
@ -123,7 +121,6 @@ impl Offcanvas {
/// Por ejemplo, con `BreakPoint::Lg`, será *offcanvas* en móviles y tabletas, y visible /// Por ejemplo, con `BreakPoint::Lg`, será *offcanvas* en móviles y tabletas, y visible
/// directamente en pantallas grandes. Por defecto usa `BreakPoint::None` para que sea /// directamente en pantallas grandes. Por defecto usa `BreakPoint::None` para que sea
/// *offcanvas* siempre. /// *offcanvas* siempre.
#[builder_fn]
pub fn with_breakpoint(mut self, bp: BreakPoint) -> Self { pub fn with_breakpoint(mut self, bp: BreakPoint) -> Self {
self.breakpoint = bp; self.breakpoint = bp;
self self
@ -131,28 +128,24 @@ impl Offcanvas {
/// Ajusta la capa de fondo del panel para definir su comportamiento al hacer clic fuera del /// Ajusta la capa de fondo del panel para definir su comportamiento al hacer clic fuera del
/// panel. /// panel.
#[builder_fn]
pub fn with_backdrop(mut self, backdrop: bs::offcanvas::Backdrop) -> Self { pub fn with_backdrop(mut self, backdrop: bs::offcanvas::Backdrop) -> Self {
self.backdrop = backdrop; self.backdrop = backdrop;
self self
} }
/// Permite o bloquea el desplazamiento de la página principal mientras el panel está abierto. /// Permite o bloquea el desplazamiento de la página principal mientras el panel está abierto.
#[builder_fn]
pub fn with_body_scroll(mut self, scrolling: bs::offcanvas::BodyScroll) -> Self { pub fn with_body_scroll(mut self, scrolling: bs::offcanvas::BodyScroll) -> Self {
self.body_scroll = scrolling; self.body_scroll = scrolling;
self self
} }
/// Indica desde qué borde de la ventana entra y se ancla el panel. /// Indica desde qué borde de la ventana entra y se ancla el panel.
#[builder_fn]
pub fn with_placement(mut self, placement: bs::offcanvas::Placement) -> Self { pub fn with_placement(mut self, placement: bs::offcanvas::Placement) -> Self {
self.placement = placement; self.placement = placement;
self self
} }
/// Fija el estado inicial del panel (oculto o visible al cargar). /// Fija el estado inicial del panel (oculto o visible al cargar).
#[builder_fn]
pub fn with_visibility(mut self, visibility: bs::offcanvas::Visibility) -> Self { pub fn with_visibility(mut self, visibility: bs::offcanvas::Visibility) -> Self {
self.visibility = visibility; self.visibility = visibility;
self self
@ -160,7 +153,6 @@ impl Offcanvas {
/// Añade un nuevo componente al panel o modifica la lista de componentes (`children`) con una /// Añade un nuevo componente al panel o modifica la lista de componentes (`children`) con una
/// operación [`ChildOp`]. /// operación [`ChildOp`].
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -65,6 +65,7 @@ impl Component for Item {
} }
} }
#[builder_impl]
impl Item { impl Item {
/// Crea un ítem de navegación con etiqueta, ruta e icono. /// Crea un ítem de navegación con etiqueta, ruta e icono.
/// ///
@ -82,21 +83,18 @@ impl Item {
// **< Item BUILDER >*************************************************************************** // **< Item BUILDER >***************************************************************************
/// Establece el texto localizable del ítem. /// Establece el texto localizable del ítem.
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece la ruta de destino del ítem. /// Establece la ruta de destino del ítem.
#[builder_fn]
pub fn with_route(mut self, route: impl Into<Option<Route>>) -> Self { pub fn with_route(mut self, route: impl Into<Option<Route>>) -> Self {
self.route = route.into(); self.route = route.into();
self self
} }
/// Establece el nombre del icono de Bootstrap Icons (sin el prefijo `bi-`). /// Establece el nombre del icono de Bootstrap Icons (sin el prefijo `bi-`).
#[builder_fn]
pub fn with_icon(mut self, icon: impl Into<CowStr>) -> Self { pub fn with_icon(mut self, icon: impl Into<CowStr>) -> Self {
self.icon = icon.into(); self.icon = icon.into();
self self

View file

@ -40,6 +40,7 @@ impl Component for Section {
} }
} }
#[builder_impl]
impl Section { impl Section {
/// Crea un encabezado de sección con el título indicado. /// Crea un encabezado de sección con el título indicado.
pub fn titled(title: Lc) -> Self { pub fn titled(title: Lc) -> Self {
@ -49,7 +50,6 @@ impl Section {
// **< Section BUILDER >************************************************************************ // **< Section BUILDER >************************************************************************
/// Establece el título localizable de la sección. /// Establece el título localizable de la sección.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self

View file

@ -107,6 +107,7 @@ impl Component for MenuBlock {
} }
} }
#[builder_impl]
impl MenuBlock { impl MenuBlock {
/// Crea un `MenuBlock` para el menú con el `machine_name` dado. /// Crea un `MenuBlock` para el menú con el `machine_name` dado.
pub fn with(menu_name: impl Into<String>) -> Self { pub fn with(menu_name: impl Into<String>) -> Self {
@ -115,7 +116,6 @@ impl MenuBlock {
block block
} }
#[builder_fn]
pub fn with_show_title(mut self, v: impl Into<Option<bool>>) -> Self { pub fn with_show_title(mut self, v: impl Into<Option<bool>>) -> Self {
if let Some(v) = v.into() { if let Some(v) = v.into() {
self.show_title = v; self.show_title = v;
@ -125,13 +125,11 @@ impl MenuBlock {
/// Establece la profundidad máxima de nodos a incluir. El efectivo nunca supera `2`, por muy /// Establece la profundidad máxima de nodos a incluir. El efectivo nunca supera `2`, por muy
/// alto que sea el valor indicado (ver "Limitaciones conocidas" en [`MenuBlock`]). /// alto que sea el valor indicado (ver "Limitaciones conocidas" en [`MenuBlock`]).
#[builder_fn]
pub fn with_max_depth(mut self, v: impl Into<Option<u8>>) -> Self { pub fn with_max_depth(mut self, v: impl Into<Option<u8>>) -> Self {
self.max_depth = v.into(); self.max_depth = v.into();
self self
} }
#[builder_fn]
pub fn with_include_disabled(mut self, v: impl Into<Option<bool>>) -> Self { pub fn with_include_disabled(mut self, v: impl Into<Option<bool>>) -> Self {
if let Some(v) = v.into() { if let Some(v) = v.into() {
self.include_disabled = v; self.include_disabled = v;
@ -139,7 +137,6 @@ impl MenuBlock {
self self
} }
#[builder_fn]
pub fn with_hide_when_empty(mut self, v: impl Into<Option<bool>>) -> Self { pub fn with_hide_when_empty(mut self, v: impl Into<Option<bool>>) -> Self {
if let Some(v) = v.into() { if let Some(v) = v.into() {
self.hide_when_empty = v; self.hide_when_empty = v;

View file

@ -73,6 +73,7 @@ impl Component for MenuBreadcrumb {
} }
} }
#[builder_impl]
impl MenuBreadcrumb { impl MenuBreadcrumb {
/// Crea un `MenuBreadcrumb` para el menú con el `machine_name` dado. /// Crea un `MenuBreadcrumb` para el menú con el `machine_name` dado.
pub fn with(menu_name: impl Into<String>) -> Self { pub fn with(menu_name: impl Into<String>) -> Self {
@ -81,7 +82,6 @@ impl MenuBreadcrumb {
bc bc
} }
#[builder_fn]
pub fn with_include_current(mut self, v: impl Into<Option<bool>>) -> Self { pub fn with_include_current(mut self, v: impl Into<Option<bool>>) -> Self {
if let Some(v) = v.into() { if let Some(v) = v.into() {
self.include_current = v; self.include_current = v;

View file

@ -43,22 +43,20 @@ impl Component for AdminPasswordForm {
} }
} }
#[builder_impl]
impl AdminPasswordForm { impl AdminPasswordForm {
// **< AdminPasswordForm BUILDER >************************************************************** // **< AdminPasswordForm BUILDER >**************************************************************
#[builder_fn]
pub(crate) fn with_user_id(mut self, user_id: i32) -> Self { pub(crate) fn with_user_id(mut self, user_id: i32) -> Self {
self.user_id = user_id; self.user_id = user_id;
self self
} }
#[builder_fn]
pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self
} }
#[builder_fn]
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self { pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into(); self.waypoint = waypoint.into();
self self

View file

@ -98,52 +98,45 @@ impl Component for RoleForm {
} }
} }
#[builder_impl]
impl RoleForm { impl RoleForm {
// **< RoleForm BUILDER >*********************************************************************** // **< RoleForm BUILDER >***********************************************************************
#[builder_fn]
pub(crate) fn with_mode(mut self, mode: RoleFormMode) -> Self { pub(crate) fn with_mode(mut self, mode: RoleFormMode) -> Self {
self.mode = mode; self.mode = mode;
self self
} }
#[builder_fn]
pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self
} }
#[builder_fn]
pub(crate) fn with_role_id(mut self, role_id: impl Into<Option<i32>>) -> Self { pub(crate) fn with_role_id(mut self, role_id: impl Into<Option<i32>>) -> Self {
self.role_id = role_id.into(); self.role_id = role_id.into();
self self
} }
#[builder_fn]
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self { pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into(); self.waypoint = waypoint.into();
self self
} }
#[builder_fn]
pub(crate) fn with_machine_name(mut self, machine_name: impl Into<String>) -> Self { pub(crate) fn with_machine_name(mut self, machine_name: impl Into<String>) -> Self {
self.machine_name = machine_name.into(); self.machine_name = machine_name.into();
self self
} }
#[builder_fn]
pub(crate) fn with_label(mut self, label: impl Into<String>) -> Self { pub(crate) fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = label.into(); self.label = label.into();
self self
} }
#[builder_fn]
pub(crate) fn with_description(mut self, description: impl Into<String>) -> Self { pub(crate) fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = description.into(); self.description = description.into();
self self
} }
#[builder_fn]
pub(crate) fn with_weight(mut self, weight: i32) -> Self { pub(crate) fn with_weight(mut self, weight: i32) -> Self {
self.weight = weight; self.weight = weight;
self self

View file

@ -61,28 +61,25 @@ impl Component for RolePermissionsForm {
} }
} }
#[builder_impl]
impl RolePermissionsForm { impl RolePermissionsForm {
// **< RolePermissionsForm BUILDER >************************************************************ // **< RolePermissionsForm BUILDER >************************************************************
#[builder_fn]
pub(crate) fn with_role_id(mut self, role_id: i32) -> Self { pub(crate) fn with_role_id(mut self, role_id: i32) -> Self {
self.role_id = role_id; self.role_id = role_id;
self self
} }
#[builder_fn]
pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self
} }
#[builder_fn]
pub(crate) fn with_groups(mut self, groups: PermissionGroups) -> Self { pub(crate) fn with_groups(mut self, groups: PermissionGroups) -> Self {
self.groups = groups; self.groups = groups;
self self
} }
#[builder_fn]
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self { pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into(); self.waypoint = waypoint.into();
self self

View file

@ -128,52 +128,45 @@ impl Component for RoleTable {
} }
} }
#[builder_impl]
impl RoleTable { impl RoleTable {
// **< RoleTable BUILDER >********************************************************************** // **< RoleTable BUILDER >**********************************************************************
#[builder_fn]
pub(crate) fn with_prop(mut self, op: PropsOp) -> Self { pub(crate) fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
#[builder_fn]
pub(crate) fn with_items(mut self, items: Vec<RoleListItem>) -> Self { pub(crate) fn with_items(mut self, items: Vec<RoleListItem>) -> Self {
self.items = items; self.items = items;
self self
} }
#[builder_fn]
pub(crate) fn with_message(mut self, message: impl Into<Option<Lc>>) -> Self { pub(crate) fn with_message(mut self, message: impl Into<Option<Lc>>) -> Self {
self.message = message.into(); self.message = message.into();
self self
} }
#[builder_fn]
pub(crate) fn with_sort(mut self, sort: RoleSortField) -> Self { pub(crate) fn with_sort(mut self, sort: RoleSortField) -> Self {
self.sort = sort; self.sort = sort;
self self
} }
#[builder_fn]
pub(crate) fn with_dir(mut self, dir: SortDir) -> Self { pub(crate) fn with_dir(mut self, dir: SortDir) -> Self {
self.dir = dir; self.dir = dir;
self self
} }
#[builder_fn]
pub(crate) fn with_page(mut self, page: u64) -> Self { pub(crate) fn with_page(mut self, page: u64) -> Self {
self.page = page; self.page = page;
self self
} }
#[builder_fn]
pub(crate) fn with_per_page(mut self, per_page: u64) -> Self { pub(crate) fn with_per_page(mut self, per_page: u64) -> Self {
self.per_page = per_page; self.per_page = per_page;
self self
} }
#[builder_fn]
pub(crate) fn with_total(mut self, total: u64) -> Self { pub(crate) fn with_total(mut self, total: u64) -> Self {
self.total = total; self.total = total;
self self

View file

@ -121,76 +121,65 @@ impl Component for UserForm {
} }
} }
#[builder_impl]
impl UserForm { impl UserForm {
// **< UserForm BUILDER >*********************************************************************** // **< UserForm BUILDER >***********************************************************************
#[builder_fn]
pub(crate) fn with_mode(mut self, mode: UserFormMode) -> Self { pub(crate) fn with_mode(mut self, mode: UserFormMode) -> Self {
self.mode = mode; self.mode = mode;
self self
} }
#[builder_fn]
pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self
} }
#[builder_fn]
pub(crate) fn with_user_id(mut self, user_id: impl Into<Option<i32>>) -> Self { pub(crate) fn with_user_id(mut self, user_id: impl Into<Option<i32>>) -> Self {
self.user_id = user_id.into(); self.user_id = user_id.into();
self self
} }
#[builder_fn]
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self { pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into(); self.waypoint = waypoint.into();
self self
} }
#[builder_fn]
pub(crate) fn with_username(mut self, username: impl Into<String>) -> Self { pub(crate) fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = username.into(); self.username = username.into();
self self
} }
#[builder_fn]
pub(crate) fn with_email(mut self, email: impl Into<String>) -> Self { pub(crate) fn with_email(mut self, email: impl Into<String>) -> Self {
self.email = email.into(); self.email = email.into();
self self
} }
#[builder_fn]
pub(crate) fn with_display_name(mut self, display_name: impl Into<String>) -> Self { pub(crate) fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
self.display_name = display_name.into(); self.display_name = display_name.into();
self self
} }
#[builder_fn]
pub(crate) fn with_language(mut self, language: impl Into<String>) -> Self { pub(crate) fn with_language(mut self, language: impl Into<String>) -> Self {
self.language = language.into(); self.language = language.into();
self self
} }
#[builder_fn]
pub(crate) fn with_timezone(mut self, timezone: impl Into<String>) -> Self { pub(crate) fn with_timezone(mut self, timezone: impl Into<String>) -> Self {
self.timezone = timezone.into(); self.timezone = timezone.into();
self self
} }
#[builder_fn]
pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self { pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self {
self.roles = roles; self.roles = roles;
self self
} }
#[builder_fn]
pub(crate) fn with_allow_admin_field(mut self, allow_admin_field: bool) -> Self { pub(crate) fn with_allow_admin_field(mut self, allow_admin_field: bool) -> Self {
self.allow_admin_field = allow_admin_field; self.allow_admin_field = allow_admin_field;
self self
} }
#[builder_fn]
pub(crate) fn with_is_admin(mut self, is_admin: bool) -> Self { pub(crate) fn with_is_admin(mut self, is_admin: bool) -> Self {
self.is_admin = is_admin; self.is_admin = is_admin;
self self

View file

@ -43,28 +43,25 @@ impl Component for UserRolesForm {
} }
} }
#[builder_impl]
impl UserRolesForm { impl UserRolesForm {
// **< UserRolesForm BUILDER >****************************************************************** // **< UserRolesForm BUILDER >******************************************************************
#[builder_fn]
pub(crate) fn with_user_id(mut self, user_id: i32) -> Self { pub(crate) fn with_user_id(mut self, user_id: i32) -> Self {
self.user_id = user_id; self.user_id = user_id;
self self
} }
#[builder_fn]
pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self
} }
#[builder_fn]
pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self { pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self {
self.roles = roles; self.roles = roles;
self self
} }
#[builder_fn]
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self { pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into(); self.waypoint = waypoint.into();
self self

View file

@ -100,52 +100,45 @@ impl Component for UserTable {
} }
} }
#[builder_impl]
impl UserTable { impl UserTable {
// **< UserTable BUILDER >********************************************************************** // **< UserTable BUILDER >**********************************************************************
#[builder_fn]
pub(crate) fn with_prop(mut self, op: PropsOp) -> Self { pub(crate) fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
#[builder_fn]
pub(crate) fn with_items(mut self, items: Vec<UserListItem>) -> Self { pub(crate) fn with_items(mut self, items: Vec<UserListItem>) -> Self {
self.items = items; self.items = items;
self self
} }
#[builder_fn]
pub(crate) fn with_sort(mut self, sort: UserSortField) -> Self { pub(crate) fn with_sort(mut self, sort: UserSortField) -> Self {
self.sort = sort; self.sort = sort;
self self
} }
#[builder_fn]
pub(crate) fn with_dir(mut self, dir: SortDir) -> Self { pub(crate) fn with_dir(mut self, dir: SortDir) -> Self {
self.dir = dir; self.dir = dir;
self self
} }
#[builder_fn]
pub(crate) fn with_query(mut self, query: impl Into<Option<String>>) -> Self { pub(crate) fn with_query(mut self, query: impl Into<Option<String>>) -> Self {
self.query = query.into(); self.query = query.into();
self self
} }
#[builder_fn]
pub(crate) fn with_page(mut self, page: u64) -> Self { pub(crate) fn with_page(mut self, page: u64) -> Self {
self.page = page; self.page = page;
self self
} }
#[builder_fn]
pub(crate) fn with_per_page(mut self, per_page: u64) -> Self { pub(crate) fn with_per_page(mut self, per_page: u64) -> Self {
self.per_page = per_page; self.per_page = per_page;
self self
} }
#[builder_fn]
pub(crate) fn with_total(mut self, total: u64) -> Self { pub(crate) fn with_total(mut self, total: u64) -> Self {
self.total = total; self.total = total;
self self

View file

@ -97,14 +97,13 @@ fn links(allow_registration: bool) -> Html {
}) })
} }
#[builder_impl]
impl LoginForm { impl LoginForm {
#[builder_fn]
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self
} }
#[builder_fn]
pub fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self { pub fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into(); self.waypoint = waypoint.into();
self self

View file

@ -48,18 +48,17 @@ impl Component for PasswordConfirm {
} }
} }
#[builder_impl]
impl PasswordConfirm { impl PasswordConfirm {
// **< PasswordConfirm BUILDER >******************************************************************** // **< PasswordConfirm BUILDER >********************************************************************
/// Establece la etiqueta del campo de contraseña (por defecto, "field-password"). /// Establece la etiqueta del campo de contraseña (por defecto, "field-password").
#[builder_fn]
pub(crate) fn with_password_label(mut self, label: Lc) -> Self { pub(crate) fn with_password_label(mut self, label: Lc) -> Self {
self.password_label = label; self.password_label = label;
self self
} }
/// Establece la etiqueta del campo de confirmación (por defecto, "field-confirm-password"). /// Establece la etiqueta del campo de confirmación (por defecto, "field-confirm-password").
#[builder_fn]
pub(crate) fn with_confirm_label(mut self, label: Lc) -> Self { pub(crate) fn with_confirm_label(mut self, label: Lc) -> Self {
self.confirm_label = label; self.confirm_label = label;
self self

View file

@ -44,8 +44,8 @@ impl Component for PasswordResetConfirmForm {
} }
} }
#[builder_impl]
impl PasswordResetConfirmForm { impl PasswordResetConfirmForm {
#[builder_fn]
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self

View file

@ -49,8 +49,8 @@ fn back_to_login() -> Html {
}) })
} }
#[builder_impl]
impl PasswordResetForm { impl PasswordResetForm {
#[builder_fn]
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self

View file

@ -45,8 +45,8 @@ impl Component for RegisterForm {
} }
} }
#[builder_impl]
impl RegisterForm { impl RegisterForm {
#[builder_fn]
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self { pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into(); self.error = error.into();
self self

View file

@ -0,0 +1,449 @@
//! Núcleo compartido de `#[builder_fn]` y `#[builder_impl]`.
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{
Attribute, Block, FnArg, Ident, ImplItem, ImplItemFn, ItemImpl, ItemTrait, Pat, ReturnType,
Signature, TraitItem, TraitItemFn, Type, Visibility, WhereClause, parse_quote, parse2,
};
// Genera el código común a `#[builder_fn]` y `#[builder_impl]` para un único método `with_...()`.
//
// Recibe las piezas ya extraídas de un `ImplItemFn` o de un `TraitItemFn`: firma, atributos,
// visibilidad (ausente en métodos de trait), cuerpo (ausente en la declaración de un método trait
// sin implementación por defecto) y si el receptor es de trait (`self`) o de impl (`mut self`).
fn expand_builder(
sig: &Signature,
attrs: &[Attribute],
vis: Option<&Visibility>,
body_opt: Option<&Block>,
is_trait: bool,
) -> TokenStream {
let with_name = sig.ident.clone();
let with_name_str = sig.ident.to_string();
// Valida el nombre del método.
if !with_name_str.starts_with("with_") {
return quote_spanned! {
sig.ident.span() => compile_error!("expected a named `with_...()` method");
};
}
// Sólo se exige `pub` en `impl` (en `trait` no aplica).
let vis_pub = match (is_trait, vis) {
(false, Some(v)) => quote! { #v },
_ => quote! {},
};
// Validaciones comunes.
if sig.asyncness.is_some() {
return quote_spanned! {
sig.asyncness.span() => compile_error!("`with_...()` cannot be `async`");
};
}
if sig.constness.is_some() {
return quote_spanned! {
sig.constness.span() => compile_error!("`with_...()` cannot be `const`");
};
}
if sig.abi.is_some() {
return quote_spanned! {
sig.abi.span() => compile_error!("`with_...()` cannot be `extern`");
};
}
if sig.unsafety.is_some() {
return quote_spanned! {
sig.unsafety.span() => compile_error!("`with_...()` cannot be `unsafe`");
};
}
// En `impl` se exige exactamente `mut self`; y en `trait` se exige `self` (sin &).
let receiver_ok = match sig.inputs.first() {
Some(FnArg::Receiver(r)) => {
// Rechaza `self: SomeType`.
if r.colon_token.is_some() {
false
} else if is_trait {
// Exactamente `self` (sin &, sin mut).
r.reference.is_none() && r.mutability.is_none()
} else {
// Exactamente `mut self`.
r.reference.is_none() && r.mutability.is_some()
}
}
_ => false,
};
if !receiver_ok {
let msg = if is_trait {
"expected `self` (not `mut self`, `&self` or `&mut self`) in trait method"
} else {
"expected first argument to be exactly `mut self`"
};
let err = sig
.inputs
.first()
.map(|a| a.span())
.unwrap_or(sig.ident.span());
return quote_spanned! {
err => compile_error!(#msg);
};
}
// Valida que el método devuelve exactamente `Self`.
match &sig.output {
ReturnType::Type(_, ty) => match ty.as_ref() {
Type::Path(p) if p.qself.is_none() && p.path.is_ident("Self") => {}
_ => {
return quote_spanned! {
ty.span() => compile_error!("expected return type to be exactly `Self`");
};
}
},
_ => {
return quote_spanned! {
sig.output.span() => compile_error!("expected return type to be exactly `Self`");
};
}
}
// Genera el nombre del método `alter_...()`.
let stem = with_name_str.strip_prefix("with_").expect("validated");
let alter_ident = Ident::new(&format!("alter_{stem}"), with_name.span());
// Extrae genéricos y cláusulas `where`.
let generics = &sig.generics;
let where_clause = &sig.generics.where_clause;
// Extrae identificadores de los argumentos para la llamada (sin `mut` ni patrones complejos).
let args: Vec<_> = sig.inputs.iter().skip(1).collect();
let call_idents: Vec<Ident> = {
let mut v = Vec::new();
for arg in sig.inputs.iter().skip(1) {
match arg {
FnArg::Typed(pat) => {
if let Pat::Ident(pat_ident) = pat.pat.as_ref() {
v.push(pat_ident.ident.clone());
} else {
return quote_spanned! {
pat.pat.span() => compile_error!(
"each parameter must be a simple identifier, e.g. `value: T`"
);
};
}
}
_ => {
return quote_spanned! {
arg.span() => compile_error!("unexpected receiver in parameter list");
};
}
}
}
v
};
// Separa atributos de documentación y resto.
let mut doc_attrs = Vec::new();
let mut other_attrs = Vec::new();
let mut non_doc_or_inline_attrs = Vec::new();
for a in attrs.iter() {
let p = a.path();
if p.is_ident("doc") {
doc_attrs.push(a.clone());
} else {
other_attrs.push(a.clone());
if !p.is_ident("inline") {
non_doc_or_inline_attrs.push(a.clone());
}
}
}
// Firma resumida de la función `alter_...()` para mostrarla en la doc de `with_...()`.
let alter_sig_tokens = if args.is_empty() {
// Sin argumentos sólo se muestra `&mut self` (puede que no tenga mucho sentido).
quote! { #vis_pub fn #alter_ident #generics (&mut self) -> &mut Self #where_clause }
} else {
// Con argumentos se muestra `&mut self, ...`.
quote! { #vis_pub fn #alter_ident #generics (&mut self, ...) -> &mut Self #where_clause }
};
// Normaliza espacios raros tipo `& mut`.
let alter_sig_str = alter_sig_tokens.to_string().replace("& mut", "&mut");
// Nombre de la función `alter_...()` como alias de búsqueda.
let alter_name_str = alter_ident.to_string();
// Texto introductorio para la documentación adicional de `with_...()`.
let with_alter_title = format!(
"# {} el método `{}()` generado por [`#[builder_fn]`](pagetop_macros::builder_fn)",
if doc_attrs.is_empty() {
"Añade"
} else {
"También añade"
},
alter_name_str
);
let with_alter_doc = concat!(
"Permite modificar la instancia (`&mut self`) con los mismos argumentos ",
"pero sin consumirla."
);
// Atributos completos que se aplican siempre a `with_...()`.
let with_prefix = quote! {
#(#other_attrs)*
#(#doc_attrs)*
#[doc(alias = #alter_name_str)]
#[doc = ""]
#[doc = #with_alter_title]
#[doc = #with_alter_doc]
#[doc = "```text"]
#[doc = #alter_sig_str]
#[doc = "```"]
};
// Genera el código final.
match body_opt {
None => {
quote! {
#with_prefix
fn #with_name #generics (self, #(#args),*) -> Self #where_clause;
#(#non_doc_or_inline_attrs)*
#[doc(hidden)]
fn #alter_ident #generics (&mut self, #(#args),*) -> &mut Self #where_clause;
}
}
Some(body) => {
// Si no se indicó ninguna forma de `inline`, fuerza `#[inline]` para `with_...()`.
let force_inline = if attrs.iter().any(|a| a.path().is_ident("inline")) {
quote! {}
} else {
quote! { #[inline] }
};
let with_fn = if is_trait {
// Un cuerpo por defecto se compila junto a la propia definición del trait, donde
// `Self` podría no ser `Sized`; a diferencia de una declaración sin cuerpo (rama
// `None`), aquí sí hace falta acotarlo explícitamente para poder devolver `Self`
// por valor. Se añade la cota sobre el `Punctuated` ya existente (en vez de
// concatenar tokens a mano) para que la coma se coloque bien incluso si el `where`
// original ya termina en una.
let with_where: WhereClause = match where_clause {
Some(wc) => {
let mut wc = wc.clone();
wc.predicates.push(parse_quote!(Self: Sized));
wc
}
None => parse_quote!(where Self: Sized),
};
quote! {
#with_prefix
#force_inline
#vis_pub fn #with_name #generics (self, #(#args),*) -> Self #with_where {
let mut s = self;
s.#alter_ident(#(#call_idents),*);
s
}
}
} else {
quote! {
#with_prefix
#force_inline
#vis_pub fn #with_name #generics (mut self, #(#args),*) -> Self #where_clause {
self.#alter_ident(#(#call_idents),*);
self
}
}
};
quote! {
#with_fn
#(#non_doc_or_inline_attrs)*
#[doc(hidden)]
#vis_pub fn #alter_ident #generics (&mut self, #(#args),*) -> &mut Self #where_clause {
#body
}
}
}
}
}
// Implementa `#[builder_fn]`: detecta si el ítem anotado es un método de `impl` o de `trait`,
// extrae sus piezas comunes y delega en `expand_builder`.
pub(crate) fn expand_fn(item: TokenStream) -> TokenStream {
enum Kind {
Impl(ImplItemFn),
Trait(TraitItemFn),
}
// Detecta si estamos en `impl` o `trait`.
let kind = if let Ok(it) = parse2::<ImplItemFn>(item.clone()) {
Kind::Impl(it)
} else if let Ok(tt) = parse2::<TraitItemFn>(item.clone()) {
Kind::Trait(tt)
} else {
return quote! {
compile_error!("#[builder_fn] only supports methods in `impl` blocks or `trait` items");
};
};
// Extrae piezas comunes (sig, attrs, vis, bloque?, es_trait?).
let (sig, attrs, vis, body_opt, is_trait) = match &kind {
Kind::Impl(m) => (&m.sig, &m.attrs, Some(&m.vis), Some(&m.block), false),
Kind::Trait(t) => (&t.sig, &t.attrs, None, t.default.as_ref(), true),
};
expand_builder(sig, attrs, vis, body_opt, is_trait)
}
// Comprueba si la lista de atributos contiene uno con el nombre dado.
fn has_attr(attrs: &[Attribute], name: &str) -> bool {
attrs.iter().any(|a| a.path().is_ident(name))
}
// Decide qué hacer con un único método durante el barrido de `#[builder_impl]`, sea de un `impl`
// o de un `trait`. Devuelve `None` si el método no es un `with_...()` a barrer (ni siquiera marcado
// con `#[builder_skip]`), en cuyo caso el llamador lo reemite intacto.
fn sweep_with_fn(
sig: &Signature,
attrs: &[Attribute],
vis: Option<&Visibility>,
body_opt: Option<&Block>,
is_trait: bool,
) -> Option<TokenStream> {
if !sig.ident.to_string().starts_with("with_") {
return None;
}
let skip = has_attr(attrs, "builder_skip");
// Se rechaza `with_...()` marcado a la vez con `#[builder_skip]` y `#[builder_fn]`.
if skip && has_attr(attrs, "builder_fn") {
return Some(quote_spanned! {
sig.ident.span() => compile_error!(
"`#[builder_skip]` and `#[builder_fn]` cannot be combined on the same method"
);
});
}
if skip {
return None;
}
// Descarta atributos auxiliares para no reprocesar ni dejar atributos desconocidos.
let clean: Vec<Attribute> = attrs
.iter()
.filter(|a| !a.path().is_ident("builder_fn") && !a.path().is_ident("builder_skip"))
.cloned()
.collect();
Some(expand_builder(sig, &clean, vis, body_opt, is_trait))
}
// Implementa `#[builder_impl]`: aplica `expand_builder` a todos los métodos `with_...()` de un
// bloque `impl` o de una definición de `trait`, dejando el resto de ítems intactos.
pub(crate) fn expand_impl(item: TokenStream) -> TokenStream {
if let Ok(item_impl) = parse2::<ItemImpl>(item.clone()) {
return expand_item_impl(item_impl);
}
if let Ok(item_trait) = parse2::<ItemTrait>(item) {
return expand_item_trait(item_trait);
}
quote! {
compile_error!("#[builder_impl] only supports `impl` blocks or `trait` definitions");
}
}
fn expand_item_impl(item: ItemImpl) -> TokenStream {
let ItemImpl {
attrs,
defaultness,
unsafety,
impl_token,
generics,
trait_,
self_ty,
items,
..
} = item;
let mut out = Vec::new();
for it in items {
match it {
ImplItem::Fn(f) => {
match sweep_with_fn(&f.sig, &f.attrs, Some(&f.vis), Some(&f.block), false) {
Some(ts) => out.push(ts),
None => {
// Método no-builder (o `with_...()` marcado con `#[builder_skip]`): se
// reemite intacto, retirando siempre `#[builder_skip]` (atributo inerte).
let mut f = f;
f.attrs.retain(|a| !a.path().is_ident("builder_skip"));
out.push(quote! { #f });
}
}
}
other => out.push(quote! { #other }),
}
}
let (impl_generics, _type_generics, where_clause) = generics.split_for_impl();
// Reconstruye la parte `Trait for` si el impl es de trait.
let trait_ = trait_.map(|(bang, path, for_token)| quote! { #bang #path #for_token });
quote! {
#(#attrs)*
#defaultness #unsafety #impl_token #impl_generics #trait_ #self_ty #where_clause {
#(#out)*
}
}
}
fn expand_item_trait(item: ItemTrait) -> TokenStream {
let ItemTrait {
attrs,
vis,
unsafety,
auto_token,
trait_token,
ident,
generics,
colon_token,
supertraits,
items,
..
} = item;
let mut out = Vec::new();
for it in items {
match it {
TraitItem::Fn(f) => {
match sweep_with_fn(&f.sig, &f.attrs, None, f.default.as_ref(), true) {
Some(ts) => out.push(ts),
None => {
// Método no-builder (o `with_...()` marcado con `#[builder_skip]`): se
// reemite intacto, retirando siempre `#[builder_skip]` (atributo inerte).
let mut f = f;
f.attrs.retain(|a| !a.path().is_ident("builder_skip"));
out.push(quote! { #f });
}
}
}
other => out.push(quote! { #other }),
}
}
// El propio nombre de la lista de genéricos (`<T: Bound>`) es el que lleva las cotas en una
// definición de trait, a diferencia de su uso como tipo; por eso se usa `impl_generics` y no
// `type_generics` para reconstruir `trait Nombre<...>`.
let (impl_generics, _type_generics, where_clause) = generics.split_for_impl();
quote! {
#(#attrs)*
#vis #unsafety #auto_token #trait_token #ident #impl_generics
#colon_token #supertraits
#where_clause
{
#(#out)*
}
}
}

View file

@ -34,12 +34,13 @@ cada proyecto PageTop.
html_favicon_url = "https://git.cillero.es/manuelcillero/pagetop/raw/branch/main/assets/favicon.ico" html_favicon_url = "https://git.cillero.es/manuelcillero/pagetop/raw/branch/main/assets/favicon.ico"
)] )]
mod builder;
mod maud; mod maud;
mod smart_default; mod smart_default;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::{quote, quote_spanned}; use quote::quote;
use syn::{DeriveInput, ItemFn, parse_macro_input, spanned::Spanned}; use syn::{DeriveInput, ItemFn, parse_macro_input};
/// Macro para escribir plantillas HTML (basada en [Maud](https://docs.rs/maud)). /// Macro para escribir plantillas HTML (basada en [Maud](https://docs.rs/maud)).
#[proc_macro] #[proc_macro]
@ -162,280 +163,84 @@ pub fn derive_auto_default(input: TokenStream) -> TokenStream {
/// La documentación del método `with_...()` incluirá también la firma resumida del método /// La documentación del método `with_...()` incluirá también la firma resumida del método
/// `alter_...()` y un alias de búsqueda con su nombre, de tal manera que buscando `alter_...` en la /// `alter_...()` y un alias de búsqueda con su nombre, de tal manera que buscando `alter_...` en la
/// documentación se mostrará la entrada del método `with_...()`. /// documentación se mostrará la entrada del método `with_...()`.
///
/// Para aplicar la misma transformación a todos los métodos `with_...()` de un `impl` de una sola
/// vez, usa [`#[builder_impl]`](builder_impl).
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn builder_fn(_: TokenStream, item: TokenStream) -> TokenStream { pub fn builder_fn(_: TokenStream, item: TokenStream) -> TokenStream {
use syn::{FnArg, Ident, ImplItemFn, Pat, ReturnType, TraitItemFn, Type, parse2}; builder::expand_fn(item.into()).into()
let ts: proc_macro2::TokenStream = item.clone().into();
enum Kind {
Impl(ImplItemFn),
Trait(TraitItemFn),
} }
// Detecta si estamos en `impl` o `trait`. /// Macro (*attribute*) que aplica [`#[builder_fn]`](builder_fn) a los métodos `with_` de un
let kind = if let Ok(it) = parse2::<ImplItemFn>(ts.clone()) { /// `impl`/`trait`.
Kind::Impl(it) ///
} else if let Ok(tt) = parse2::<TraitItemFn>(ts.clone()) { /// Cada método que empiece por `with_` se transforma igual que si llevara `#[builder_fn]`
Kind::Trait(tt) /// individualmente: se genera su correspondiente método `alter_...()` y se añade la misma
} else { /// documentación. El resto de ítems del bloque (métodos que no empiecen por `with_`, constantes
return quote! { /// asociadas, tipos, etc.) no se modifican.
compile_error!("#[builder_fn] only supports methods in `impl` blocks or `trait` items"); ///
} /// La política es estricta; si un método `with_...()` no cumple la firma esperada por
.into(); /// [`#[builder_fn]`](builder_fn) para su contexto, la macro emite el mismo error de compilación que
}; /// emitiría `#[builder_fn]` sobre ese método. Para excluir deliberadamente un método `with_...()`,
/// márcalo con `#[builder_skip]`; se mantendrá intacto, como cualquier otro método que no sea
// Extrae piezas comunes (sig, attrs, vis, bloque?, es_trait?). /// *builder*.
let (sig, attrs, vis, body_opt, is_trait) = match &kind { ///
Kind::Impl(m) => (&m.sig, &m.attrs, Some(&m.vis), Some(&m.block), false), /// Un `#[builder_fn]` explícito sobre un método dentro de un bloque `#[builder_impl]` es
Kind::Trait(t) => (&t.sig, &t.attrs, None, t.default.as_ref(), true), /// redundante pero inofensivo, no se expande dos veces. Combinar `#[builder_skip]` y
}; /// `#[builder_fn]` sobre el mismo método sí es un error de compilación porque la intención de ambos
/// atributos sí es contradictoria.
let with_name = sig.ident.clone(); ///
let with_name_str = sig.ident.to_string(); /// # Ejemplo
///
// Valida el nombre del método. /// ```rust,no_run
if !with_name_str.starts_with("with_") { /// # use pagetop_macros::builder_impl;
return quote_spanned! { /// # #[derive(Default)]
sig.ident.span() => compile_error!("expected a named `with_...()` method"); /// # struct Example { a: Option<String>, b: Option<u32> }
} /// #[builder_impl]
.into(); /// impl Example {
} /// pub fn with_a(mut self, value: impl Into<String>) -> Self {
/// self.a = Some(value.into());
// Sólo se exige `pub` en `impl` (en `trait` no aplica). /// self
let vis_pub = match (is_trait, vis) { /// }
(false, Some(v)) => quote! { #v }, ///
_ => quote! {}, /// pub fn with_b(mut self, value: u32) -> Self {
}; /// self.b = Some(value);
/// self
// Validaciones comunes. /// }
if sig.asyncness.is_some() { ///
return quote_spanned! { /// pub fn a(&self) -> Option<&str> {
sig.asyncness.span() => compile_error!("`with_...()` cannot be `async`"); /// self.a.as_deref()
} /// }
.into(); /// }
} ///
if sig.constness.is_some() { /// let example = Example::default().with_a("hello").with_b(42);
return quote_spanned! { /// ```
sig.constness.span() => compile_error!("`with_...()` cannot be `const`"); ///
} /// genera, para `with_a` y `with_b`, el mismo par `with_.../alter_...` que produciría anotar cada
.into(); /// uno individualmente con [`#[builder_fn]`](builder_fn); `a()` se reemite sin modificar.
} ///
if sig.abi.is_some() { /// Sobre una definición de `trait`, con receptor `self` (sin `mut`) en cada `with_...()`:
return quote_spanned! { ///
sig.abi.span() => compile_error!("`with_...()` cannot be `extern`"); /// ```rust,no_run
} /// # use pagetop_macros::builder_impl;
.into(); /// #[builder_impl]
} /// pub trait Example {
if sig.unsafety.is_some() { /// /// Sin cuerpo por defecto: sólo genera la declaración.
return quote_spanned! { /// fn with_a(self, value: impl Into<String>) -> Self;
sig.unsafety.span() => compile_error!("`with_...()` cannot be `unsafe`"); ///
} /// /// Con cuerpo por defecto: genera también la implementación, heredable sin redefinirla.
.into(); /// fn with_b(self, value: u32) -> Self {
} /// self
/// }
// En `impl` se exige exactamente `mut self`; y en `trait` se exige `self` (sin &). /// }
let receiver_ok = match sig.inputs.first() { /// ```
Some(FnArg::Receiver(r)) => { ///
// Rechaza `self: SomeType`. /// Un `with_...()` de trait con cuerpo por defecto añade `where Self: Sized` automáticamente. A
if r.colon_token.is_some() { /// diferencia de una declaración sin cuerpo, éste se compila junto a la propia definición del
false /// trait, donde `Self` podría no ser `Sized`, y Rust lo exige para poder devolverlo por valor.
} else if is_trait { #[proc_macro_attribute]
// Exactamente `self` (sin &, sin mut). pub fn builder_impl(_: TokenStream, item: TokenStream) -> TokenStream {
r.reference.is_none() && r.mutability.is_none() builder::expand_impl(item.into()).into()
} else {
// Exactamente `mut self`.
r.reference.is_none() && r.mutability.is_some()
}
}
_ => false,
};
if !receiver_ok {
let msg = if is_trait {
"expected `self` (not `mut self`, `&self` or `&mut self`) in trait method"
} else {
"expected first argument to be exactly `mut self`"
};
let err = sig
.inputs
.first()
.map(|a| a.span())
.unwrap_or(sig.ident.span());
return quote_spanned! {
err => compile_error!(#msg);
}
.into();
}
// Valida que el método devuelve exactamente `Self`.
match &sig.output {
ReturnType::Type(_, ty) => match ty.as_ref() {
Type::Path(p) if p.qself.is_none() && p.path.is_ident("Self") => {}
_ => {
return quote_spanned! {
ty.span() => compile_error!("expected return type to be exactly `Self`");
}
.into();
}
},
_ => {
return quote_spanned! {
sig.output.span() => compile_error!("expected return type to be exactly `Self`");
}
.into();
}
}
// Genera el nombre del método `alter_...()`.
let stem = with_name_str.strip_prefix("with_").expect("validated");
let alter_ident = Ident::new(&format!("alter_{stem}"), with_name.span());
// Extrae genéricos y cláusulas `where`.
let generics = &sig.generics;
let where_clause = &sig.generics.where_clause;
// Extrae identificadores de los argumentos para la llamada (sin `mut` ni patrones complejos).
let args: Vec<_> = sig.inputs.iter().skip(1).collect();
let call_idents: Vec<Ident> = {
let mut v = Vec::new();
for arg in sig.inputs.iter().skip(1) {
match arg {
FnArg::Typed(pat) => {
if let Pat::Ident(pat_ident) = pat.pat.as_ref() {
v.push(pat_ident.ident.clone());
} else {
return quote_spanned! {
pat.pat.span() => compile_error!(
"each parameter must be a simple identifier, e.g. `value: T`"
);
}
.into();
}
}
_ => {
return quote_spanned! {
arg.span() => compile_error!("unexpected receiver in parameter list");
}
.into();
}
}
}
v
};
// Separa atributos de documentación y resto.
let mut doc_attrs = Vec::new();
let mut other_attrs = Vec::new();
let mut non_doc_or_inline_attrs = Vec::new();
for a in attrs.iter() {
let p = a.path();
if p.is_ident("doc") {
doc_attrs.push(a.clone());
} else {
other_attrs.push(a.clone());
if !p.is_ident("inline") {
non_doc_or_inline_attrs.push(a.clone());
}
}
}
// Firma resumida de la función `alter_...()` para mostrarla en la doc de `with_...()`.
let alter_sig_tokens = if args.is_empty() {
// Sin argumentos sólo se muestra `&mut self` (puede que no tenga mucho sentido).
quote! { #vis_pub fn #alter_ident #generics (&mut self) -> &mut Self #where_clause }
} else {
// Con argumentos se muestra `&mut self, ...`.
quote! { #vis_pub fn #alter_ident #generics (&mut self, ...) -> &mut Self #where_clause }
};
// Normaliza espacios raros tipo `& mut`.
let alter_sig_str = alter_sig_tokens.to_string().replace("& mut", "&mut");
// Nombre de la función `alter_...()` como alias de búsqueda.
let alter_name_str = alter_ident.to_string();
// Texto introductorio para la documentación adicional de `with_...()`.
let with_alter_title = format!(
"# {} el método `{}()` generado por [`#[builder_fn]`](pagetop_macros::builder_fn)",
if doc_attrs.is_empty() {
"Añade"
} else {
"También añade"
},
alter_name_str
);
let with_alter_doc = concat!(
"Permite modificar la instancia (`&mut self`) con los mismos argumentos ",
"pero sin consumirla."
);
// Atributos completos que se aplican siempre a `with_...()`.
let with_prefix = quote! {
#(#other_attrs)*
#(#doc_attrs)*
#[doc(alias = #alter_name_str)]
#[doc = ""]
#[doc = #with_alter_title]
#[doc = #with_alter_doc]
#[doc = "```text"]
#[doc = #alter_sig_str]
#[doc = "```"]
};
// Genera el código final.
let expanded = match body_opt {
None => {
quote! {
#with_prefix
fn #with_name #generics (self, #(#args),*) -> Self #where_clause;
#(#non_doc_or_inline_attrs)*
#[doc(hidden)]
fn #alter_ident #generics (&mut self, #(#args),*) -> &mut Self #where_clause;
}
}
Some(body) => {
// Si no se indicó ninguna forma de `inline`, fuerza `#[inline]` para `with_...()`.
let force_inline = if attrs.iter().any(|a| a.path().is_ident("inline")) {
quote! {}
} else {
quote! { #[inline] }
};
let with_fn = if is_trait {
quote! {
#with_prefix
#force_inline
#vis_pub fn #with_name #generics (self, #(#args),*) -> Self #where_clause {
let mut s = self;
s.#alter_ident(#(#call_idents),*);
s
}
}
} else {
quote! {
#with_prefix
#force_inline
#vis_pub fn #with_name #generics (mut self, #(#args),*) -> Self #where_clause {
self.#alter_ident(#(#call_idents),*);
self
}
}
};
quote! {
#with_fn
#(#non_doc_or_inline_attrs)*
#[doc(hidden)]
#vis_pub fn #alter_ident #generics (&mut self, #(#args),*) -> &mut Self #where_clause {
#body
}
}
}
};
expanded.into()
} }
/// Define una función `main` asíncrona como punto de entrada de PageTop. /// Define una función `main` asíncrona como punto de entrada de PageTop.

View file

@ -49,6 +49,7 @@ impl Component for Badge {
} }
} }
#[builder_impl]
impl Badge { impl Badge {
/// Crea un badge predeterminado (`Intent::default()`) con la etiqueta indicada. /// Crea un badge predeterminado (`Intent::default()`) con la etiqueta indicada.
pub fn labeled(label: Lc) -> Self { pub fn labeled(label: Lc) -> Self {
@ -115,28 +116,24 @@ impl Badge {
// **< Badge BUILDER >************************************************************************** // **< Badge BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece la etiqueta del badge. /// Establece la etiqueta del badge.
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece la intención semántica del badge. /// Establece la intención semántica del badge.
#[builder_fn]
pub fn with_intent(mut self, intent: Intent) -> Self { pub fn with_intent(mut self, intent: Intent) -> Self {
self.intent = intent; self.intent = intent;
self self

View file

@ -50,25 +50,23 @@ impl Component for Block {
} }
} }
#[builder_impl]
impl Block { impl Block {
// **< Block BUILDER >************************************************************************** // **< Block BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece el título del bloque. /// Establece el título del bloque.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
@ -76,7 +74,6 @@ impl Block {
/// Añade un nuevo componente al bloque o modifica la lista de componentes (`children`) con una /// Añade un nuevo componente al bloque o modifica la lista de componentes (`children`) con una
/// operación [`ChildOp`]. /// operación [`ChildOp`].
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -77,39 +77,35 @@ impl Component for Brand {
} }
} }
#[builder_impl]
impl Brand { impl Brand {
// **< Brand BUILDER >************************************************************************** // **< Brand BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Asigna o quita la imagen de marca. Si se pasa `None`, no se mostrará. /// Asigna o quita la imagen de marca. Si se pasa `None`, no se mostrará.
#[builder_fn]
pub fn with_image(mut self, image: impl Into<Option<Image>>) -> Self { pub fn with_image(mut self, image: impl Into<Option<Image>>) -> Self {
self.image.alter_component(image); self.image.alter_component(image);
self self
} }
/// Establece el título de la identidad de marca. /// Establece el título de la identidad de marca.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
} }
/// Define la ruta de destino. Si es `None`, la marca no será un enlace. /// Define la ruta de destino. Si es `None`, la marca no será un enlace.
#[builder_fn]
pub fn with_route(mut self, route: impl Into<Option<Route>>) -> Self { pub fn with_route(mut self, route: impl Into<Option<Route>>) -> Self {
self.route = route.into(); self.route = route.into();
self self

View file

@ -67,25 +67,23 @@ impl Component for Breadcrumb {
} }
} }
#[builder_impl]
impl Breadcrumb { impl Breadcrumb {
// **< Breadcrumb BUILDER >********************************************************************* // **< Breadcrumb BUILDER >*********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Añade un nuevo elemento al final del breadcrumb. /// Añade un nuevo elemento al final del breadcrumb.
#[builder_fn]
pub fn with_crumb(mut self, crumb: breadcrumb::Crumb) -> Self { pub fn with_crumb(mut self, crumb: breadcrumb::Crumb) -> Self {
self.crumbs.push(crumb); self.crumbs.push(crumb);
self self

View file

@ -31,6 +31,7 @@ pub struct Crumb {
is_current: bool, is_current: bool,
} }
#[builder_impl]
impl Crumb { impl Crumb {
/// Crea un elemento enlazado a la ruta indicada. /// Crea un elemento enlazado a la ruta indicada.
pub fn new(label: Lc, route: impl Into<Route>) -> Self { pub fn new(label: Lc, route: impl Into<Route>) -> Self {
@ -66,14 +67,12 @@ impl Crumb {
// **< Crumb BUILDER >************************************************************************** // **< Crumb BUILDER >**************************************************************************
/// Establece el identificador único del elemento. /// Establece el identificador único del elemento.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS o atributos HTML del elemento. /// Modifica identificador, clases CSS o atributos HTML del elemento.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self

View file

@ -131,6 +131,7 @@ impl Component for Button {
} }
} }
#[builder_impl]
impl Button { impl Button {
/// Crea un botón de **envío** (`type="submit"`). /// Crea un botón de **envío** (`type="submit"`).
/// ///
@ -186,35 +187,30 @@ impl Button {
// **< Button BUILDER >************************************************************************* // **< Button BUILDER >*************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece el comportamiento del botón al activarse. /// Establece el comportamiento del botón al activarse.
#[builder_fn]
pub fn with_kind(mut self, kind: button::Kind) -> Self { pub fn with_kind(mut self, kind: button::Kind) -> Self {
self.kind = kind; self.kind = kind;
self self
} }
/// Establece el tamaño visual del botón (usa [`button::Size::None`] para quitarlo). /// Establece el tamaño visual del botón (usa [`button::Size::None`] para quitarlo).
#[builder_fn]
pub fn with_size(mut self, size: button::Size) -> Self { pub fn with_size(mut self, size: button::Size) -> Self {
self.size = size; self.size = size;
self self
} }
/// Establece el estilo visual del botón (usa [`button::Style::None`] para quitarlo). /// Establece el estilo visual del botón (usa [`button::Style::None`] para quitarlo).
#[builder_fn]
pub fn with_style(mut self, style: button::Style) -> Self { pub fn with_style(mut self, style: button::Style) -> Self {
self.style = style; self.style = style;
self self
@ -224,7 +220,6 @@ impl Button {
/// ///
/// Cuando el formulario tiene varios botones de envío, el navegador incluye en el envío el par /// Cuando el formulario tiene varios botones de envío, el navegador incluye en el envío el par
/// `name=value` sólo del botón que activó el formulario. Permite identificar cuál fue pulsado. /// `name=value` sólo del botón que activó el formulario. Permite identificar cuál fue pulsado.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
@ -234,21 +229,18 @@ impl Button {
/// ///
/// Es el dato que el navegador transmite al servidor junto con el `name` cuando este botón /// Es el dato que el navegador transmite al servidor junto con el `name` cuando este botón
/// activa el envío. Útil para distinguir entre varios botones de envío en un mismo formulario. /// activa el envío. Útil para distinguir entre varios botones de envío en un mismo formulario.
#[builder_fn]
pub fn with_value(mut self, value: impl AsRef<str>) -> Self { pub fn with_value(mut self, value: impl AsRef<str>) -> Self {
self.value.alter_str(value); self.value.alter_str(value);
self self
} }
/// Establece la etiqueta visible del botón (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del botón (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto emergente del botón (usa [`Lc::none()`] para quitarlo). /// Establece el texto emergente del botón (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
@ -257,21 +249,18 @@ impl Button {
/// Establece la ruta de destino y convierte el botón en enlace de navegación (`<a href=...>`). /// Establece la ruta de destino y convierte el botón en enlace de navegación (`<a href=...>`).
/// Puedes usar un [`Route`] vacío (por defecto) para que vuelva a renderizarse como `<button>`. /// Puedes usar un [`Route`] vacío (por defecto) para que vuelva a renderizarse como `<button>`.
/// Ver [`Button::anchor()`] para el constructor equivalente. /// Ver [`Button::anchor()`] para el constructor equivalente.
#[builder_fn]
pub fn with_href(mut self, route: impl Into<Route>) -> Self { pub fn with_href(mut self, route: impl Into<Route>) -> Self {
self.href = route.into(); self.href = route.into();
self self
} }
/// Establece si el botón recibe el foco automáticamente al cargar la página. /// Establece si el botón recibe el foco automáticamente al cargar la página.
#[builder_fn]
pub fn with_autofocus(mut self, autofocus: bool) -> Self { pub fn with_autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus; self.autofocus = autofocus;
self self
} }
/// Establece si el botón está deshabilitado. /// Establece si el botón está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self

View file

@ -47,25 +47,23 @@ impl Component for ButtonSet {
} }
} }
#[builder_impl]
impl ButtonSet { impl ButtonSet {
// **< ButtonSet BUILDER >************************************************************************* // **< ButtonSet BUILDER >*************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Añade un botón al conjunto, o modifica su lista de botones con una operación [`TypedOp`]. /// Añade un botón al conjunto, o modifica su lista de botones con una operación [`TypedOp`].
#[builder_fn]
pub fn with_button(mut self, op: impl Into<TypedOp<Button>>) -> Self { pub fn with_button(mut self, op: impl Into<TypedOp<Button>>) -> Self {
self.buttons.alter_child(op.into()); self.buttons.alter_child(op.into());
self self

View file

@ -78,6 +78,7 @@ impl Component for Container {
} }
} }
#[builder_impl]
impl Container { impl Container {
/// Crea un contenedor de tipo `Main` (`<main>`). /// Crea un contenedor de tipo `Main` (`<main>`).
pub fn main() -> Self { pub fn main() -> Self {
@ -122,14 +123,12 @@ impl Container {
// **< Container BUILDER >********************************************************************** // **< Container BUILDER >**********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -137,7 +136,6 @@ impl Container {
/// Añade un nuevo componente al contenedor o modifica la lista de componentes (`children`) con /// Añade un nuevo componente al contenedor o modifica la lista de componentes (`children`) con
/// una operación [`ChildOp`]. /// una operación [`ChildOp`].
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -103,25 +103,23 @@ impl Component for Dialog {
} }
} }
#[builder_impl]
impl Dialog { impl Dialog {
// **< Dialog BUILDER >************************************************************************* // **< Dialog BUILDER >*************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece el título del diálogo. /// Establece el título del diálogo.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
@ -129,7 +127,6 @@ impl Dialog {
/// Añade un nuevo componente al cuerpo del diálogo o modifica la lista de componentes /// Añade un nuevo componente al cuerpo del diálogo o modifica la lista de componentes
/// (`children`) del cuerpo con una operación [`ChildOp`]. /// (`children`) del cuerpo con una operación [`ChildOp`].
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.body.alter_child(op.into()); self.body.alter_child(op.into());
self self
@ -141,7 +138,6 @@ impl Dialog {
/// El pie ya se maqueta en fila y alineado a la derecha por su propia clase CSS /// El pie ya se maqueta en fila y alineado a la derecha por su propia clase CSS
/// (`dialog-footer`); por lo que no requiere un [`ButtonSet`](super::ButtonSet) para alinear /// (`dialog-footer`); por lo que no requiere un [`ButtonSet`](super::ButtonSet) para alinear
/// los botones, aunque puede usarse si se desea. /// los botones, aunque puede usarse si se desea.
#[builder_fn]
pub fn with_footer(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_footer(mut self, op: impl Into<ChildOp>) -> Self {
self.footer.alter_child(op.into()); self.footer.alter_child(op.into());
self self

View file

@ -130,46 +130,41 @@ impl Component for Dropdown {
} }
} }
#[builder_impl]
impl Dropdown { impl Dropdown {
// **< Dropdown BUILDER >*********************************************************************** // **< Dropdown BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece el título del menú desplegable. /// Establece el título del menú desplegable.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
} }
/// Activa/desactiva el modo *split* (botón de acción más *toggle*). /// Activa/desactiva el modo *split* (botón de acción más *toggle*).
#[builder_fn]
pub fn with_button_split(mut self, split: bool) -> Self { pub fn with_button_split(mut self, split: bool) -> Self {
self.button_split = split; self.button_split = split;
self self
} }
/// Establece el tamaño visual del botón (usa [`button::Size::None`] para quitarlo). /// Establece el tamaño visual del botón (usa [`button::Size::None`] para quitarlo).
#[builder_fn]
pub fn with_button_size(mut self, size: button::Size) -> Self { pub fn with_button_size(mut self, size: button::Size) -> Self {
self.button_size = size; self.button_size = size;
self self
} }
/// Establece el estilo visual del botón (usa [`button::Style::None`] para quitarlo). /// Establece el estilo visual del botón (usa [`button::Style::None`] para quitarlo).
#[builder_fn]
pub fn with_button_style(mut self, style: button::Style) -> Self { pub fn with_button_style(mut self, style: button::Style) -> Self {
self.button_style = style; self.button_style = style;
self self
@ -191,7 +186,6 @@ impl Dropdown {
/// dropdown::Item::link(Lc::n("Home"), "/"), /// dropdown::Item::link(Lc::n("Home"), "/"),
/// ])); /// ]));
/// ``` /// ```
#[builder_fn]
pub fn with_item(mut self, op: impl Into<TypedOp<dropdown::Item>>) -> Self { pub fn with_item(mut self, op: impl Into<TypedOp<dropdown::Item>>) -> Self {
self.items.alter_child(op.into()); self.items.alter_child(op.into());
self self

View file

@ -151,6 +151,7 @@ impl Component for Item {
} }
} }
#[builder_impl]
impl Item { impl Item {
/// Crea un elemento de tipo texto, mostrado sin interacción. /// Crea un elemento de tipo texto, mostrado sin interacción.
pub fn label(label: Lc) -> Self { pub fn label(label: Lc) -> Self {
@ -257,14 +258,12 @@ impl Item {
// **< Item BUILDER >*************************************************************************** // **< Item BUILDER >***************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self

View file

@ -28,6 +28,7 @@ pub struct Item {
disabled: bool, disabled: bool,
} }
#[builder_impl]
impl Item { impl Item {
/// Crea una nueva casilla con el valor y la etiqueta indicados. /// Crea una nueva casilla con el valor y la etiqueta indicados.
pub fn new(value: impl AsRef<str>, label: Lc) -> Self { pub fn new(value: impl AsRef<str>, label: Lc) -> Self {
@ -42,14 +43,12 @@ impl Item {
// **< Item BUILDER >*************************************************************************** // **< Item BUILDER >***************************************************************************
/// Establece si la casilla debe aparecer marcada por defecto. /// Establece si la casilla debe aparecer marcada por defecto.
#[builder_fn]
pub fn with_checked(mut self, checked: bool) -> Self { pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = checked; self.checked = checked;
self self
} }
/// Establece si la casilla está deshabilitada. /// Establece si la casilla está deshabilitada.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -179,18 +178,17 @@ impl Component for Field {
} }
} }
#[builder_impl]
impl Field { impl Field {
// **< Field BUILDER >************************************************************************** // **< Field BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -201,28 +199,24 @@ impl Field {
/// Todas las casillas [`form::check::Item`](Item) del grupo llevarán este mismo `name`. Si se /// Todas las casillas [`form::check::Item`](Item) del grupo llevarán este mismo `name`. Si se
/// omite, se asigna un nombre generado automáticamente. Para deserializar los campos en el /// omite, se asigna un nombre generado automáticamente. Para deserializar los campos en el
/// servidor es recomendable establecer un `name` explícito. /// servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece la etiqueta visible del grupo (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del grupo (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto de ayuda del grupo (usa [`Lc::none()`] para quitarlo). /// Establece el texto de ayuda del grupo (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_help_text(mut self, help_text: Lc) -> Self { pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text; self.help_text = help_text;
self self
} }
/// Añade una casilla al grupo. Las casillas se muestran en el orden en que se añaden. /// Añade una casilla al grupo. Las casillas se muestran en el orden en que se añaden.
#[builder_fn]
pub fn with_item(mut self, item: Item) -> Self { pub fn with_item(mut self, item: Item) -> Self {
self.items.push(item); self.items.push(item);
self self
@ -231,7 +225,6 @@ impl Field {
/// Establece si todo el grupo está deshabilitado. /// Establece si todo el grupo está deshabilitado.
/// ///
/// Cuando está activo, se combina con el estado `disabled` de cada [`Item`]. /// Cuando está activo, se combina con el estado `disabled` de cada [`Item`].
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -240,7 +233,6 @@ impl Field {
/// Establece si las casillas se muestran en línea horizontalmente. /// Establece si las casillas se muestran en línea horizontalmente.
/// ///
/// Al activar este modo, se añade la clase `form-check-inline` al contenedor de cada casilla. /// Al activar este modo, se añade la clase `form-check-inline` al contenedor de cada casilla.
#[builder_fn]
pub fn with_inline(mut self, inline: bool) -> Self { pub fn with_inline(mut self, inline: bool) -> Self {
self.inline = inline; self.inline = inline;
self self

View file

@ -135,6 +135,7 @@ impl Component for Checkbox {
} }
} }
#[builder_impl]
impl Checkbox { impl Checkbox {
/// Crea una casilla de verificación estándar. /// Crea una casilla de verificación estándar.
pub fn check() -> Self { pub fn check() -> Self {
@ -152,21 +153,18 @@ impl Checkbox {
// **< Checkbox BUILDER >*********************************************************************** // **< Checkbox BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece la variante visual del control. /// Establece la variante visual del control.
#[builder_fn]
pub fn with_kind(mut self, kind: form::CheckboxKind) -> Self { pub fn with_kind(mut self, kind: form::CheckboxKind) -> Self {
self.checkbox_kind = kind; self.checkbox_kind = kind;
self self
@ -176,42 +174,36 @@ impl Checkbox {
/// ///
/// Si se omite, se asigna un identificador generado automáticamente. Para deserializar el campo /// Si se omite, se asigna un identificador generado automáticamente. Para deserializar el campo
/// en el servidor es recomendable establecer un `name` explícito. /// en el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece la etiqueta visible del control (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del control (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece si el control debe aparecer marcado/activo por defecto. /// Establece si el control debe aparecer marcado/activo por defecto.
#[builder_fn]
pub fn with_checked(mut self, checked: bool) -> Self { pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = checked; self.checked = checked;
self self
} }
/// Establece si el control recibe el foco automáticamente al cargar la página. /// Establece si el control recibe el foco automáticamente al cargar la página.
#[builder_fn]
pub fn with_autofocus(mut self, autofocus: bool) -> Self { pub fn with_autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus; self.autofocus = autofocus;
self self
} }
/// Establece si el campo es obligatorio. /// Establece si el campo es obligatorio.
#[builder_fn]
pub fn with_required(mut self, required: bool) -> Self { pub fn with_required(mut self, required: bool) -> Self {
self.required = required; self.required = required;
self self
} }
/// Establece si el control está deshabilitado. /// Establece si el control está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -221,7 +213,6 @@ impl Checkbox {
/// ///
/// Al activar este modo, se añade la clase `form-check-inline` al contenedor, lo que permite /// Al activar este modo, se añade la clase `form-check-inline` al contenedor, lo que permite
/// alinear varios controles horizontalmente. /// alinear varios controles horizontalmente.
#[builder_fn]
pub fn with_inline(mut self, inline: bool) -> Self { pub fn with_inline(mut self, inline: bool) -> Self {
self.inline = inline; self.inline = inline;
self self
@ -230,7 +221,6 @@ impl Checkbox {
/// Establece si el control y su etiqueta se justifican a la derecha del contenedor. /// Establece si el control y su etiqueta se justifican a la derecha del contenedor.
/// ///
/// Al activar este modo, se añade la clase `form-check-reverse` al contenedor. /// Al activar este modo, se añade la clase `form-check-reverse` al contenedor.
#[builder_fn]
pub fn with_reverse(mut self, reverse: bool) -> Self { pub fn with_reverse(mut self, reverse: bool) -> Self {
self.reverse = reverse; self.reverse = reverse;
self self

View file

@ -89,18 +89,17 @@ impl Component for Form {
} }
} }
#[builder_impl]
impl Form { impl Form {
// **< Form BUILDER >*************************************************************************** // **< Form BUILDER >***************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -110,7 +109,6 @@ impl Form {
/// ///
/// Acepta un literal, un `String`, o una [`Route`] explícita construida con [`Route::with()`] /// Acepta un literal, un `String`, o una [`Route`] explícita construida con [`Route::with()`]
/// para rutas que dependan del contexto de renderizado. /// para rutas que dependan del contexto de renderizado.
#[builder_fn]
pub fn with_action(mut self, action: impl Into<Route>) -> Self { pub fn with_action(mut self, action: impl Into<Route>) -> Self {
self.action = action.into(); self.action = action.into();
self self
@ -120,7 +118,6 @@ impl Form {
/// ///
/// - `GET`: el atributo `method` se omite. /// - `GET`: el atributo `method` se omite.
/// - `POST`: se establece `method="post"`. /// - `POST`: se establece `method="post"`.
#[builder_fn]
pub fn with_method(mut self, method: form::Method) -> Self { pub fn with_method(mut self, method: form::Method) -> Self {
self.method = method; self.method = method;
self self
@ -129,7 +126,6 @@ impl Form {
/// Establece el juego de caracteres aceptado por el formulario. /// Establece el juego de caracteres aceptado por el formulario.
/// ///
/// Por defecto se utiliza `"UTF-8"`. /// Por defecto se utiliza `"UTF-8"`.
#[builder_fn]
pub fn with_charset(mut self, charset: impl AsRef<str>) -> Self { pub fn with_charset(mut self, charset: impl AsRef<str>) -> Self {
self.charset.alter_str(charset); self.charset.alter_str(charset);
self self
@ -137,7 +133,6 @@ impl Form {
/// Añade un nuevo componente al formulario o modifica la lista de componentes (`children`) con /// Añade un nuevo componente al formulario o modifica la lista de componentes (`children`) con
/// una operación [`ChildOp`]. /// una operación [`ChildOp`].
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -67,39 +67,35 @@ impl Component for Fieldset {
} }
} }
#[builder_impl]
impl Fieldset { impl Fieldset {
// **< Fieldset BUILDER >*********************************************************************** // **< Fieldset BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece la leyenda del `fieldset` (usa [`Lc::none()`] para quitarla). /// Establece la leyenda del `fieldset` (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_legend(mut self, legend: Lc) -> Self { pub fn with_legend(mut self, legend: Lc) -> Self {
self.legend = legend; self.legend = legend;
self self
} }
/// Establece la descripción del `fieldset` (usa [`Lc::none()`] para quitarla). /// Establece la descripción del `fieldset` (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_description(mut self, description: Lc) -> Self { pub fn with_description(mut self, description: Lc) -> Self {
self.description = description; self.description = description;
self self
} }
/// Establece si el `fieldset` está deshabilitado. /// Establece si el `fieldset` está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -107,7 +103,6 @@ impl Fieldset {
/// Añade un nuevo componente al `fieldset`, o aplica una operación [`ChildOp`] sobre la lista /// Añade un nuevo componente al `fieldset`, o aplica una operación [`ChildOp`] sobre la lista
/// de componentes (`children`). /// de componentes (`children`).
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -54,6 +54,7 @@ impl Component for Hidden {
} }
} }
#[builder_impl]
impl Hidden { impl Hidden {
/// Crea un campo oculto con nombre y valor (atributos `name` y `value`) ya establecidos. /// Crea un campo oculto con nombre y valor (atributos `name` y `value`) ya establecidos.
/// ///
@ -68,14 +69,12 @@ impl Hidden {
/// ///
/// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para /// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para
/// deserializar el campo en el servidor es recomendable establecer un `name` explícito. /// deserializar el campo en el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece el valor del campo oculto (atributo `value`). /// Establece el valor del campo oculto (atributo `value`).
#[builder_fn]
pub fn with_value(mut self, value: impl AsRef<str>) -> Self { pub fn with_value(mut self, value: impl AsRef<str>) -> Self {
self.value.alter_str(value); self.value.alter_str(value);
self self

View file

@ -275,6 +275,7 @@ impl Component for Field {
} }
} }
#[builder_impl]
impl Field { impl Field {
/// Crea un campo de **texto genérico** (`type="text"`). /// Crea un campo de **texto genérico** (`type="text"`).
/// ///
@ -391,14 +392,12 @@ impl Field {
// **< Field BUILDER >************************************************************************** // **< Field BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -408,42 +407,36 @@ impl Field {
/// ///
/// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para /// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para
/// deserializar el campo en el servidor es recomendable establecer un `name` explícito. /// deserializar el campo en el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece el valor inicial del campo. /// Establece el valor inicial del campo.
#[builder_fn]
pub fn with_value(mut self, value: impl AsRef<str>) -> Self { pub fn with_value(mut self, value: impl AsRef<str>) -> Self {
self.value.alter_str(value); self.value.alter_str(value);
self self
} }
/// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo). /// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_help_text(mut self, help_text: Lc) -> Self { pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text; self.help_text = help_text;
self self
} }
/// Establece la longitud mínima permitida en caracteres (`None` para no imponer mínimo). /// Establece la longitud mínima permitida en caracteres (`None` para no imponer mínimo).
#[builder_fn]
pub fn with_minlength(mut self, minlength: impl Into<Option<u16>>) -> Self { pub fn with_minlength(mut self, minlength: impl Into<Option<u16>>) -> Self {
self.minlength = minlength.into(); self.minlength = minlength.into();
self self
} }
/// Establece la longitud máxima permitida en caracteres (`None` para no imponer límite). /// Establece la longitud máxima permitida en caracteres (`None` para no imponer límite).
#[builder_fn]
pub fn with_maxlength(mut self, maxlength: impl Into<Option<u16>>) -> Self { pub fn with_maxlength(mut self, maxlength: impl Into<Option<u16>>) -> Self {
self.maxlength = maxlength.into(); self.maxlength = maxlength.into();
self self
@ -453,7 +446,6 @@ impl Field {
/// ///
/// Este texto aparece en el mismo campo y desaparece en cuanto el usuario empieza a escribir. /// Este texto aparece en el mismo campo y desaparece en cuanto el usuario empieza a escribir.
/// Al ser texto visible para el usuario se acepta [`Lc`] para poder localizarlo. /// Al ser texto visible para el usuario se acepta [`Lc`] para poder localizarlo.
#[builder_fn]
pub fn with_placeholder(mut self, placeholder: Lc) -> Self { pub fn with_placeholder(mut self, placeholder: Lc) -> Self {
self.placeholder = placeholder; self.placeholder = placeholder;
self self
@ -464,7 +456,6 @@ impl Field {
/// Usar los métodos de [`form::Autocomplete`] para los valores más habituales (p. ej. /// Usar los métodos de [`form::Autocomplete`] para los valores más habituales (p. ej.
/// [`Autocomplete::email()`](form::Autocomplete::email) o /// [`Autocomplete::email()`](form::Autocomplete::email) o
/// [`Autocomplete::current_password()`](form::Autocomplete::current_password)). /// [`Autocomplete::current_password()`](form::Autocomplete::current_password)).
#[builder_fn]
pub fn with_autocomplete( pub fn with_autocomplete(
mut self, mut self,
autocomplete: impl Into<Option<form::Autocomplete>>, autocomplete: impl Into<Option<form::Autocomplete>>,
@ -474,28 +465,24 @@ impl Field {
} }
/// Establece si el campo recibe el foco automáticamente al cargar la página. /// Establece si el campo recibe el foco automáticamente al cargar la página.
#[builder_fn]
pub fn with_autofocus(mut self, autofocus: bool) -> Self { pub fn with_autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus; self.autofocus = autofocus;
self self
} }
/// Establece si el campo es de sólo lectura. /// Establece si el campo es de sólo lectura.
#[builder_fn]
pub fn with_readonly(mut self, readonly: bool) -> Self { pub fn with_readonly(mut self, readonly: bool) -> Self {
self.readonly = readonly; self.readonly = readonly;
self self
} }
/// Establece si el campo es obligatorio. /// Establece si el campo es obligatorio.
#[builder_fn]
pub fn with_required(mut self, required: bool) -> Self { pub fn with_required(mut self, required: bool) -> Self {
self.required = required; self.required = required;
self self
} }
/// Establece si el campo está deshabilitado. /// Establece si el campo está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -505,7 +492,6 @@ impl Field {
/// ///
/// Útil para mostrar un valor no editable en pantalla que sí se envía al servidor con el /// Útil para mostrar un valor no editable en pantalla que sí se envía al servidor con el
/// formulario. El efecto visual depende del tema activo. /// formulario. El efecto visual depende del tema activo.
#[builder_fn]
pub fn with_plaintext(mut self, plaintext: bool) -> Self { pub fn with_plaintext(mut self, plaintext: bool) -> Self {
self.plaintext = plaintext; self.plaintext = plaintext;
self self
@ -515,7 +501,6 @@ impl Field {
/// ///
/// A diferencia del atributo `type` ([`form::input::Kind`]), no restringe los valores aceptados /// A diferencia del atributo `type` ([`form::input::Kind`]), no restringe los valores aceptados
/// ni activa la validación del navegador; es sólo una sugerencia de presentación. /// ni activa la validación del navegador; es sólo una sugerencia de presentación.
#[builder_fn]
pub fn with_inputmode(mut self, inputmode: impl Into<Option<Mode>>) -> Self { pub fn with_inputmode(mut self, inputmode: impl Into<Option<Mode>>) -> Self {
self.inputmode = inputmode.into(); self.inputmode = inputmode.into();
self self

View file

@ -121,18 +121,17 @@ impl Component for Number {
} }
} }
#[builder_impl]
impl Number { impl Number {
// **< Number BUILDER >************************************************************************ // **< Number BUILDER >************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -142,42 +141,36 @@ impl Number {
/// ///
/// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para /// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para
/// deserializar el campo en el servidor es recomendable establecer un `name` explícito. /// deserializar el campo en el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece el valor inicial del campo. /// Establece el valor inicial del campo.
#[builder_fn]
pub fn with_value(mut self, value: impl Into<Option<u64>>) -> Self { pub fn with_value(mut self, value: impl Into<Option<u64>>) -> Self {
self.value = value.into(); self.value = value.into();
self self
} }
/// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo). /// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_help_text(mut self, help_text: Lc) -> Self { pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text; self.help_text = help_text;
self self
} }
/// Establece el valor mínimo permitido (`None` para no imponer mínimo). /// Establece el valor mínimo permitido (`None` para no imponer mínimo).
#[builder_fn]
pub fn with_min(mut self, min: impl Into<Option<u64>>) -> Self { pub fn with_min(mut self, min: impl Into<Option<u64>>) -> Self {
self.min = min.into(); self.min = min.into();
self self
} }
/// Establece el valor máximo permitido (`None` para no imponer máximo). /// Establece el valor máximo permitido (`None` para no imponer máximo).
#[builder_fn]
pub fn with_max(mut self, max: impl Into<Option<u64>>) -> Self { pub fn with_max(mut self, max: impl Into<Option<u64>>) -> Self {
self.max = max.into(); self.max = max.into();
self self
@ -187,35 +180,30 @@ impl Number {
/// ///
/// Pasar `None` omite el atributo `step` y deja que el navegador aplique su valor por defecto /// Pasar `None` omite el atributo `step` y deja que el navegador aplique su valor por defecto
/// (normalmente `1`). /// (normalmente `1`).
#[builder_fn]
pub fn with_step(mut self, step: impl Into<Option<u64>>) -> Self { pub fn with_step(mut self, step: impl Into<Option<u64>>) -> Self {
self.step = step.into(); self.step = step.into();
self self
} }
/// Establece si el campo recibe el foco automáticamente al cargar la página. /// Establece si el campo recibe el foco automáticamente al cargar la página.
#[builder_fn]
pub fn with_autofocus(mut self, autofocus: bool) -> Self { pub fn with_autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus; self.autofocus = autofocus;
self self
} }
/// Establece si el campo es de sólo lectura. /// Establece si el campo es de sólo lectura.
#[builder_fn]
pub fn with_readonly(mut self, readonly: bool) -> Self { pub fn with_readonly(mut self, readonly: bool) -> Self {
self.readonly = readonly; self.readonly = readonly;
self self
} }
/// Establece si el campo es obligatorio. /// Establece si el campo es obligatorio.
#[builder_fn]
pub fn with_required(mut self, required: bool) -> Self { pub fn with_required(mut self, required: bool) -> Self {
self.required = required; self.required = required;
self self
} }
/// Establece si el campo está deshabilitado. /// Establece si el campo está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self

View file

@ -29,6 +29,7 @@ pub struct Item {
disabled: bool, disabled: bool,
} }
#[builder_impl]
impl Item { impl Item {
/// Crea una nueva opción con el valor y la etiqueta indicados. /// Crea una nueva opción con el valor y la etiqueta indicados.
pub fn new(value: impl AsRef<str>, label: Lc) -> Self { pub fn new(value: impl AsRef<str>, label: Lc) -> Self {
@ -46,14 +47,12 @@ impl Item {
/// ///
/// Si varias opciones del grupo tienen `checked` activo, sólo la primera se renderizará como /// Si varias opciones del grupo tienen `checked` activo, sólo la primera se renderizará como
/// seleccionada; las demás se ignorarán. /// seleccionada; las demás se ignorarán.
#[builder_fn]
pub fn with_checked(mut self, checked: bool) -> Self { pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = checked; self.checked = checked;
self self
} }
/// Establece si la opción está inicialmente deshabilitada. /// Establece si la opción está inicialmente deshabilitada.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -196,18 +195,17 @@ impl Component for Field {
} }
} }
#[builder_impl]
impl Field { impl Field {
// **< Field BUILDER >************************************************************************** // **< Field BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -221,28 +219,24 @@ impl Field {
/// ///
/// Si se omite, se asigna un nombre generado automáticamente. Para deserializar los campos en /// Si se omite, se asigna un nombre generado automáticamente. Para deserializar los campos en
/// el servidor es recomendable establecer un `name` explícito. /// el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece la etiqueta visible del grupo (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del grupo (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto de ayuda del grupo (usa [`Lc::none()`] para quitarlo). /// Establece el texto de ayuda del grupo (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_help_text(mut self, help_text: Lc) -> Self { pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text; self.help_text = help_text;
self self
} }
/// Añade una opción al grupo. Las opciones se muestran en el orden en que se añaden. /// Añade una opción al grupo. Las opciones se muestran en el orden en que se añaden.
#[builder_fn]
pub fn with_item(mut self, item: Item) -> Self { pub fn with_item(mut self, item: Item) -> Self {
self.items.push(item); self.items.push(item);
self self
@ -252,7 +246,6 @@ impl Field {
/// ///
/// El atributo `required` se propaga a todos los botones del grupo para cumplir con la /// El atributo `required` se propaga a todos los botones del grupo para cumplir con la
/// especificación HTML. /// especificación HTML.
#[builder_fn]
pub fn with_required(mut self, required: bool) -> Self { pub fn with_required(mut self, required: bool) -> Self {
self.required = required; self.required = required;
self self
@ -261,7 +254,6 @@ impl Field {
/// Establece si todo el grupo está deshabilitado. /// Establece si todo el grupo está deshabilitado.
/// ///
/// Cuando está activo, se combina con el estado `disabled` de cada [`Item`]. /// Cuando está activo, se combina con el estado `disabled` de cada [`Item`].
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -270,7 +262,6 @@ impl Field {
/// Establece si los botones se muestran en línea horizontalmente. /// Establece si los botones se muestran en línea horizontalmente.
/// ///
/// Al activar este modo, se añade la clase `form-check-inline` al contenedor de cada opción. /// Al activar este modo, se añade la clase `form-check-inline` al contenedor de cada opción.
#[builder_fn]
pub fn with_inline(mut self, inline: bool) -> Self { pub fn with_inline(mut self, inline: bool) -> Self {
self.inline = inline; self.inline = inline;
self self

View file

@ -106,18 +106,17 @@ impl Component for Range {
} }
} }
#[builder_impl]
impl Range { impl Range {
// **< Range BUILDER >************************************************************************** // **< Range BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -127,7 +126,6 @@ impl Range {
/// ///
/// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para /// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para
/// deserializar el campo en el servidor es recomendable establecer un `name` explícito. /// deserializar el campo en el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
@ -137,21 +135,18 @@ impl Range {
/// ///
/// Pasar `None` omite el atributo `value` y deja que el navegador aplique su valor por defecto /// Pasar `None` omite el atributo `value` y deja que el navegador aplique su valor por defecto
/// (normalmente el punto medio del rango). /// (normalmente el punto medio del rango).
#[builder_fn]
pub fn with_value(mut self, value: impl Into<Option<f64>>) -> Self { pub fn with_value(mut self, value: impl Into<Option<f64>>) -> Self {
self.value = value.into(); self.value = value.into();
self self
} }
/// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo). /// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_help_text(mut self, help_text: Lc) -> Self { pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text; self.help_text = help_text;
self self
@ -160,7 +155,6 @@ impl Range {
/// Establece el valor mínimo del rango. /// Establece el valor mínimo del rango.
/// ///
/// Pasar `None` omite el atributo `min` y deja que el navegador aplique su valor por defecto. /// Pasar `None` omite el atributo `min` y deja que el navegador aplique su valor por defecto.
#[builder_fn]
pub fn with_min(mut self, min: impl Into<Option<f64>>) -> Self { pub fn with_min(mut self, min: impl Into<Option<f64>>) -> Self {
self.min = min.into(); self.min = min.into();
self self
@ -169,7 +163,6 @@ impl Range {
/// Establece el valor máximo del rango. /// Establece el valor máximo del rango.
/// ///
/// Pasar `None` omite el atributo `max` y deja que el navegador aplique su valor por defecto. /// Pasar `None` omite el atributo `max` y deja que el navegador aplique su valor por defecto.
#[builder_fn]
pub fn with_max(mut self, max: impl Into<Option<f64>>) -> Self { pub fn with_max(mut self, max: impl Into<Option<f64>>) -> Self {
self.max = max.into(); self.max = max.into();
self self
@ -179,21 +172,18 @@ impl Range {
/// ///
/// Pasar `None` omite el atributo `step` y deja que el navegador aplique su valor por defecto /// Pasar `None` omite el atributo `step` y deja que el navegador aplique su valor por defecto
/// (normalmente `1`). /// (normalmente `1`).
#[builder_fn]
pub fn with_step(mut self, step: impl Into<Option<f64>>) -> Self { pub fn with_step(mut self, step: impl Into<Option<f64>>) -> Self {
self.step = step.into(); self.step = step.into();
self self
} }
/// Establece si el control recibe el foco automáticamente al cargar la página. /// Establece si el control recibe el foco automáticamente al cargar la página.
#[builder_fn]
pub fn with_autofocus(mut self, autofocus: bool) -> Self { pub fn with_autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus; self.autofocus = autofocus;
self self
} }
/// Establece si el control está deshabilitado. /// Establece si el control está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self

View file

@ -32,6 +32,7 @@ pub struct Item {
disabled: bool, disabled: bool,
} }
#[builder_impl]
impl Item { impl Item {
/// Crea un nuevo elemento con el valor y la etiqueta indicados. /// Crea un nuevo elemento con el valor y la etiqueta indicados.
pub fn new(value: impl AsRef<str>, label: Lc) -> Self { pub fn new(value: impl AsRef<str>, label: Lc) -> Self {
@ -50,14 +51,12 @@ impl Item {
/// En una lista de selección única, el navegador aplica la selección al último elemento marcado /// En una lista de selección única, el navegador aplica la selección al último elemento marcado
/// si hay más de uno; mientras que en una lista múltiple se respetan todos los elementos /// si hay más de uno; mientras que en una lista múltiple se respetan todos los elementos
/// marcados. /// marcados.
#[builder_fn]
pub fn with_selected(mut self, selected: bool) -> Self { pub fn with_selected(mut self, selected: bool) -> Self {
self.selected = selected; self.selected = selected;
self self
} }
/// Establece si el elemento está deshabilitado. /// Establece si el elemento está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -90,6 +89,7 @@ pub struct Group {
disabled: bool, disabled: bool,
} }
#[builder_impl]
impl Group { impl Group {
/// Crea un nuevo grupo con la etiqueta indicada. /// Crea un nuevo grupo con la etiqueta indicada.
pub fn new(label: Lc) -> Self { pub fn new(label: Lc) -> Self {
@ -102,14 +102,12 @@ impl Group {
// **< Group BUILDER >************************************************************************** // **< Group BUILDER >**************************************************************************
/// Añade un elemento al grupo. Los elementos se muestran en el orden en que se añaden. /// Añade un elemento al grupo. Los elementos se muestran en el orden en que se añaden.
#[builder_fn]
pub fn with_item(mut self, item: Item) -> Self { pub fn with_item(mut self, item: Item) -> Self {
self.items.push(item); self.items.push(item);
self self
} }
/// Establece si el grupo de elementos está deshabilitado en bloque. /// Establece si el grupo de elementos está deshabilitado en bloque.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self
@ -307,18 +305,17 @@ impl Component for Field {
} }
} }
#[builder_impl]
impl Field { impl Field {
// **< Field BUILDER >************************************************************************** // **< Field BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -328,21 +325,18 @@ impl Field {
/// ///
/// Sin él, el valor seleccionado no se transmite al servidor al enviar el formulario. Para /// Sin él, el valor seleccionado no se transmite al servidor al enviar el formulario. Para
/// deserializar el campo en el servidor es recomendable establecer un `name` explícito. /// deserializar el campo en el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo). /// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_help_text(mut self, help_text: Lc) -> Self { pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text; self.help_text = help_text;
self self
@ -351,7 +345,6 @@ impl Field {
/// Añade un elemento individual a la lista de selección. /// Añade un elemento individual a la lista de selección.
/// ///
/// Los elementos y grupos se muestran en el orden en que se añaden. /// Los elementos y grupos se muestran en el orden en que se añaden.
#[builder_fn]
pub fn with_item(mut self, item: Item) -> Self { pub fn with_item(mut self, item: Item) -> Self {
self.entries.push(Entry::Item(item)); self.entries.push(Entry::Item(item));
self self
@ -360,7 +353,6 @@ impl Field {
/// Añade un grupo de elementos a la lista de selección. /// Añade un grupo de elementos a la lista de selección.
/// ///
/// Los elementos y grupos se muestran en el orden en que se añaden. /// Los elementos y grupos se muestran en el orden en que se añaden.
#[builder_fn]
pub fn with_group(mut self, group: Group) -> Self { pub fn with_group(mut self, group: Group) -> Self {
self.entries.push(Entry::Group(group)); self.entries.push(Entry::Group(group));
self self
@ -375,7 +367,6 @@ impl Field {
/// Para un número reducido de elementos con etiquetas descriptivas considera usar /// Para un número reducido de elementos con etiquetas descriptivas considera usar
/// [`form::check::Field`] en su lugar, ofrece una presentación más clara y es más accesible en /// [`form::check::Field`] en su lugar, ofrece una presentación más clara y es más accesible en
/// pantallas pequeñas. /// pantallas pequeñas.
#[builder_fn]
pub fn with_multiple(mut self, multiple: bool) -> Self { pub fn with_multiple(mut self, multiple: bool) -> Self {
self.multiple = multiple; self.multiple = multiple;
self self
@ -389,7 +380,6 @@ impl Field {
/// ///
/// Es especialmente útil con selección múltiple para controlar el número de filas visibles sin /// Es especialmente útil con selección múltiple para controlar el número de filas visibles sin
/// necesidad de recurrir al desplazamiento. /// necesidad de recurrir al desplazamiento.
#[builder_fn]
pub fn with_rows(mut self, rows: impl Into<Option<u16>>) -> Self { pub fn with_rows(mut self, rows: impl Into<Option<u16>>) -> Self {
self.rows = rows.into(); self.rows = rows.into();
self self
@ -404,7 +394,6 @@ impl Field {
/// ///
/// Usa los métodos de [`form::Autocomplete`] para los valores más habituales. Pasa `None` para /// Usa los métodos de [`form::Autocomplete`] para los valores más habituales. Pasa `None` para
/// omitir el atributo. /// omitir el atributo.
#[builder_fn]
pub fn with_autocomplete( pub fn with_autocomplete(
mut self, mut self,
autocomplete: impl Into<Option<form::Autocomplete>>, autocomplete: impl Into<Option<form::Autocomplete>>,
@ -414,21 +403,18 @@ impl Field {
} }
/// Establece si el campo recibe el foco automáticamente al cargar la página. /// Establece si el campo recibe el foco automáticamente al cargar la página.
#[builder_fn]
pub fn with_autofocus(mut self, autofocus: bool) -> Self { pub fn with_autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus; self.autofocus = autofocus;
self self
} }
/// Establece si el campo es obligatorio. /// Establece si el campo es obligatorio.
#[builder_fn]
pub fn with_required(mut self, required: bool) -> Self { pub fn with_required(mut self, required: bool) -> Self {
self.required = required; self.required = required;
self self
} }
/// Establece si el campo está deshabilitado. /// Establece si el campo está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self

View file

@ -135,18 +135,17 @@ impl Component for Textarea {
} }
} }
#[builder_impl]
impl Textarea { impl Textarea {
// **< Textarea BUILDER >*********************************************************************** // **< Textarea BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -156,28 +155,24 @@ impl Textarea {
/// ///
/// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para /// Sin él, el valor del campo no se transmite al servidor al enviar el formulario. Para
/// deserializar el campo en el servidor es recomendable establecer un `name` explícito. /// deserializar el campo en el servidor es recomendable establecer un `name` explícito.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name.alter_name(name); self.name.alter_name(name);
self self
} }
/// Establece el valor inicial del área de texto. /// Establece el valor inicial del área de texto.
#[builder_fn]
pub fn with_value(mut self, value: impl AsRef<str>) -> Self { pub fn with_value(mut self, value: impl AsRef<str>) -> Self {
self.value.alter_str(value); self.value.alter_str(value);
self self
} }
/// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla). /// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla).
#[builder_fn]
pub fn with_label(mut self, label: Lc) -> Self { pub fn with_label(mut self, label: Lc) -> Self {
self.label = label; self.label = label;
self self
} }
/// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo). /// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo).
#[builder_fn]
pub fn with_help_text(mut self, help_text: Lc) -> Self { pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text; self.help_text = help_text;
self self
@ -187,21 +182,18 @@ impl Textarea {
/// ///
/// Sin valor o pasando `None`, el área muestra su altura predeterminada, dos filas según el /// Sin valor o pasando `None`, el área muestra su altura predeterminada, dos filas según el
/// estándar. /// estándar.
#[builder_fn]
pub fn with_rows(mut self, rows: impl Into<Option<u16>>) -> Self { pub fn with_rows(mut self, rows: impl Into<Option<u16>>) -> Self {
self.rows = rows.into(); self.rows = rows.into();
self self
} }
/// Establece la longitud mínima permitida en caracteres. /// Establece la longitud mínima permitida en caracteres.
#[builder_fn]
pub fn with_minlength(mut self, minlength: impl Into<Option<u16>>) -> Self { pub fn with_minlength(mut self, minlength: impl Into<Option<u16>>) -> Self {
self.minlength = minlength.into(); self.minlength = minlength.into();
self self
} }
/// Establece la longitud máxima permitida en caracteres. /// Establece la longitud máxima permitida en caracteres.
#[builder_fn]
pub fn with_maxlength(mut self, maxlength: impl Into<Option<u16>>) -> Self { pub fn with_maxlength(mut self, maxlength: impl Into<Option<u16>>) -> Self {
self.maxlength = maxlength.into(); self.maxlength = maxlength.into();
self self
@ -211,7 +203,6 @@ impl Textarea {
/// ///
/// Este texto aparece en el área de texto y desaparece en cuanto el usuario empieza a escribir. /// Este texto aparece en el área de texto y desaparece en cuanto el usuario empieza a escribir.
/// Al ser texto visible para el usuario se acepta [`Lc`] para poder localizarlo. /// Al ser texto visible para el usuario se acepta [`Lc`] para poder localizarlo.
#[builder_fn]
pub fn with_placeholder(mut self, placeholder: Lc) -> Self { pub fn with_placeholder(mut self, placeholder: Lc) -> Self {
self.placeholder = placeholder; self.placeholder = placeholder;
self self
@ -224,7 +215,6 @@ impl Textarea {
/// ///
/// Usa los métodos de [`form::Autocomplete`] para los valores más habituales. Pasa `None` para /// Usa los métodos de [`form::Autocomplete`] para los valores más habituales. Pasa `None` para
/// omitir el atributo. /// omitir el atributo.
#[builder_fn]
pub fn with_autocomplete( pub fn with_autocomplete(
mut self, mut self,
autocomplete: impl Into<Option<form::Autocomplete>>, autocomplete: impl Into<Option<form::Autocomplete>>,
@ -234,28 +224,24 @@ impl Textarea {
} }
/// Establece si el campo recibe el foco automáticamente al cargar la página. /// Establece si el campo recibe el foco automáticamente al cargar la página.
#[builder_fn]
pub fn with_autofocus(mut self, autofocus: bool) -> Self { pub fn with_autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus; self.autofocus = autofocus;
self self
} }
/// Establece si el campo es de sólo lectura. /// Establece si el campo es de sólo lectura.
#[builder_fn]
pub fn with_readonly(mut self, readonly: bool) -> Self { pub fn with_readonly(mut self, readonly: bool) -> Self {
self.readonly = readonly; self.readonly = readonly;
self self
} }
/// Establece si el campo es obligatorio. /// Establece si el campo es obligatorio.
#[builder_fn]
pub fn with_required(mut self, required: bool) -> Self { pub fn with_required(mut self, required: bool) -> Self {
self.required = required; self.required = required;
self self
} }
/// Establece si el campo está deshabilitado. /// Establece si el campo está deshabilitado.
#[builder_fn]
pub fn with_disabled(mut self, disabled: bool) -> Self { pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
self self

View file

@ -60,6 +60,7 @@ impl Component for Html {
} }
} }
#[builder_impl]
impl Html { impl Html {
// **< Html BUILDER >*************************************************************************** // **< Html BUILDER >***************************************************************************
@ -79,7 +80,6 @@ impl Html {
/// Permite a otras extensiones modificar la función de renderizado que se ejecutará cuando /// Permite a otras extensiones modificar la función de renderizado que se ejecutará cuando
/// [`Self::prepare()`] invoque esta instancia. La nueva función también recibe una referencia /// [`Self::prepare()`] invoque esta instancia. La nueva función también recibe una referencia
/// mutable al [`Context`]. /// mutable al [`Context`].
#[builder_fn]
pub fn with_fn<F>(mut self, f: F) -> Self pub fn with_fn<F>(mut self, f: F) -> Self
where where
F: Fn(&mut Context) -> Markup + Send + Sync + 'static, F: Fn(&mut Context) -> Markup + Send + Sync + 'static,

View file

@ -96,6 +96,7 @@ impl Component for Image {
} }
} }
#[builder_impl]
impl Image { impl Image {
/// Crea rápidamente una imagen especificando su origen. /// Crea rápidamente una imagen especificando su origen.
pub fn with(source: image::Source) -> Self { pub fn with(source: image::Source) -> Self {
@ -105,28 +106,24 @@ impl Image {
// **< Image BUILDER >************************************************************************** // **< Image BUILDER >**************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Define las dimensiones de la imagen (auto, ancho/alto, ambos). /// Define las dimensiones de la imagen (auto, ancho/alto, ambos).
#[builder_fn]
pub fn with_size(mut self, size: image::Size) -> Self { pub fn with_size(mut self, size: image::Size) -> Self {
self.size = size; self.size = size;
self self
} }
/// Establece el origen de la imagen, influyendo en su disposición en el contenido. /// Establece el origen de la imagen, influyendo en su disposición en el contenido.
#[builder_fn]
pub fn with_source(mut self, source: image::Source) -> Self { pub fn with_source(mut self, source: image::Source) -> Self {
self.source = source; self.source = source;
self self
@ -136,7 +133,6 @@ impl Image {
/// ///
/// Se recomienda siempre aportar un texto alternativo salvo que la imagen sea puramente /// Se recomienda siempre aportar un texto alternativo salvo que la imagen sea puramente
/// decorativa. /// decorativa.
#[builder_fn]
pub fn with_alternative(mut self, alt: Lc) -> Self { pub fn with_alternative(mut self, alt: Lc) -> Self {
self.alternative = alt; self.alternative = alt;
self self

View file

@ -216,6 +216,7 @@ impl Component for Intro {
} }
} }
#[builder_impl]
impl Intro { impl Intro {
// **< Intro BUILDER >************************************************************************** // **< Intro BUILDER >**************************************************************************
@ -227,7 +228,6 @@ impl Intro {
/// # use pagetop::prelude::*; /// # use pagetop::prelude::*;
/// let intro = Intro::default().with_title(Lc::n("Intro title")); /// let intro = Intro::default().with_title(Lc::n("Intro title"));
/// ``` /// ```
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
@ -241,7 +241,6 @@ impl Intro {
/// # use pagetop::prelude::*; /// # use pagetop::prelude::*;
/// let intro = Intro::default().with_slogan(Lc::n("A short slogan")); /// let intro = Intro::default().with_slogan(Lc::n("A short slogan"));
/// ``` /// ```
#[builder_fn]
pub fn with_slogan(mut self, slogan: Lc) -> Self { pub fn with_slogan(mut self, slogan: Lc) -> Self {
self.slogan = slogan; self.slogan = slogan;
self self
@ -262,7 +261,6 @@ impl Intro {
/// // Descarta el botón de la intro. /// // Descarta el botón de la intro.
/// let intro_no_button = Intro::default().with_button(None); /// let intro_no_button = Intro::default().with_button(None);
/// ``` /// ```
#[builder_fn]
pub fn with_button(mut self, button: impl Into<Option<(Lc, Route)>>) -> Self { pub fn with_button(mut self, button: impl Into<Option<(Lc, Route)>>) -> Self {
self.button = button.into(); self.button = button.into();
self self
@ -280,7 +278,6 @@ impl Intro {
/// # use pagetop::prelude::*; /// # use pagetop::prelude::*;
/// let intro = Intro::default().with_opening(IntroOpening::Custom); /// let intro = Intro::default().with_opening(IntroOpening::Custom);
/// ``` /// ```
#[builder_fn]
pub fn with_opening(mut self, opening: IntroOpening) -> Self { pub fn with_opening(mut self, opening: IntroOpening) -> Self {
self.opening = opening; self.opening = opening;
self self
@ -290,7 +287,6 @@ impl Intro {
/// operación [`ChildOp`]. /// operación [`ChildOp`].
/// ///
/// Si se añade un bloque ([`Block`]) se aplicarán estilos específicos para destacarlo. /// Si se añade un bloque ([`Block`]) se aplicarán estilos específicos para destacarlo.
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -69,18 +69,17 @@ impl Component for Messages {
} }
} }
#[builder_impl]
impl Messages { impl Messages {
// **< Messages BUILDER >*********************************************************************** // **< Messages BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self

View file

@ -69,25 +69,23 @@ impl Component for Nav {
} }
} }
#[builder_impl]
impl Nav { impl Nav {
// **< Nav BUILDER >**************************************************************************** // **< Nav BUILDER >****************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Selecciona la distribución y orientación del menú. /// Selecciona la distribución y orientación del menú.
#[builder_fn]
pub fn with_layout(mut self, layout: nav::Layout) -> Self { pub fn with_layout(mut self, layout: nav::Layout) -> Self {
self.nav_layout = layout; self.nav_layout = layout;
self self
@ -105,7 +103,6 @@ impl Nav {
/// nav::Item::link_disabled(...), /// nav::Item::link_disabled(...),
/// ])); /// ]));
/// ``` /// ```
#[builder_fn]
pub fn with_item(mut self, op: impl Into<TypedOp<nav::Item>>) -> Self { pub fn with_item(mut self, op: impl Into<TypedOp<nav::Item>>) -> Self {
self.items.alter_child(op.into()); self.items.alter_child(op.into());
self self

View file

@ -176,6 +176,7 @@ impl Component for Item {
} }
} }
#[builder_impl]
impl Item { impl Item {
/// Crea un elemento de tipo texto, mostrado sin interacción. /// Crea un elemento de tipo texto, mostrado sin interacción.
pub fn label(label: Lc) -> Self { pub fn label(label: Lc) -> Self {
@ -268,14 +269,12 @@ impl Item {
// **< Item BUILDER >*************************************************************************** // **< Item BUILDER >***************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -283,7 +282,6 @@ impl Item {
/// Fuerza si un [`ItemKind::Link`] se marca activo, o `None` para volver a la detección /// Fuerza si un [`ItemKind::Link`] se marca activo, o `None` para volver a la detección
/// automática por coincidencia exacta de ruta. /// automática por coincidencia exacta de ruta.
#[builder_fn]
pub fn with_active(mut self, active: impl Into<Option<bool>>) -> Self { pub fn with_active(mut self, active: impl Into<Option<bool>>) -> Self {
self.active_override = active.into(); self.active_override = active.into();
self self

View file

@ -167,6 +167,7 @@ impl Component for Navbar {
} }
} }
#[builder_impl]
impl Navbar { impl Navbar {
/// Crea una barra de navegación **simple**, sin marca y sin botón. /// Crea una barra de navegación **simple**, sin marca y sin botón.
pub fn simple() -> Self { pub fn simple() -> Self {
@ -198,21 +199,18 @@ impl Navbar {
// **< Navbar BUILDER >************************************************************************* // **< Navbar BUILDER >*************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Define el tipo de disposición que tendrá la barra de navegación. /// Define el tipo de disposición que tendrá la barra de navegación.
#[builder_fn]
pub fn with_layout(mut self, layout: navbar::Layout) -> Self { pub fn with_layout(mut self, layout: navbar::Layout) -> Self {
self.layout = layout; self.layout = layout;
self self
@ -230,7 +228,6 @@ impl Navbar {
/// navbar::Item::text(...), /// navbar::Item::text(...),
/// ])); /// ]));
/// ``` /// ```
#[builder_fn]
pub fn with_item(mut self, op: impl Into<TypedOp<navbar::Item>>) -> Self { pub fn with_item(mut self, op: impl Into<TypedOp<navbar::Item>>) -> Self {
self.items.alter_child(op.into()); self.items.alter_child(op.into());
self self

View file

@ -335,25 +335,23 @@ impl Component for Pager {
} }
} }
#[builder_impl]
impl Pager { impl Pager {
// **< Pager BUILDER >************************************************************************* // **< Pager BUILDER >*************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS o atributos HTML del componente. /// Modifica identificador, clases CSS o atributos HTML del componente.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
} }
/// Establece la ruta base sobre la que se construye el enlace de cada página. /// Establece la ruta base sobre la que se construye el enlace de cada página.
#[builder_fn]
pub fn with_base_path(mut self, base_path: impl AsRef<str>) -> Self { pub fn with_base_path(mut self, base_path: impl AsRef<str>) -> Self {
self.base_path.alter_str(base_path); self.base_path.alter_str(base_path);
self self
@ -362,28 +360,24 @@ impl Pager {
/// Añade un parámetro de consulta que debe viajar en el enlace de cada página, además de /// Añade un parámetro de consulta que debe viajar en el enlace de cada página, además de
/// `page` (que `Pager` añade siempre al final). Llamar varias veces añade varios /// `page` (que `Pager` añade siempre al final). Llamar varias veces añade varios
/// parámetros, en el orden en que se declaren. /// parámetros, en el orden en que se declaren.
#[builder_fn]
pub fn with_extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self { pub fn with_extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.extra_query.push((key.into(), value.into())); self.extra_query.push((key.into(), value.into()));
self self
} }
/// Establece la página actual (siendo 1 la primera página). /// Establece la página actual (siendo 1 la primera página).
#[builder_fn]
pub fn with_current_page(mut self, current_page: u64) -> Self { pub fn with_current_page(mut self, current_page: u64) -> Self {
self.current_page = current_page; self.current_page = current_page;
self self
} }
/// Establece el número de elementos que se muestran por página. /// Establece el número de elementos que se muestran por página.
#[builder_fn]
pub fn with_items_per_page(mut self, items_per_page: u64) -> Self { pub fn with_items_per_page(mut self, items_per_page: u64) -> Self {
self.items_per_page = items_per_page; self.items_per_page = items_per_page;
self self
} }
/// Establece el número total de elementos del listado completo. /// Establece el número total de elementos del listado completo.
#[builder_fn]
pub fn with_total_items(mut self, total_items: u64) -> Self { pub fn with_total_items(mut self, total_items: u64) -> Self {
self.total_items = total_items; self.total_items = total_items;
self self
@ -394,7 +388,6 @@ impl Pager {
/// ///
/// El valor `0` desactiva el truncado y muestra siempre todas las páginas. Usar cuando el /// El valor `0` desactiva el truncado y muestra siempre todas las páginas. Usar cuando el
/// número total de páginas sea pequeño y no haya riesgo de desbordar la interfaz. /// número total de páginas sea pequeño y no haya riesgo de desbordar la interfaz.
#[builder_fn]
pub fn with_window(mut self, window: u64) -> Self { pub fn with_window(mut self, window: u64) -> Self {
self.window = window; self.window = window;
self self
@ -402,7 +395,6 @@ impl Pager {
/// Establece la alineación horizontal del paginador dentro de su contenedor. Por defecto es /// Establece la alineación horizontal del paginador dentro de su contenedor. Por defecto es
/// [`PagerAlign::Center`]. /// [`PagerAlign::Center`].
#[builder_fn]
pub fn with_align(mut self, align: PagerAlign) -> Self { pub fn with_align(mut self, align: PagerAlign) -> Self {
self.align = align; self.align = align;
self self
@ -415,7 +407,6 @@ impl Pager {
/// ///
/// [`with_prev_next()`]: Self::with_prev_next /// [`with_prev_next()`]: Self::with_prev_next
/// [`with_jump()`]: Self::with_jump /// [`with_jump()`]: Self::with_jump
#[builder_fn]
pub fn with_summary(mut self, summary: PagerVisibility) -> Self { pub fn with_summary(mut self, summary: PagerVisibility) -> Self {
self.summary = summary; self.summary = summary;
self self
@ -425,7 +416,6 @@ impl Pager {
/// `PagerVisibility::Auto`: sólo se muestran cuando el número total de páginas supera al /// `PagerVisibility::Auto`: sólo se muestran cuando el número total de páginas supera al
/// número de páginas que se muestra en el paginador (con el extremo correspondiente /// número de páginas que se muestra en el paginador (con el extremo correspondiente
/// desactivado en vez de oculto). /// desactivado en vez de oculto).
#[builder_fn]
pub fn with_prev_next(mut self, prev_next: PagerVisibility) -> Self { pub fn with_prev_next(mut self, prev_next: PagerVisibility) -> Self {
self.prev_next = prev_next; self.prev_next = prev_next;
self self
@ -434,7 +424,6 @@ impl Pager {
/// Establece la visibilidad del formulario para saltar directamente a una página. Por /// Establece la visibilidad del formulario para saltar directamente a una página. Por
/// defecto es `PagerVisibility::Auto`: sólo se muestra cuando el número total de páginas /// defecto es `PagerVisibility::Auto`: sólo se muestra cuando el número total de páginas
/// supera al número de páginas que se muestra en el paginador. /// supera al número de páginas que se muestra en el paginador.
#[builder_fn]
pub fn with_jump(mut self, jump: PagerVisibility) -> Self { pub fn with_jump(mut self, jump: PagerVisibility) -> Self {
self.jump = jump; self.jump = jump;
self self
@ -442,7 +431,6 @@ impl Pager {
/// Establece la etiqueta de accesibilidad (`aria-label`) del elemento `<nav>`. Por defecto es /// Establece la etiqueta de accesibilidad (`aria-label`) del elemento `<nav>`. Por defecto es
/// "Page navigation" (clave `pager_aria_label`), igual que hace el paginador de Bootstrap. /// "Page navigation" (clave `pager_aria_label`), igual que hace el paginador de Bootstrap.
#[builder_fn]
pub fn with_aria_label(mut self, aria_label: Lc) -> Self { pub fn with_aria_label(mut self, aria_label: Lc) -> Self {
self.aria_label = aria_label; self.aria_label = aria_label;
self self

View file

@ -47,6 +47,7 @@ impl Component for PoweredBy {
} }
} }
#[builder_impl]
impl PoweredBy { impl PoweredBy {
// **< PoweredBy BUILDER >********************************************************************** // **< PoweredBy BUILDER >**********************************************************************
@ -60,7 +61,6 @@ impl PoweredBy {
/// let p1 = PoweredBy::default().with_copyright(Some("2001 © Foo Inc.")); /// let p1 = PoweredBy::default().with_copyright(Some("2001 © Foo Inc."));
/// let p2 = PoweredBy::new().with_copyright(None::<String>); /// let p2 = PoweredBy::new().with_copyright(None::<String>);
/// ``` /// ```
#[builder_fn]
pub fn with_copyright(mut self, copyright: Option<impl Into<String>>) -> Self { pub fn with_copyright(mut self, copyright: Option<impl Into<String>>) -> Self {
self.copyright = copyright.map(Into::into); self.copyright = copyright.map(Into::into);
self self

View file

@ -24,6 +24,7 @@ pub struct Cell {
children: Children, children: Children,
} }
#[builder_impl]
impl Cell { impl Cell {
/// Crea una celda a partir del componente o texto ([`Lc`]) indicado. /// Crea una celda a partir del componente o texto ([`Lc`]) indicado.
/// ///
@ -44,14 +45,12 @@ impl Cell {
// **< Cell BUILDER >*************************************************************************** // **< Cell BUILDER >***************************************************************************
/// Establece el identificador único de la celda. /// Establece el identificador único de la celda.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS o atributos HTML de la celda. /// Modifica identificador, clases CSS o atributos HTML de la celda.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -60,7 +59,6 @@ impl Cell {
/// Establece el número de columnas que ocupa la celda (atributo `colspan`). /// Establece el número de columnas que ocupa la celda (atributo `colspan`).
/// ///
/// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo. /// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo.
#[builder_fn]
pub fn with_colspan(mut self, span: u8) -> Self { pub fn with_colspan(mut self, span: u8) -> Self {
self.props.alter_prop(if span == 1 { self.props.alter_prop(if span == 1 {
PropsOp::remove("colspan") PropsOp::remove("colspan")
@ -73,7 +71,6 @@ impl Cell {
/// Establece el número de filas que ocupa la celda (atributo `rowspan`). /// Establece el número de filas que ocupa la celda (atributo `rowspan`).
/// ///
/// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo. /// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo.
#[builder_fn]
pub fn with_rowspan(mut self, span: u8) -> Self { pub fn with_rowspan(mut self, span: u8) -> Self {
self.props.alter_prop(if span == 1 { self.props.alter_prop(if span == 1 {
PropsOp::remove("rowspan") PropsOp::remove("rowspan")
@ -85,7 +82,6 @@ impl Cell {
/// Añade un nuevo componente a la celda o modifica la lista de componentes (`children`) con una /// Añade un nuevo componente a la celda o modifica la lista de componentes (`children`) con una
/// operación [`ChildOp`]. /// operación [`ChildOp`].
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into()); self.children.alter_child(op.into());
self self

View file

@ -27,6 +27,7 @@ pub struct Column {
sort: Option<table::SortLink>, sort: Option<table::SortLink>,
} }
#[builder_impl]
impl Column { impl Column {
/// Crea una cabecera con el texto localizado indicado. /// Crea una cabecera con el texto localizado indicado.
pub fn new(label: Lc) -> Self { pub fn new(label: Lc) -> Self {
@ -39,14 +40,12 @@ impl Column {
// **< Column BUILDER >************************************************************************* // **< Column BUILDER >*************************************************************************
/// Establece el identificador único de la celda de cabecera. /// Establece el identificador único de la celda de cabecera.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS o atributos HTML de la columna. /// Modifica identificador, clases CSS o atributos HTML de la columna.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -55,7 +54,6 @@ impl Column {
/// Establece el número de columnas que ocupa la cabecera (atributo `colspan`). /// Establece el número de columnas que ocupa la cabecera (atributo `colspan`).
/// ///
/// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo. /// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo.
#[builder_fn]
pub fn with_colspan(mut self, span: u8) -> Self { pub fn with_colspan(mut self, span: u8) -> Self {
self.props.alter_prop(if span == 1 { self.props.alter_prop(if span == 1 {
PropsOp::remove("colspan") PropsOp::remove("colspan")
@ -68,7 +66,6 @@ impl Column {
/// Establece el número de filas que ocupa la cabecera (atributo `rowspan`). /// Establece el número de filas que ocupa la cabecera (atributo `rowspan`).
/// ///
/// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo. /// Con `1` (el valor por defecto de HTML) elimina el atributo en vez de fijarlo.
#[builder_fn]
pub fn with_rowspan(mut self, span: u8) -> Self { pub fn with_rowspan(mut self, span: u8) -> Self {
self.props.alter_prop(if span == 1 { self.props.alter_prop(if span == 1 {
PropsOp::remove("rowspan") PropsOp::remove("rowspan")
@ -80,7 +77,6 @@ impl Column {
/// Convierte la columna en ordenable con el enlace indicado, o la vuelve no ordenable con /// Convierte la columna en ordenable con el enlace indicado, o la vuelve no ordenable con
/// `None`. /// `None`.
#[builder_fn]
pub fn with_sort(mut self, sort: impl Into<Option<table::SortLink>>) -> Self { pub fn with_sort(mut self, sort: impl Into<Option<table::SortLink>>) -> Self {
self.sort = sort.into(); self.sort = sort.into();
self self

View file

@ -118,18 +118,17 @@ impl Component for Table {
} }
} }
#[builder_impl]
impl Table { impl Table {
// **< Table BUILDER >************************************************************************** // **< Table BUILDER >**************************************************************************
/// Establece el identificador único de la tabla. /// Establece el identificador único de la tabla.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS o atributos HTML de la tabla. /// Modifica identificador, clases CSS o atributos HTML de la tabla.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -141,14 +140,12 @@ impl Table {
/// `table::Column::new(...)` con el texto indicado), o un [`table::Column`] ya construido (por /// `table::Column::new(...)` con el texto indicado), o un [`table::Column`] ya construido (por
/// ejemplo para asignarle clases, atributos propios o un enlace de ordenación con /// ejemplo para asignarle clases, atributos propios o un enlace de ordenación con
/// `with_sort()`). /// `with_sort()`).
#[builder_fn]
pub fn with_column(mut self, column: impl Into<table::Column>) -> Self { pub fn with_column(mut self, column: impl Into<table::Column>) -> Self {
self.columns.push(column.into()); self.columns.push(column.into());
self self
} }
/// Añade una fila de datos al final de la tabla. /// Añade una fila de datos al final de la tabla.
#[builder_fn]
pub fn with_row(mut self, row: table::Row) -> Self { pub fn with_row(mut self, row: table::Row) -> Self {
self.rows.push(row); self.rows.push(row);
self self
@ -160,7 +157,6 @@ impl Table {
/// ///
/// Ese mismo resultado se obtiene también si la traducción no resuelve a ningún texto (por /// Ese mismo resultado se obtiene también si la traducción no resuelve a ningún texto (por
/// ejemplo, con `Lc::n("")`). /// ejemplo, con `Lc::n("")`).
#[builder_fn]
pub fn with_empty(mut self, empty: impl Into<Option<Lc>>) -> Self { pub fn with_empty(mut self, empty: impl Into<Option<Lc>>) -> Self {
self.empty = empty.into(); self.empty = empty.into();
self self

View file

@ -39,6 +39,7 @@ pub struct SortLink {
dir: Option<SortDir>, dir: Option<SortDir>,
} }
#[builder_impl]
impl SortLink { impl SortLink {
/// Crea un enlace de ordenación hacia la URL indicada, sin dirección activa. /// Crea un enlace de ordenación hacia la URL indicada, sin dirección activa.
pub fn new(href: impl Into<RoutePath>) -> Self { pub fn new(href: impl Into<RoutePath>) -> Self {
@ -51,7 +52,6 @@ impl SortLink {
// **< SortLink BUILDER >*********************************************************************** // **< SortLink BUILDER >***********************************************************************
/// Establece el identificador único del enlace. /// Establece el identificador único del enlace.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
@ -59,7 +59,6 @@ impl SortLink {
/// Establece la dirección de orden vigente, o `None` si esta columna no es la que ordena /// Establece la dirección de orden vigente, o `None` si esta columna no es la que ordena
/// actualmente la tabla. /// actualmente la tabla.
#[builder_fn]
pub fn with_dir(mut self, dir: impl Into<Option<SortDir>>) -> Self { pub fn with_dir(mut self, dir: impl Into<Option<SortDir>>) -> Self {
self.dir = dir.into(); self.dir = dir.into();
self self
@ -67,7 +66,6 @@ impl SortLink {
/// Modifica los atributos HTML del enlace. Es el punto de extensión para añadir atributos de /// Modifica los atributos HTML del enlace. Es el punto de extensión para añadir atributos de
/// interactividad sin que `Table` necesite conocerlos. /// interactividad sin que `Table` necesite conocerlos.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self

View file

@ -19,6 +19,7 @@ pub struct Row {
cells: Vec<table::Cell>, cells: Vec<table::Cell>,
} }
#[builder_impl]
impl Row { impl Row {
/// Crea una fila vacía. /// Crea una fila vacía.
pub fn new() -> Self { pub fn new() -> Self {
@ -28,14 +29,12 @@ impl Row {
// **< Row BUILDER >**************************************************************************** // **< Row BUILDER >****************************************************************************
/// Establece el identificador único de la fila. /// Establece el identificador único de la fila.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id); self.props.alter_id(id);
self self
} }
/// Modifica identificador, clases CSS o atributos HTML de la fila. /// Modifica identificador, clases CSS o atributos HTML de la fila.
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
self.props.alter_prop(op); self.props.alter_prop(op);
self self
@ -46,7 +45,6 @@ impl Row {
/// Acepta directamente un `&str`, un `String` o un [`Lc`] (equivalen a `table::Cell::new(...)` /// Acepta directamente un `&str`, un `String` o un [`Lc`] (equivalen a `table::Cell::new(...)`
/// con el contenido indicado), o un [`table::Cell`] ya construido (por ejemplo para asignarle /// con el contenido indicado), o un [`table::Cell`] ya construido (por ejemplo para asignarle
/// clases o atributos propios, o para contener otros componentes). /// clases o atributos propios, o para contener otros componentes).
#[builder_fn]
pub fn with_cell(mut self, cell: impl Into<table::Cell>) -> Self { pub fn with_cell(mut self, cell: impl Into<table::Cell>) -> Self {
self.cells.push(cell.into()); self.cells.push(cell.into());
self self

View file

@ -55,10 +55,9 @@ pub use route::Route;
/// Ok(html! { "Visible component" }) /// Ok(html! { "Visible component" })
/// } /// }
/// } /// }
/// /// #[builder_impl]
/// impl SampleComponent { /// impl SampleComponent {
/// /// Asigna una función que decidirá si el componente se renderiza o no. /// /// Asigna una función que decidirá si el componente se renderiza o no.
/// #[builder_fn]
/// pub fn with_renderable(mut self, f: Option<FnIsRenderable>) -> Self { /// pub fn with_renderable(mut self, f: Option<FnIsRenderable>) -> Self {
/// self.renderable = f; /// self.renderable = f;
/// self /// self

View file

@ -1,6 +1,6 @@
use crate::core::component::{Component, Context}; use crate::core::component::{Component, Context};
use crate::html::{Markup, html}; use crate::html::{Markup, html};
use crate::{AutoDefault, UniqueId, builder_fn}; use crate::{AutoDefault, UniqueId, builder_impl};
use std::fmt; use std::fmt;
use std::sync::Arc; use std::sync::Arc;
@ -26,6 +26,7 @@ impl fmt::Debug for Child {
} }
} }
#[builder_impl]
impl Child { impl Child {
/// Crea un nuevo `Child` a partir de un componente. /// Crea un nuevo `Child` a partir de un componente.
pub fn with(component: impl Component) -> Self { pub fn with(component: impl Component) -> Self {
@ -44,7 +45,6 @@ impl Child {
/// Establece un componente nuevo, o lo vacía. /// Establece un componente nuevo, o lo vacía.
/// ///
/// Si se proporciona `Some(component)`, se encapsula como [`Child`]; y si es `None`, se limpia. /// Si se proporciona `Some(component)`, se encapsula como [`Child`]; y si es `None`, se limpia.
#[builder_fn]
pub fn with_component<C: Component>(mut self, component: impl Into<Option<C>>) -> Self { pub fn with_component<C: Component>(mut self, component: impl Into<Option<C>>) -> Self {
self.0 = component.into().map(|c| Arc::new(c) as Arc<dyn Component>); self.0 = component.into().map(|c| Arc::new(c) as Arc<dyn Component>);
self self
@ -154,6 +154,7 @@ impl<C: Component> fmt::Debug for Embed<C> {
} }
} }
#[builder_impl]
impl<C: Component> Embed<C> { impl<C: Component> Embed<C> {
/// Crea un nuevo `Embed` a partir de un componente. /// Crea un nuevo `Embed` a partir de un componente.
pub fn with(component: C) -> Self { pub fn with(component: C) -> Self {
@ -165,7 +166,6 @@ impl<C: Component> Embed<C> {
/// Establece un componente nuevo, o lo vacía. /// Establece un componente nuevo, o lo vacía.
/// ///
/// Si se proporciona `Some(component)`, se encapsula como [`Embed`]; y si es `None`, se limpia. /// Si se proporciona `Some(component)`, se encapsula como [`Embed`]; y si es `None`, se limpia.
#[builder_fn]
pub fn with_component(mut self, component: impl Into<Option<C>>) -> Self { pub fn with_component(mut self, component: impl Into<Option<C>>) -> Self {
self.0 = component.into().map(Arc::new); self.0 = component.into().map(Arc::new);
self self
@ -364,6 +364,7 @@ impl<C: Component> From<TypedOp<C>> for ChildOp {
#[derive(AutoDefault, Clone, Debug)] #[derive(AutoDefault, Clone, Debug)]
pub struct Children(Vec<Child>); pub struct Children(Vec<Child>);
#[builder_impl]
impl Children { impl Children {
/// Crea una lista vacía. /// Crea una lista vacía.
pub fn new() -> Self { pub fn new() -> Self {
@ -378,7 +379,6 @@ impl Children {
// **< Children BUILDER >*********************************************************************** // **< Children BUILDER >***********************************************************************
/// Añade un componente hijo o aplica una operación [`ChildOp`] sobre la lista. /// Añade un componente hijo o aplica una operación [`ChildOp`] sobre la lista.
#[builder_fn]
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self { pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
match op.into() { match op.into() {
ChildOp::Add(any) => self.add(any), ChildOp::Add(any) => self.add(any),

View file

@ -9,7 +9,7 @@ use crate::html::{Markup, Props, PropsOp, RoutePath, html};
use crate::locale::Lc; use crate::locale::Lc;
use crate::locale::{LangId, LanguageIdentifier, RequestLocale}; use crate::locale::{LangId, LanguageIdentifier, RequestLocale};
use crate::web::HttpRequest; use crate::web::HttpRequest;
use crate::{builder_fn, util}; use crate::{builder_impl, util};
use parking_lot::Mutex; use parking_lot::Mutex;
use thiserror::Error; use thiserror::Error;
@ -85,11 +85,11 @@ pub enum ContextError {
/// .with_param("user_id", 42_i32) /// .with_param("user_id", 42_i32)
/// } /// }
/// ``` /// ```
#[builder_impl]
pub trait Contextual: LangId { pub trait Contextual: LangId {
// **< Contextual BUILDER >********************************************************************* // **< Contextual BUILDER >*********************************************************************
/// Establece el idioma del documento. /// Establece el idioma del documento.
#[builder_fn]
fn with_langid(self, language: &impl LangId) -> Self; fn with_langid(self, language: &impl LangId) -> Self;
/// Almacena la petición HTTP de origen en el contexto. /// Almacena la petición HTTP de origen en el contexto.
@ -99,15 +99,12 @@ pub trait Contextual: LangId {
/// cualquier idioma forzado antes con [`with_langid()`](Self::with_langid) o el usuario ya /// cualquier idioma forzado antes con [`with_langid()`](Self::with_langid) o el usuario ya
/// resuelto. Si necesitas forzar el idioma o el usuario, llama a `with_request()` primero en /// resuelto. Si necesitas forzar el idioma o el usuario, llama a `with_request()` primero en
/// la cadena de construcción, nunca después. /// la cadena de construcción, nunca después.
#[builder_fn]
fn with_request(self, request: Option<HttpRequest>) -> Self; fn with_request(self, request: Option<HttpRequest>) -> Self;
/// Especifica la plantilla para renderizar el documento. /// Especifica la plantilla para renderizar el documento.
#[builder_fn]
fn with_template(self, template: TemplateRef) -> Self; fn with_template(self, template: TemplateRef) -> Self;
/// Especifica el tema para renderizar el documento. /// Especifica el tema para renderizar el documento.
#[builder_fn]
fn with_theme(self, theme: ThemeRef) -> Self; fn with_theme(self, theme: ThemeRef) -> Self;
/// Añade o modifica un parámetro dinámico del contexto. /// Añade o modifica un parámetro dinámico del contexto.
@ -125,25 +122,20 @@ pub trait Contextual: LangId {
/// .with_param("title", "Hello".to_string()) /// .with_param("title", "Hello".to_string())
/// .with_param("flags", vec!["a", "b"]); /// .with_param("flags", vec!["a", "b"]);
/// ``` /// ```
#[builder_fn]
fn with_param<T: Send + Sync + 'static>(self, key: &'static str, value: T) -> Self; fn with_param<T: Send + Sync + 'static>(self, key: &'static str, value: T) -> Self;
/// Define los recursos del contexto usando [`AssetsOp`]. /// Define los recursos del contexto usando [`AssetsOp`].
#[builder_fn]
fn with_assets(self, op: AssetsOp) -> Self; fn with_assets(self, op: AssetsOp) -> Self;
/// Modifica identificador, clases CSS, atributos HTML o valores extra del elemento `<body>`. /// Modifica identificador, clases CSS, atributos HTML o valores extra del elemento `<body>`.
#[builder_fn]
fn with_body_props(self, op: PropsOp) -> Self; fn with_body_props(self, op: PropsOp) -> Self;
/// Añade un componente o aplica una operación [`ChildOp`] en la región por defecto del /// Añade un componente o aplica una operación [`ChildOp`] en la región por defecto del
/// documento. /// documento.
#[builder_fn]
fn with_child(self, op: impl Into<ChildOp>) -> Self; fn with_child(self, op: impl Into<ChildOp>) -> Self;
/// Añade un componente o aplica una operación [`ChildOp`] en una región específica del /// Añade un componente o aplica una operación [`ChildOp`] en una región específica del
/// documento. /// documento.
#[builder_fn]
fn with_child_in(self, region: RegionRef, op: impl Into<ChildOp>) -> Self; fn with_child_in(self, region: RegionRef, op: impl Into<ChildOp>) -> Self;
// **< Contextual GETTERS >********************************************************************* // **< Contextual GETTERS >*********************************************************************
@ -546,10 +538,10 @@ impl LangId for Context {
} }
} }
#[builder_impl]
impl Contextual for Context { impl Contextual for Context {
// **< Contextual BUILDER >********************************************************************* // **< Contextual BUILDER >*********************************************************************
#[builder_fn]
fn with_request(mut self, request: Option<HttpRequest>) -> Self { fn with_request(mut self, request: Option<HttpRequest>) -> Self {
self.request = request; self.request = request;
// Recalcula el *locale* y el usuario actual según la nueva petición y la política de // Recalcula el *locale* y el usuario actual según la nueva petición y la política de
@ -559,32 +551,27 @@ impl Contextual for Context {
self self
} }
#[builder_fn]
fn with_langid(mut self, language: &impl LangId) -> Self { fn with_langid(mut self, language: &impl LangId) -> Self {
self.locale.with_langid(language); self.locale.with_langid(language);
self self
} }
#[builder_fn]
fn with_template(mut self, template: TemplateRef) -> Self { fn with_template(mut self, template: TemplateRef) -> Self {
self.template = template; self.template = template;
self self
} }
#[builder_fn]
fn with_theme(mut self, theme: ThemeRef) -> Self { fn with_theme(mut self, theme: ThemeRef) -> Self {
self.theme = theme; self.theme = theme;
self self
} }
#[builder_fn]
fn with_param<T: Send + Sync + 'static>(mut self, key: &'static str, value: T) -> Self { fn with_param<T: Send + Sync + 'static>(mut self, key: &'static str, value: T) -> Self {
let type_name = TypeInfo::FullName.of::<T>(); let type_name = TypeInfo::FullName.of::<T>();
self.params.insert(key, (Box::new(value), type_name)); self.params.insert(key, (Box::new(value), type_name));
self self
} }
#[builder_fn]
fn with_assets(mut self, op: AssetsOp) -> Self { fn with_assets(mut self, op: AssetsOp) -> Self {
match op { match op {
// Favicon. // Favicon.
@ -621,20 +608,17 @@ impl Contextual for Context {
self self
} }
#[builder_fn]
fn with_body_props(mut self, op: PropsOp) -> Self { fn with_body_props(mut self, op: PropsOp) -> Self {
self.body_props.alter_prop(op); self.body_props.alter_prop(op);
self self
} }
#[builder_fn]
fn with_child(mut self, op: impl Into<ChildOp>) -> Self { fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.regions self.regions
.alter_child_in(&CoreRegions::Content, op.into()); .alter_child_in(&CoreRegions::Content, op.into());
self self
} }
#[builder_fn]
fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self { fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self {
self.regions.alter_child_in(region, op.into()); self.regions.alter_child_in(region, op.into());
self self

View file

@ -1,6 +1,6 @@
use crate::core::component::{Child, ChildOp, Children, Component}; use crate::core::component::{Child, ChildOp, Children, Component};
use crate::core::theme::{CoreRegions, RegionRef, ThemeRef}; use crate::core::theme::{CoreRegions, RegionRef, ThemeRef};
use crate::{AutoDefault, UniqueId, builder_fn}; use crate::{AutoDefault, UniqueId, builder_impl};
use parking_lot::RwLock; use parking_lot::RwLock;
@ -55,12 +55,12 @@ static COMMON_REGIONS: LazyLock<RwLock<RegionComponents>> =
#[derive(AutoDefault)] #[derive(AutoDefault)]
pub(crate) struct ChildrenInRegions(HashMap<&'static str, Children>); pub(crate) struct ChildrenInRegions(HashMap<&'static str, Children>);
#[builder_impl]
impl ChildrenInRegions { impl ChildrenInRegions {
pub fn with(region: RegionRef, child: Child) -> Self { pub fn with(region: RegionRef, child: Child) -> Self {
Self::default().with_child_in(region, child) Self::default().with_child_in(region, child)
} }
#[builder_fn]
pub fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self { pub fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self {
let child = op.into(); let child = op.into();
let region_name = region.name(); let region_name = region.name();

View file

@ -1,4 +1,4 @@
use crate::{AutoDefault, builder_fn, util}; use crate::{AutoDefault, builder_impl, util};
// **< AttrName >*********************************************************************************** // **< AttrName >***********************************************************************************
@ -24,6 +24,7 @@ use crate::{AutoDefault, builder_fn, util};
#[derive(AutoDefault, Clone, Debug)] #[derive(AutoDefault, Clone, Debug)]
pub struct AttrName(Option<String>); pub struct AttrName(Option<String>);
#[builder_impl]
impl AttrName { impl AttrName {
/// Crea un nuevo `AttrName` normalizando el valor. /// Crea un nuevo `AttrName` normalizando el valor.
pub fn new(name: impl AsRef<str>) -> Self { pub fn new(name: impl AsRef<str>) -> Self {
@ -33,7 +34,6 @@ impl AttrName {
// **< AttrName BUILDER >*********************************************************************** // **< AttrName BUILDER >***********************************************************************
/// Establece un nombre nuevo normalizando el valor. /// Establece un nombre nuevo normalizando el valor.
#[builder_fn]
pub fn with_name(mut self, name: impl AsRef<str>) -> Self { pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.0 = util::normalize_token(name); self.0 = util::normalize_token(name);
self self
@ -79,6 +79,7 @@ impl AttrName {
#[derive(AutoDefault, Clone, Debug)] #[derive(AutoDefault, Clone, Debug)]
pub struct AttrValue(Option<String>); pub struct AttrValue(Option<String>);
#[builder_impl]
impl AttrValue { impl AttrValue {
/// Crea un nuevo `AttrValue` normalizando el valor. /// Crea un nuevo `AttrValue` normalizando el valor.
pub fn new(value: impl AsRef<str>) -> Self { pub fn new(value: impl AsRef<str>) -> Self {
@ -88,7 +89,6 @@ impl AttrValue {
// **< AttrValue BUILDER >********************************************************************** // **< AttrValue BUILDER >**********************************************************************
/// Establece una cadena nueva normalizando el valor. /// Establece una cadena nueva normalizando el valor.
#[builder_fn]
pub fn with_str(mut self, value: impl AsRef<str>) -> Self { pub fn with_str(mut self, value: impl AsRef<str>) -> Self {
self.0 = util::non_blank(value.as_ref()).map(str::to_string); self.0 = util::non_blank(value.as_ref()).map(str::to_string);
self self

View file

@ -1,6 +1,6 @@
use crate::core::TypeInfo; use crate::core::TypeInfo;
use crate::html::maud::{Escaper, RenderAttrs}; use crate::html::maud::{Escaper, RenderAttrs};
use crate::{AutoDefault, CowStr, builder_fn, trace, util}; use crate::{AutoDefault, CowStr, builder_impl, trace, util};
use thiserror::Error; use thiserror::Error;
@ -453,9 +453,9 @@ impl PropsOp {
/// } /// }
/// } /// }
/// ///
/// #[builder_impl]
/// impl MyButton { /// impl MyButton {
/// /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente. /// /// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
/// #[builder_fn]
/// pub fn with_prop(mut self, op: PropsOp) -> Self { /// pub fn with_prop(mut self, op: PropsOp) -> Self {
/// self.props.alter_prop(op); /// self.props.alter_prop(op);
/// self /// self
@ -471,6 +471,7 @@ pub struct Props {
extras: HashMap<&'static str, PropsExtra>, extras: HashMap<&'static str, PropsExtra>,
} }
#[builder_impl]
impl Props { impl Props {
/// Crea una colección con un primer atributo ya establecido. /// Crea una colección con un primer atributo ya establecido.
pub fn new(name: impl Into<CowStr>, value: impl Into<CowStr>) -> Self { pub fn new(name: impl Into<CowStr>, value: impl Into<CowStr>) -> Self {
@ -485,7 +486,6 @@ impl Props {
// **< Props BUILDER >************************************************************************** // **< Props BUILDER >**************************************************************************
/// Establece el identificador del componente; equivale a `with_prop(PropsOp::set_id(id))`. /// Establece el identificador del componente; equivale a `with_prop(PropsOp::set_id(id))`.
#[builder_fn]
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self { pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.apply_id(id.into().as_ref()); self.apply_id(id.into().as_ref());
self self
@ -494,7 +494,6 @@ impl Props {
/// Modifica el identificador, las clases, los atributos o los valores extra según la operación /// Modifica el identificador, las clases, los atributos o los valores extra según la operación
/// indicada. El método recomendado para construir cada operación es usar los constructores de /// indicada. El método recomendado para construir cada operación es usar los constructores de
/// [`PropsOp`]. /// [`PropsOp`].
#[builder_fn]
pub fn with_prop(mut self, op: PropsOp) -> Self { pub fn with_prop(mut self, op: PropsOp) -> Self {
match op { match op {
PropsOp::SetId(value) => { PropsOp::SetId(value) => {

View file

@ -1,4 +1,4 @@
use crate::{AutoDefault, CowStr, builder_fn}; use crate::{AutoDefault, CowStr, builder_impl};
use std::fmt::{self, Write as _}; use std::fmt::{self, Write as _};
@ -53,6 +53,7 @@ pub struct RoutePath {
query: indexmap::IndexMap<String, String>, query: indexmap::IndexMap<String, String>,
} }
#[builder_impl]
impl RoutePath { impl RoutePath {
/// Crea un `RoutePath` a partir de un *path* inicial. /// Crea un `RoutePath` a partir de un *path* inicial.
/// ///
@ -72,7 +73,6 @@ impl RoutePath {
/// ///
/// Un `value` vacío no se distingue de [`with_flag()`](Self::with_flag): ambos se renderizan /// Un `value` vacío no se distingue de [`with_flag()`](Self::with_flag): ambos se renderizan
/// como `?key`, sin `=`. /// como `?key`, sin `=`.
#[builder_fn]
pub fn with_param(mut self, key: impl Into<String>, value: impl AsRef<str>) -> Self { pub fn with_param(mut self, key: impl Into<String>, value: impl AsRef<str>) -> Self {
self.query self.query
.insert(key.into(), Self::encode_query_value(value.as_ref())); .insert(key.into(), Self::encode_query_value(value.as_ref()));
@ -80,7 +80,6 @@ impl RoutePath {
} }
/// Añade o sustituye un *flag* sin valor, por ejemplo `?debug`. /// Añade o sustituye un *flag* sin valor, por ejemplo `?debug`.
#[builder_fn]
pub fn with_flag(mut self, flag: impl Into<String>) -> Self { pub fn with_flag(mut self, flag: impl Into<String>) -> Self {
self.query.insert(flag.into(), String::new()); self.query.insert(flag.into(), String::new());
self self

View file

@ -140,7 +140,7 @@ pub const PAGETOP_VERSION: &str = env!("CARGO_PKG_VERSION");
/// [`impl Extension`](crate::core::extension::Extension). /// [`impl Extension`](crate::core::extension::Extension).
pub use async_trait::async_trait; pub use async_trait::async_trait;
pub use pagetop_macros::{AutoDefault, builder_fn, html, main, test}; pub use pagetop_macros::{AutoDefault, builder_fn, builder_impl, html, main, test};
pub use pagetop_statics::{StaticFile, resource}; pub use pagetop_statics::{StaticFile, resource};

View file

@ -4,7 +4,7 @@
pub use crate::PAGETOP_VERSION; pub use crate::PAGETOP_VERSION;
pub use crate::{async_trait, builder_fn, html, main, test}; pub use crate::{async_trait, builder_fn, builder_impl, html, main, test};
pub use crate::{AutoDefault, CowStr, Getters, StaticResources, UniqueId, Weight}; pub use crate::{AutoDefault, CowStr, Getters, StaticResources, UniqueId, Weight};

View file

@ -29,7 +29,7 @@ use crate::html::{DOCTYPE, Markup, html};
use crate::html::{Props, PropsOp}; use crate::html::{Props, PropsOp};
use crate::locale::{CharacterDirection, LangId, LanguageIdentifier, Lc}; use crate::locale::{CharacterDirection, LangId, LanguageIdentifier, Lc};
use crate::web::HttpRequest; use crate::web::HttpRequest;
use crate::{AutoDefault, builder_fn}; use crate::{AutoDefault, builder_impl};
// **< ReservedRegions >**************************************************************************** // **< ReservedRegions >****************************************************************************
@ -95,6 +95,7 @@ pub struct Page {
context : Context, context : Context,
} }
#[builder_impl]
impl Page { impl Page {
/// Crea una nueva instancia de página. /// Crea una nueva instancia de página.
/// ///
@ -126,28 +127,24 @@ impl Page {
// **< Page BUILDER >*************************************************************************** // **< Page BUILDER >***************************************************************************
/// Establece el título de la página como un valor traducible. /// Establece el título de la página como un valor traducible.
#[builder_fn]
pub fn with_title(mut self, title: Lc) -> Self { pub fn with_title(mut self, title: Lc) -> Self {
self.title = title; self.title = title;
self self
} }
/// Establece la descripción de la página como un valor traducible. /// Establece la descripción de la página como un valor traducible.
#[builder_fn]
pub fn with_description(mut self, description: Lc) -> Self { pub fn with_description(mut self, description: Lc) -> Self {
self.description = description; self.description = description;
self self
} }
/// Añade una entrada `<meta name="..." content="...">` al `<head>`. /// Añade una entrada `<meta name="..." content="...">` al `<head>`.
#[builder_fn]
pub fn with_metadata(mut self, name: &'static str, content: &'static str) -> Self { pub fn with_metadata(mut self, name: &'static str, content: &'static str) -> Self {
self.metadata.push((name, content)); self.metadata.push((name, content));
self self
} }
/// Añade una entrada `<meta property="..." content="...">` al `<head>`. /// Añade una entrada `<meta property="..." content="...">` al `<head>`.
#[builder_fn]
pub fn with_property(mut self, property: &'static str, content: &'static str) -> Self { pub fn with_property(mut self, property: &'static str, content: &'static str) -> Self {
self.properties.push((property, content)); self.properties.push((property, content));
self self
@ -267,59 +264,51 @@ impl LangId for Page {
} }
} }
#[builder_impl]
impl Contextual for Page { impl Contextual for Page {
// **< Contextual BUILDER >********************************************************************* // **< Contextual BUILDER >*********************************************************************
#[builder_fn]
fn with_request(mut self, request: Option<HttpRequest>) -> Self { fn with_request(mut self, request: Option<HttpRequest>) -> Self {
self.context.alter_request(request); self.context.alter_request(request);
self self
} }
#[builder_fn]
fn with_langid(mut self, language: &impl LangId) -> Self { fn with_langid(mut self, language: &impl LangId) -> Self {
self.context.alter_langid(language); self.context.alter_langid(language);
self self
} }
#[builder_fn]
fn with_template(mut self, template: TemplateRef) -> Self { fn with_template(mut self, template: TemplateRef) -> Self {
self.context.alter_template(template); self.context.alter_template(template);
self self
} }
#[builder_fn]
fn with_theme(mut self, theme: ThemeRef) -> Self { fn with_theme(mut self, theme: ThemeRef) -> Self {
self.context.alter_theme(theme); self.context.alter_theme(theme);
self self
} }
#[builder_fn]
fn with_param<T: Send + Sync + 'static>(mut self, key: &'static str, value: T) -> Self { fn with_param<T: Send + Sync + 'static>(mut self, key: &'static str, value: T) -> Self {
self.context.alter_param(key, value); self.context.alter_param(key, value);
self self
} }
#[builder_fn]
fn with_assets(mut self, op: AssetsOp) -> Self { fn with_assets(mut self, op: AssetsOp) -> Self {
self.context.alter_assets(op); self.context.alter_assets(op);
self self
} }
#[builder_fn]
fn with_body_props(mut self, op: PropsOp) -> Self { fn with_body_props(mut self, op: PropsOp) -> Self {
self.context.alter_body_props(op); self.context.alter_body_props(op);
self self
} }
#[builder_fn]
fn with_child(mut self, op: impl Into<ChildOp>) -> Self { fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.context self.context
.alter_child_in(&CoreRegions::Content, op.into()); .alter_child_in(&CoreRegions::Content, op.into());
self self
} }
#[builder_fn]
fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self { fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self {
self.context.alter_child_in(region, op.into()); self.context.alter_child_in(region, op.into());
self self