Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting JsValue as properties #3458

Merged
merged 7 commits into from
Oct 28, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 35 additions & 14 deletions packages/yew-macro/src/html_tree/html_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,27 +247,35 @@ impl ToTokens for HtmlElement {
}
});

fn apply_as(directive: Option<&PropDirective>) -> TokenStream {
match directive {
Some(PropDirective::ApplyAsProperty(token)) => {
quote_spanned!(token.span()=> ::yew::virtual_dom::ApplyAttributeAs::Property)
}
None => quote!(::yew::virtual_dom::ApplyAttributeAs::Attribute),
}
}

/// Try to turn attribute list into a `::yew::virtual_dom::Attributes::Static`
fn try_into_static(
src: &[(LitStr, Value, Option<PropDirective>)],
) -> Option<TokenStream> {
if src
.iter()
.any(|(_, _, d)| matches!(d, Some(PropDirective::ApplyAsProperty(_))))
{
// don't try to make a static attribute list if there are any properties to
// assign
return None;
}
let mut kv = Vec::with_capacity(src.len());
for (k, v, directive) in src.iter() {
let v = match v {
Value::Static(v) => quote! { #v },
Value::Dynamic(_) => return None,
};
let apply_as = apply_as(directive.as_ref());
kv.push(quote! { ( #k, #v, #apply_as ) });
let v = match directive {
Some(PropDirective::ApplyAsProperty(token)) => {
quote_spanned!(token.span()=> ::yew::virtual_dom::AttributeOrProperty::Property(
::std::convert::Into::into(#v)
))
}
None => quote!(::yew::virtual_dom::AttributeOrProperty::Attribute(
::yew::virtual_dom::AttrValue::Static(#v)
)),
ranile marked this conversation as resolved.
Show resolved Hide resolved
};
kv.push(quote! { ( #k, #v) });
}

Some(quote! { ::yew::virtual_dom::Attributes::Static(&[#(#kv),*]) })
Expand All @@ -280,9 +288,22 @@ impl ToTokens for HtmlElement {
try_into_static(&attrs).unwrap_or_else(|| {
let keys = attrs.iter().map(|(k, ..)| quote! { #k });
let values = attrs.iter().map(|(_, v, directive)| {
let apply_as = apply_as(directive.as_ref());
let value = wrap_attr_value(v);
quote! { ::std::option::Option::map(#value, |it| (it, #apply_as)) }
let value = match directive {
Some(PropDirective::ApplyAsProperty(token)) => {
quote_spanned!(token.span()=> ::std::option::Option::Some(
::yew::virtual_dom::AttributeOrProperty::Property(
::std::convert::Into::into(#v)
))
)
}
None => {
let value = wrap_attr_value(v);
quote! {
::std::option::Option::map(#value, ::yew::virtual_dom::AttributeOrProperty::Attribute)
}
},
};
quote! { #value }
});
quote! {
::yew::virtual_dom::Attributes::Dynamic{
Expand Down
107 changes: 55 additions & 52 deletions packages/yew/src/dom_bundle/btag/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use yew::AttrValue;
use super::Apply;
use crate::dom_bundle::BSubtree;
use crate::virtual_dom::vtag::{InputFields, Value};
use crate::virtual_dom::{ApplyAttributeAs, Attributes};
use crate::virtual_dom::{AttributeOrProperty, Attributes};

impl<T: AccessValue> Apply for Value<T> {
type Bundle = Self;
Expand Down Expand Up @@ -92,23 +92,23 @@ impl Attributes {
#[cold]
fn apply_diff_index_maps(
el: &Element,
new: &IndexMap<AttrValue, (AttrValue, ApplyAttributeAs)>,
old: &IndexMap<AttrValue, (AttrValue, ApplyAttributeAs)>,
new: &IndexMap<AttrValue, AttributeOrProperty>,
old: &IndexMap<AttrValue, AttributeOrProperty>,
) {
for (key, value) in new.iter() {
match old.get(key) {
Some(old_value) => {
if value != old_value {
Self::set(el, key, value.0.as_ref(), value.1);
Self::set(el, key, value);
}
}
None => Self::set(el, key, value.0.as_ref(), value.1),
None => Self::set(el, key, value),
}
}

for (key, (_, apply_as)) in old.iter() {
for (key, value) in old.iter() {
if !new.contains_key(key) {
Self::remove(el, key, *apply_as);
Self::remove(el, key, value);
}
}
}
Expand All @@ -117,26 +117,17 @@ impl Attributes {
/// Works with any [Attributes] variants.
#[cold]
fn apply_diff_as_maps<'a>(el: &Element, new: &'a Self, old: &'a Self) {
fn collect(src: &Attributes) -> HashMap<&str, (&str, ApplyAttributeAs)> {
fn collect(src: &Attributes) -> HashMap<&str, &AttributeOrProperty> {
use Attributes::*;

match src {
Static(arr) => (*arr)
.iter()
.map(|(k, v, apply_as)| (*k, (*v, *apply_as)))
.collect(),
Static(arr) => (*arr).iter().map(|(k, v)| (*k, v)).collect(),
Dynamic { keys, values } => keys
.iter()
.zip(values.iter())
.filter_map(|(k, v)| {
v.as_ref()
.map(|(v, apply_as)| (*k, (v.as_ref(), *apply_as)))
})
.collect(),
IndexMap(m) => m
.iter()
.map(|(k, (v, apply_as))| (k.as_ref(), (v.as_ref(), *apply_as)))
.filter_map(|(k, v)| v.as_ref().map(|v| (*k, v)))
.collect(),
IndexMap(m) => m.iter().map(|(k, v)| (k.as_ref(), v)).collect(),
}
}

Expand All @@ -149,37 +140,36 @@ impl Attributes {
Some(old) => old != new,
None => true,
} {
Self::set(el, k, new.0, new.1);
Self::set(el, k, new);
}
}

// Remove missing
for (k, (_, apply_as)) in old.iter() {
for (k, old_value) in old.iter() {
if !new.contains_key(k) {
Self::remove(el, k, *apply_as);
Self::remove(el, k, old_value);
}
}
}

fn set(el: &Element, key: &str, value: &str, apply_as: ApplyAttributeAs) {
match apply_as {
ApplyAttributeAs::Attribute => el
fn set(el: &Element, key: &str, value: &AttributeOrProperty) {
match value {
AttributeOrProperty::Attribute(value) => el
.set_attribute(intern(key), value)
.expect("invalid attribute key"),
ApplyAttributeAs::Property => {
AttributeOrProperty::Property(value) => {
let key = JsValue::from_str(key);
let value = JsValue::from_str(value);
js_sys::Reflect::set(el.as_ref(), &key, &value).expect("could not set property");
js_sys::Reflect::set(el.as_ref(), &key, value).expect("could not set property");
}
}
}

fn remove(el: &Element, key: &str, apply_as: ApplyAttributeAs) {
match apply_as {
ApplyAttributeAs::Attribute => el
fn remove(el: &Element, key: &str, old_value: &AttributeOrProperty) {
match old_value {
AttributeOrProperty::Attribute(_) => el
.remove_attribute(intern(key))
.expect("could not remove attribute"),
ApplyAttributeAs::Property => {
AttributeOrProperty::Property(_) => {
let key = JsValue::from_str(key);
js_sys::Reflect::set(el.as_ref(), &key, &JsValue::UNDEFINED)
.expect("could not remove property");
Expand All @@ -195,20 +185,20 @@ impl Apply for Attributes {
fn apply(self, _root: &BSubtree, el: &Element) -> Self {
match &self {
Self::Static(arr) => {
for (k, v, apply_as) in arr.iter() {
Self::set(el, k, v, *apply_as);
for (k, v) in arr.iter() {
Self::set(el, k, v);
}
}
Self::Dynamic { keys, values } => {
for (k, v) in keys.iter().zip(values.iter()) {
if let Some((v, apply_as)) = v {
Self::set(el, k, v, *apply_as)
if let Some(v) = v {
Self::set(el, k, v)
}
}
}
Self::IndexMap(m) => {
for (k, (v, apply_as)) in m.iter() {
Self::set(el, k, v, *apply_as)
for (k, v) in m.iter() {
Self::set(el, k, v)
}
}
}
Expand Down Expand Up @@ -248,7 +238,7 @@ impl Apply for Attributes {
}
macro_rules! set {
($new:expr) => {
Self::set(el, key!(), $new.0.as_ref(), $new.1)
Self::set(el, key!(), $new)
};
}

Expand All @@ -260,7 +250,7 @@ impl Apply for Attributes {
}
(Some(new), None) => set!(new),
(None, Some(old)) => {
Self::remove(el, key!(), old.1);
Self::remove(el, key!(), old);
}
(None, None) => (),
}
Expand Down Expand Up @@ -303,10 +293,11 @@ mod tests {

#[test]
fn properties_are_set() {
let attrs = Attributes::Static(&[
("href", "https://example.com/", ApplyAttributeAs::Property),
("alt", "somewhere", ApplyAttributeAs::Property),
]);
let attrs = indexmap::indexmap! {
AttrValue::Static("href") => AttributeOrProperty::Property(JsValue::from_str("https://example.com/")),
AttrValue::Static("alt") => AttributeOrProperty::Property(JsValue::from_str("somewhere")),
};
let attrs = Attributes::IndexMap(attrs);
let (element, btree) = create_element();
attrs.apply(&btree, &element);
assert_eq!(
Expand All @@ -329,10 +320,11 @@ mod tests {

#[test]
fn respects_apply_as() {
let attrs = Attributes::Static(&[
("href", "https://example.com/", ApplyAttributeAs::Attribute),
("alt", "somewhere", ApplyAttributeAs::Property),
]);
let attrs = indexmap::indexmap! {
AttrValue::Static("href") => AttributeOrProperty::Attribute(AttrValue::from("https://example.com/")),
AttrValue::Static("alt") => AttributeOrProperty::Property(JsValue::from_str("somewhere")),
};
let attrs = Attributes::IndexMap(attrs);
let (element, btree) = create_element();
attrs.apply(&btree, &element);
assert_eq!(
Expand All @@ -352,7 +344,10 @@ mod tests {

#[test]
fn class_is_always_attrs() {
let attrs = Attributes::Static(&[("class", "thing", ApplyAttributeAs::Attribute)]);
let attrs = Attributes::Static(&[(
"class",
AttributeOrProperty::Attribute(AttrValue::Static("thing")),
)]);

let (element, btree) = create_element();
attrs.apply(&btree, &element);
Expand All @@ -363,10 +358,10 @@ mod tests {
async fn macro_syntax_works() {
#[function_component]
fn Comp() -> Html {
html! { <a href="https://example.com/" ~alt="abc" /> }
html! { <a href="https://example.com/" ~alt={"abc"} ~data-bool={JsValue::from_bool(true)} /> }
}

let output = gloo::utils::document().get_element_by_id("output").unwrap();
let output = document().get_element_by_id("output").unwrap();
yew::Renderer::<Comp>::with_root(output.clone()).render();

gloo::timers::future::sleep(Duration::from_secs(1)).await;
Expand All @@ -384,5 +379,13 @@ mod tests {
"abc",
"property `alt` not set properly"
);

assert!(
Reflect::get(element.as_ref(), &JsValue::from_str("data-bool"))
.expect("no alt")
.as_bool()
.expect("not a bool"),
"property `alt` not set properly"
);
}
}
Loading
Loading