From a693ddffa39609cbb3c81963f2cc1337cc758a37 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 9 Oct 2024 13:48:33 -0500 Subject: [PATCH] Fix partially formatted if chains in attributes (#2999) --- .../tests/conditional_formatted_attributes.rs | 13 +++++++++++++ packages/rsx/src/attribute.rs | 15 +++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 packages/core/tests/conditional_formatted_attributes.rs diff --git a/packages/core/tests/conditional_formatted_attributes.rs b/packages/core/tests/conditional_formatted_attributes.rs new file mode 100644 index 000000000..c96e8d33d --- /dev/null +++ b/packages/core/tests/conditional_formatted_attributes.rs @@ -0,0 +1,13 @@ +use dioxus::prelude::*; + +/// Make sure that rsx! handles conditional attributes with one formatted branch correctly +/// Regression test for https://github.com/DioxusLabs/dioxus/issues/2997 +#[test] +fn partially_formatted_conditional_attribute() { + let width = "1px"; + _ = rsx! { + div { + width: if true { "{width}" } else { "100px" } + } + }; +} diff --git a/packages/rsx/src/attribute.rs b/packages/rsx/src/attribute.rs index a1afe0ba0..f6430229a 100644 --- a/packages/rsx/src/attribute.rs +++ b/packages/rsx/src/attribute.rs @@ -615,6 +615,20 @@ impl IfAttributeValue { then_value, else_value, } = self; + + // Quote an attribute value and convert the value to a string if it is formatted + // We always quote formatted segments as strings inside if statements so they have a consistent type + // This fixes https://github.com/DioxusLabs/dioxus/issues/2997 + fn quote_attribute_value_string(value: &AttributeValue) -> TokenStream2 { + if matches!(value, AttributeValue::AttrLiteral(HotLiteral::Fmted(_))) { + quote! { #value.to_string() } + } else { + value.to_token_stream() + } + } + + let then_value = quote_attribute_value_string(then_value); + let then_value = if terminated { quote! { #then_value } } @@ -630,6 +644,7 @@ impl IfAttributeValue { tokens } Some(other) => { + let other = quote_attribute_value_string(other); if terminated { quote! { #other } } else {