diff --git a/helpers/pagetop-macros/src/maud/generate.rs b/helpers/pagetop-macros/src/maud/generate.rs index 6e4649ba..d67da4fc 100644 --- a/helpers/pagetop-macros/src/maud/generate.rs +++ b/helpers/pagetop-macros/src/maud/generate.rs @@ -150,7 +150,7 @@ impl Generator { } fn attrs(&self, attrs: Vec, build: &mut Builder) { - let (classes, id, named_attrs, spliced) = split_attrs(attrs); + let (classes, id, mut named_attrs, spliced) = split_attrs(attrs); // Must run before `classes`/`id`/`named_attrs` are consumed below. let literal_attr_names: Vec = { @@ -170,21 +170,54 @@ impl Generator { if !classes.is_empty() { let mut toggle_class_exprs = vec![]; + // A `class="..."` (or `class=[...]`) next to shorthand classes (`.a`, `.a[cond]`) is + // merged with them into a single attribute, with its value first; otherwise the + // element would end up with two `class` attributes. + let class_value = named_attrs + .iter() + .position(|(name, attr_type)| { + name.to_string() == "class" && !matches!(attr_type, AttributeType::Empty(_)) + }) + .map(|i| named_attrs.remove(i).1); + let has_value = class_value.is_some(); + build.push_str(" "); self.name(parse_quote!(class), build); build.push_str("=\""); - for (i, (name, toggler)) in classes.into_iter().enumerate() { + match class_value { + Some(AttributeType::Normal { value, .. }) => self.markup(value, build), + Some(AttributeType::Optional { + toggler: Toggler { cond, .. }, + .. + }) => { + let inner_value: Expr = parse_quote!(inner_value); + let body = { + let mut build = self.builder(); + self.splice(inner_value.clone(), &mut build); + build.finish() + }; + build.push_tokens(quote!(if let Some(#inner_value) = (#cond) { #body })); + } + _ => {} + } + // Static classes are written before toggled ones, so the separator depends on the + // writing order, not on the position in the source: a toggled class gets a leading + // space if the `class` value, a static class or another toggled class precedes it. + let mut written = has_value; + for (name, toggler) in classes { if let Some(toggler) = toggler { - toggle_class_exprs.push((i > 0, name, toggler)); + toggle_class_exprs.push((name, toggler)); } else { - if i > 0 { + if written { build.push_str(" "); } self.name_or_markup(name, build); + written = true; } } - for (not_first, name, toggler) in toggle_class_exprs { + for (i, (name, toggler)) in toggle_class_exprs.into_iter().enumerate() { + let not_first = written || i > 0; let body = { let mut build = self.builder(); if not_first { diff --git a/src/base/component/pager.rs b/src/base/component/pager.rs index 976103d1..e210edf7 100644 --- a/src/base/component/pager.rs +++ b/src/base/component/pager.rs @@ -250,7 +250,7 @@ impl Component for Pager { } ul class="pagination" { @if show_prev_next { - li.page-item.page-previous.disabled[first_disabled] { + li class="page-item page-previous" .disabled[first_disabled] { a class="page-link" href=[(!first_disabled).then(|| Self::page_route(&route, page - 1))] aria-disabled=[first_disabled.then_some("true")] @@ -265,7 +265,7 @@ impl Component for Pager { @match item { PageItem::Number(n) => { @let href = Self::page_route(&route, n); - li.page-item.active[n == page] { + li class="page-item" .active[n == page] { a class="page-link" href=(href) aria-current=[(n == page).then_some("page")] { @@ -281,7 +281,7 @@ impl Component for Pager { } } @if show_prev_next { - li.page-item.page-next.disabled[last_disabled] { + li class="page-item page-next" .disabled[last_disabled] { a class="page-link" href=[(!last_disabled).then(|| Self::page_route(&route, page + 1))] aria-disabled=[last_disabled.then_some("true")] diff --git a/src/html/props/definition.rs b/src/html/props/definition.rs index 85806238..b8574f2f 100644 --- a/src/html/props/definition.rs +++ b/src/html/props/definition.rs @@ -124,6 +124,25 @@ use std::sync::Arc; /// assert_eq!(markup.into_string(), r#"OK"#); /// ``` /// +/// Con `class` ocurre lo mismo. Si el elemento escribe alguna clase propia, con `class="..."` o con +/// la forma abreviada (`.clase`, `.clase[cond]`), se omiten **todas** las clases de `Props`. Para +/// combinar las clases del componente con las que se aƱadan con `with_prop()`, el componente debe +/// incorporarlas a sus `Props` en su `setup()`, por ejemplo con [`PropsOp::prepend_classes()`], y +/// no las escribe en el elemento. +/// +/// ```rust +/// # use pagetop::prelude::*; +/// # let mut cx = Context::default(); +/// let props = Props::classes("extra"); +/// +/// let markup = html! { div class="card" (props.unpack(&mut cx)) {} }; +/// assert_eq!(markup.into_string(), r#"
"#); +/// +/// let props = props.with_prop(PropsOp::prepend_classes("card")); +/// let markup = html! { div (props.unpack(&mut cx)) {} }; +/// assert_eq!(markup.into_string(), r#"
"#); +/// ``` +/// /// # Valores extra /// /// Las variantes [`SetExtra`](PropsOp::SetExtra) y [`RemoveExtra`](PropsOp::RemoveExtra), usando diff --git a/tests/html_class.rs b/tests/html_class.rs new file mode 100644 index 00000000..89736b00 --- /dev/null +++ b/tests/html_class.rs @@ -0,0 +1,332 @@ +use pagetop::prelude::*; + +// Every way an element of `html!` gets its `class` attribute: literal `class="..."`, shorthand +// classes (`.a`, `.a[cond]`, `.(expr)`), both together, and the classes of a `Props` splice. + +// **< Literal class attribute >******************************************************************** + +#[pagetop::test] +async fn literal_class_attribute() { + assert_eq!( + html! { div class="a b" {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn literal_class_attribute_from_expression_is_escaped() { + let value = "a\"b"; + assert_eq!( + html! { div class=(value) {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn optional_class_attribute() { + let some = Some("a"); + let none: Option<&str> = None; + assert_eq!( + html! { div class=[some] {} }.into_string(), + r#"
"# + ); + assert_eq!(html! { div class=[none] {} }.into_string(), "
"); +} + +// **< Shorthand classes >************************************************************************** + +#[pagetop::test] +async fn shorthand_classes() { + assert_eq!( + html! { div.a.b {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_classes_without_element_name_are_a_div() { + assert_eq!( + html! { .a.b {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_toggled_classes() { + assert_eq!( + html! { div.a.b[true].c[false] {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_toggled_classes_go_after_the_fixed_ones() { + // Toggled classes are written after all the fixed ones, whatever their order in the source. + assert_eq!( + html! { div.a[true].b {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_only_toggled_classes() { + assert_eq!( + html! { div.a[true].b[true] {} }.into_string(), + r#"
"# + ); + // A leading space when the first toggled class is off: harmless, browsers ignore it. + assert_eq!( + html! { div.a[false].b[true] {} }.into_string(), + r#"
"# + ); + assert_eq!( + html! { div.a[false] {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_class_from_expression() { + let name = "dynamic"; + assert_eq!( + html! { div.a.(name) {} }.into_string(), + r#"
"# + ); + assert_eq!( + html! { div.a.(name)[false] {} }.into_string(), + r#"
"# + ); +} + +// **< Literal and shorthand classes together >***************************************************** + +#[pagetop::test] +async fn literal_and_shorthand_classes_merge_into_one_attribute() { + assert_eq!( + html! { div class="a" .b {} }.into_string(), + r#"
"# + ); + assert_eq!( + html! { div class="a b" .c.d {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn literal_class_goes_first_whatever_its_position() { + assert_eq!( + html! { div.b class="a" {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn literal_and_toggled_classes_merge() { + assert_eq!( + html! { li class="item" .active[true] {} }.into_string(), + r#"
  • "# + ); + assert_eq!( + html! { li class="item" .active[false] {} }.into_string(), + r#"
  • "# + ); + assert_eq!( + html! { li class="item" .active[true].disabled[false].first {} }.into_string(), + r#"
  • "# + ); +} + +#[pagetop::test] +async fn class_from_expression_and_shorthand_classes_merge() { + let base = "card"; + assert_eq!( + html! { div class=(base) .shadow {} }.into_string(), + r#"
    "# + ); + let escaped = "a\"b"; + assert_eq!( + html! { div class=(escaped) .c[true] {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn optional_class_and_shorthand_classes_merge() { + let some = Some("a"); + let none: Option<&str> = None; + assert_eq!( + html! { div class=[some] .b {} }.into_string(), + r#"
    "# + ); + // A leading space when the optional value is missing: harmless, browsers ignore it. + assert_eq!( + html! { div class=[none] .b {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn merged_class_keeps_the_order_of_the_other_attributes() { + // `class` is written first, then `id`, then the rest in source order, as always. + assert_eq!( + html! { a href="/" class="link" #home .active[true] title="Home" { "x" } }.into_string(), + r#"x"# + ); +} + +#[pagetop::test] +async fn merged_class_works_with_conditional_markup() { + let items = ["a", "b", "c"]; + let current = 1; + let markup = html! { + ul { + @for (i, item) in items.iter().enumerate() { + li class="item" .current[i == current] { (item) } + } + } + }; + assert_eq!( + markup.into_string(), + r#""# + ); +} + +// **< Classes from Props >************************************************************************* + +#[pagetop::test] +async fn props_classes() { + let props = Props::classes("from-props-a from-props-b"); + let mut cx = Context::default(); + assert_eq!( + html! { div (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn props_classes_with_other_literal_attributes_are_kept() { + // Only a literal `class` collides with the classes of `Props`. + let props = Props::classes("from-props"); + let mut cx = Context::default(); + assert_eq!( + html! { div #fixed style="color: red" (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn literal_class_attribute_prevails_over_props_classes() { + let props = Props::classes("from-props"); + let mut cx = Context::default(); + assert_eq!( + html! { div class="literal" (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn shorthand_classes_prevail_over_props_classes() { + let props = Props::classes("from-props"); + let mut cx = Context::default(); + assert_eq!( + html! { div.literal (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); + // Even if every shorthand class is toggled off. + assert_eq!( + html! { div.literal[false] (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn merged_literal_classes_prevail_over_props_classes() { + let props = Props::classes("from-props"); + let mut cx = Context::default(); + assert_eq!( + html! { div class="a" .b[true] (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn props_keep_their_id_when_only_the_class_collides() { + let props = Props::classes("from-props").with_id("from-props-id"); + let mut cx = Context::default(); + assert_eq!( + html! { div class="literal" (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn props_classes_after_class_operations() { + let props = Props::classes("b c") + .with_prop(PropsOp::prepend_classes("a")) + .with_prop(PropsOp::add_classes("d")) + .with_prop(PropsOp::remove_classes("c")) + .with_prop(PropsOp::replace_classes("b", "beta")); + let mut cx = Context::default(); + assert_eq!( + html! { div (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[pagetop::test] +async fn empty_props_write_no_class_attribute() { + let props = Props::default(); + let mut cx = Context::default(); + assert_eq!( + html! { div (props.unpack(&mut cx)) {} }.into_string(), + "
    " + ); +} + +// **< Classes of components >********************************************************************** + +#[pagetop::test] +async fn component_merges_its_own_classes_with_the_added_ones() { + // A component writes its own classes and the ones added with `with_prop()` in one attribute. + let mut container = Container::new() + .with_prop(PropsOp::add_classes("extra-a extra-b")) + .with_child(Lc::n("x")); + let markup = container + .render(&mut Context::default()) + .await + .into_string(); + let class = markup + .split("class=\"") + .nth(1) + .and_then(|rest| rest.split('"').next()) + .expect("the container has a class attribute"); + assert!(class.split(' ').any(|c| c == "extra-a"), "{markup}"); + assert!(class.split(' ').any(|c| c == "extra-b"), "{markup}"); + assert_eq!(markup.matches("class=").count(), 1, "{markup}"); +} + +#[pagetop::test] +async fn component_with_added_classes_never_duplicates_the_class_attribute() { + // Every component has some content: empty ones are not rendered. + let mut cx = Context::default(); + let components: Vec> = vec![ + Box::new( + Block::new() + .with_prop(PropsOp::add_classes("extra")) + .with_child(Lc::n("x")), + ), + Box::new(Badge::info(Lc::n("x")).with_prop(PropsOp::add_classes("extra"))), + Box::new(Button::plain(Lc::n("x")).with_prop(PropsOp::add_classes("extra"))), + Box::new( + Nav::new() + .with_prop(PropsOp::add_classes("extra")) + .with_item(nav::Item::link(Lc::n("x"), "/")), + ), + ]; + for mut component in components { + let markup = component.render(&mut cx).await.into_string(); + let first_tag = &markup[..markup.find('>').unwrap_or(markup.len())]; + assert!(first_tag.contains("extra"), "{markup}"); + assert_eq!(first_tag.matches("class=").count(), 1, "{markup}"); + } +}