Merge remote-tracking branch 'upstream/master' into pr/Demonthos/473

This commit is contained in:
Demonthos committed 2022-07-02 20:17:28 -05:00
commit c9b7b5b3b8
4 files changed
+163 -58

No files matched your search

@@ -1,11 +1,13 @@
use std::collections::HashSet;
use dioxus_core::{Listener, VNode}; use dioxus_core::{Listener, VNode};
use dioxus_rsx::{ use dioxus_rsx::{
BodyNode, CallBody, Component, ElementAttr, ElementAttrNamed, IfmtInput, Segment, BodyNode, CallBody, Component, ElementAttr, ElementAttrNamed, IfmtInput, Segment,
}; };
use quote::{quote, ToTokens, TokenStreamExt}; use quote::{quote, ToTokens, TokenStreamExt};
use syn::{Expr, Ident, Result}; use syn::{Expr, Ident, LitStr, Result};
use crate::CodeLocation; use crate::{attributes::attrbute_to_static_str, CodeLocation};
#[derive(Default)] #[derive(Default)]
pub struct CapturedContextBuilder { pub struct CapturedContextBuilder {
pub ifmted: Vec<IfmtInput>, pub ifmted: Vec<IfmtInput>,
@@ -14,6 +16,7 @@ pub struct CapturedContextBuilder {
pub captured_expressions: Vec<Expr>, pub captured_expressions: Vec<Expr>,
pub listeners: Vec<ElementAttrNamed>, pub listeners: Vec<ElementAttrNamed>,
pub custom_context: Option<Ident>, pub custom_context: Option<Ident>,
pub custom_attributes: HashSet<LitStr>,
} }
impl CapturedContextBuilder { impl CapturedContextBuilder {
@@ -23,6 +26,7 @@ impl CapturedContextBuilder {
self.iterators.extend(other.iterators); self.iterators.extend(other.iterators);
self.listeners.extend(other.listeners); self.listeners.extend(other.listeners);
self.captured_expressions.extend(other.captured_expressions); self.captured_expressions.extend(other.captured_expressions);
self.custom_attributes.extend(other.custom_attributes);
} }
pub fn from_call_body(body: CallBody) -> Result<Self> { pub fn from_call_body(body: CallBody) -> Result<Self> {
@@ -42,8 +46,13 @@ impl CapturedContextBuilder {
BodyNode::Element(el) => { BodyNode::Element(el) => {
for attr in el.attributes { for attr in el.attributes {
match attr.attr { match attr.attr {
ElementAttr::AttrText { value, .. } ElementAttr::AttrText { value, .. } => {
| ElementAttr::CustomAttrText { value, .. } => { let value_tokens = value.to_token_stream();
let formated: IfmtInput = syn::parse2(value_tokens)?;
captured.ifmted.push(formated);
}
ElementAttr::CustomAttrText { value, name } => {
captured.custom_attributes.insert(name);
let value_tokens = value.to_token_stream(); let value_tokens = value.to_token_stream();
let formated: IfmtInput = syn::parse2(value_tokens)?; let formated: IfmtInput = syn::parse2(value_tokens)?;
captured.ifmted.push(formated); captured.ifmted.push(formated);
@@ -51,7 +60,8 @@ impl CapturedContextBuilder {
ElementAttr::AttrExpression { name: _, value } => { ElementAttr::AttrExpression { name: _, value } => {
captured.captured_expressions.push(value); captured.captured_expressions.push(value);
} }
ElementAttr::CustomAttrExpression { name: _, value } => { ElementAttr::CustomAttrExpression { name, value } => {
captured.custom_attributes.insert(name);
captured.captured_expressions.push(value); captured.captured_expressions.push(value);
} }
ElementAttr::EventTokens { .. } => captured.listeners.push(attr), ElementAttr::EventTokens { .. } => captured.listeners.push(attr),
@@ -91,6 +101,7 @@ impl ToTokens for CapturedContextBuilder {
captured_expressions, captured_expressions,
listeners, listeners,
custom_context: _, custom_context: _,
custom_attributes,
} = self; } = self;
let listeners_str = listeners let listeners_str = listeners
.iter() .iter()
@@ -131,6 +142,7 @@ impl ToTokens for CapturedContextBuilder {
let captured_attr_expressions_text = captured_expressions let captured_attr_expressions_text = captured_expressions
.iter() .iter()
.map(|e| format!("{}", e.to_token_stream())); .map(|e| format!("{}", e.to_token_stream()));
let custom_attributes_iter = custom_attributes.iter();
tokens.append_all(quote! { tokens.append_all(quote! {
CapturedContext { CapturedContext {
captured: IfmtArgs{ captured: IfmtArgs{
@@ -140,6 +152,7 @@ impl ToTokens for CapturedContextBuilder {
iterators: vec![#((#iterators_str, #iterators)),*], iterators: vec![#((#iterators_str, #iterators)),*],
expressions: vec![#((#captured_attr_expressions_text, #captured_expressions.to_string())),*], expressions: vec![#((#captured_attr_expressions_text, #captured_expressions.to_string())),*],
listeners: vec![#((#listeners_str, #listeners)),*], listeners: vec![#((#listeners_str, #listeners)),*],
custom_attributes: &[#(#custom_attributes_iter),*],
location: code_location.clone() location: code_location.clone()
} }
}) })
@@ -159,10 +172,33 @@ pub struct CapturedContext<'a> {
pub expressions: Vec<(&'static str, String)>, pub expressions: Vec<(&'static str, String)>,
// map listener code to the resulting listener // map listener code to the resulting listener
pub listeners: Vec<(&'static str, Listener<'a>)>, pub listeners: Vec<(&'static str, Listener<'a>)>,
// used to map custom attrbutes form &'a str to &'static str
pub custom_attributes: &'static [&'static str],
// used to provide better error messages // used to provide better error messages
pub location: CodeLocation, pub location: CodeLocation,
} }
impl<'a> CapturedContext<'a> {
pub fn attrbute_to_static_str(
&self,
attr: &str,
tag: &'static str,
ns: Option<&'static str>,
literal: bool,
) -> Option<(&'static str, Option<&'static str>)> {
if let Some(attr) = attrbute_to_static_str(attr, tag, ns) {
Some(attr)
} else if literal {
self.custom_attributes
.iter()
.find(|attribute| attr == **attribute)
.map(|attribute| (*attribute, None))
} else {
None
}
}
}
pub struct IfmtArgs { pub struct IfmtArgs {
// All expressions that have been resolved // All expressions that have been resolved
pub named_args: Vec<FormattedArg>, pub named_args: Vec<FormattedArg>,
+1
View File
@@ -17,6 +17,7 @@ pub enum RecompileReason {
CapturedExpression(String), CapturedExpression(String),
CapturedComponent(String), CapturedComponent(String),
CapturedListener(String), CapturedListener(String),
CapturedAttribute(String),
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
+63 -49
View File
@@ -5,7 +5,6 @@ use quote::__private::Span;
use std::str::FromStr; use std::str::FromStr;
use syn::{parse2, parse_str, Expr}; use syn::{parse2, parse_str, Expr};
use crate::attributes::attrbute_to_static_str;
use crate::captuered_context::{CapturedContext, IfmtArgs}; use crate::captuered_context::{CapturedContext, IfmtArgs};
use crate::elements::element_to_static_str; use crate::elements::element_to_static_str;
use crate::error::{Error, ParseError, RecompileReason}; use crate::error::{Error, ParseError, RecompileReason};
@@ -76,37 +75,41 @@ fn build_node<'a>(
Ok(factory.text(format_args!("{}", text))) Ok(factory.text(format_args!("{}", text)))
} }
BodyNode::Element(el) => { BodyNode::Element(el) => {
let tag = bump.alloc(el.name.to_string()); let attributes: &mut Vec<Attribute> = bump.alloc(Vec::new());
let tag = &el.name.to_string();
if let Some((tag, ns)) = element_to_static_str(tag) { if let Some((tag, ns)) = element_to_static_str(tag) {
let attributes: &mut Vec<Attribute> = bump.alloc(Vec::new());
for attr in &el.attributes { for attr in &el.attributes {
match &attr.attr { match &attr.attr {
ElementAttr::AttrText { .. } | ElementAttr::CustomAttrText { .. } => { ElementAttr::AttrText { .. } | ElementAttr::CustomAttrText { .. } => {
let (name, value, span): (String, IfmtInput, Span) = match &attr.attr { let (name, value, span, literal): (String, IfmtInput, Span, bool) =
ElementAttr::AttrText { name, value } => ( match &attr.attr {
name.to_string(), ElementAttr::AttrText { name, value } => (
IfmtInput::from_str(&value.value()).map_err(|err| { name.to_string(),
Error::ParseError(ParseError::new( IfmtInput::from_str(&value.value()).map_err(|err| {
err, Error::ParseError(ParseError::new(
ctx.location.clone(), err,
)) ctx.location.clone(),
})?, ))
name.span(), })?,
), name.span(),
ElementAttr::CustomAttrText { name, value } => ( false,
name.value(), ),
IfmtInput::from_str(&value.value()).map_err(|err| { ElementAttr::CustomAttrText { name, value } => (
Error::ParseError(ParseError::new( name.value(),
err, IfmtInput::from_str(&value.value()).map_err(|err| {
ctx.location.clone(), Error::ParseError(ParseError::new(
)) err,
})?, ctx.location.clone(),
name.span(), ))
), })?,
_ => unreachable!(), name.span(),
}; true,
),
_ => unreachable!(),
};
if let Some((name, namespace)) = attrbute_to_static_str(&name, tag, ns) if let Some((name, namespace)) =
ctx.attrbute_to_static_str(&name, tag, ns, literal)
{ {
let value = bump.alloc(resolve_ifmt(&value, &ctx.captured)?); let value = bump.alloc(resolve_ifmt(&value, &ctx.captured)?);
attributes.push(Attribute { attributes.push(Attribute {
@@ -117,21 +120,31 @@ fn build_node<'a>(
namespace, namespace,
}); });
} else { } else {
return Err(Error::ParseError(ParseError::new( if literal {
syn::Error::new(span, format!("unknown attribute: {}", name)), // literals will be captured when a full recompile is triggered
ctx.location.clone(), return Err(Error::RecompileRequiredError(
))); RecompileReason::CapturedAttribute(name.to_string()),
));
} else {
return Err(Error::ParseError(ParseError::new(
syn::Error::new(
span,
format!("unknown attribute: {}", name),
),
ctx.location.clone(),
)));
}
} }
} }
ElementAttr::AttrExpression { .. } ElementAttr::AttrExpression { .. }
| ElementAttr::CustomAttrExpression { .. } => { | ElementAttr::CustomAttrExpression { .. } => {
let (name, value, span) = match &attr.attr { let (name, value, span, literal) = match &attr.attr {
ElementAttr::AttrExpression { name, value } => { ElementAttr::AttrExpression { name, value } => {
(name.to_string(), value, name.span()) (name.to_string(), value, name.span(), false)
} }
ElementAttr::CustomAttrExpression { name, value } => { ElementAttr::CustomAttrExpression { name, value } => {
(name.value(), value, name.span()) (name.value(), value, name.span(), true)
} }
_ => unreachable!(), _ => unreachable!(),
}; };
@@ -141,7 +154,7 @@ fn build_node<'a>(
.find(|(n, _)| parse_str::<Expr>(*n).unwrap() == *value) .find(|(n, _)| parse_str::<Expr>(*n).unwrap() == *value)
{ {
if let Some((name, namespace)) = if let Some((name, namespace)) =
attrbute_to_static_str(&name, tag, ns) ctx.attrbute_to_static_str(&name, tag, ns, literal)
{ {
let value = bump.alloc(resulting_value.clone()); let value = bump.alloc(resulting_value.clone());
attributes.push(Attribute { attributes.push(Attribute {
@@ -152,24 +165,25 @@ fn build_node<'a>(
namespace, namespace,
}); });
} else { } else {
return Err(Error::ParseError(ParseError::new( if literal {
syn::Error::new( // literals will be captured when a full recompile is triggered
span, return Err(Error::RecompileRequiredError(
format!("unknown attribute: {}", name), RecompileReason::CapturedAttribute(name.to_string()),
), ));
ctx.location.clone(), } else {
))); return Err(Error::ParseError(ParseError::new(
syn::Error::new(
span,
format!("unknown attribute: {}", name),
),
ctx.location.clone(),
)));
}
} }
} else {
return Err(Error::RecompileRequiredError(
RecompileReason::CapturedExpression(
value.into_token_stream().to_string(),
),
));
} }
} }
_ => (), _ => (),
}; }
} }
let children = bump.alloc(Vec::new()); let children = bump.alloc(Vec::new());
for child in el.children { for child in el.children {
+58 -4
View File
@@ -24,6 +24,7 @@ fn render_basic() {
expressions: Vec::new(), expressions: Vec::new(),
listeners: Vec::new(), listeners: Vec::new(),
location: location.clone(), location: location.clone(),
custom_attributes: &[],
}; };
let interperted_vnodes = LazyNodes::new(|factory| { let interperted_vnodes = LazyNodes::new(|factory| {
dioxus_rsx_interpreter::resolve_scope( dioxus_rsx_interpreter::resolve_scope(
@@ -70,6 +71,7 @@ fn render_nested() {
expressions: Vec::new(), expressions: Vec::new(),
listeners: Vec::new(), listeners: Vec::new(),
location: location.clone(), location: location.clone(),
custom_attributes: &[],
}; };
let interperted_vnodes = LazyNodes::new(|factory| { let interperted_vnodes = LazyNodes::new(|factory| {
dioxus_rsx_interpreter::resolve_scope( dioxus_rsx_interpreter::resolve_scope(
@@ -90,6 +92,54 @@ fn render_nested() {
assert!(check_eq(interperted_vnodes, static_vnodes)); assert!(check_eq(interperted_vnodes, static_vnodes));
} }
#[test]
#[allow(non_snake_case)]
fn render_custom_attribute() {
fn Base(cx: Scope) -> Element {
rsx!(cx, div {})
}
let dom = VirtualDom::new(Base);
let static_vnodes = rsx! {
div {
"data-test-1": 0,
"data-test-2": "1",
}
};
let location = CodeLocation {
file_path: String::new(),
crate_path: String::new(),
line: 2,
column: 0,
};
let empty_context = CapturedContext {
captured: IfmtArgs {
named_args: Vec::new(),
},
components: Vec::new(),
iterators: Vec::new(),
expressions: vec![("0", "0".to_string())],
listeners: Vec::new(),
location: location.clone(),
custom_attributes: &["data-test-1", "data-test-2"],
};
let interperted_vnodes = LazyNodes::new(|factory| {
dioxus_rsx_interpreter::resolve_scope(
location,
r#"div {
"data-test-1": 0,
"data-test-2": "1",
}"#,
empty_context,
factory,
)
});
let interperted_vnodes = dom.render_vnodes(interperted_vnodes);
let static_vnodes = dom.render_vnodes(static_vnodes);
assert!(check_eq(interperted_vnodes, static_vnodes));
}
#[test] #[test]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn render_component() { fn render_component() {
@@ -110,7 +160,7 @@ fn render_component() {
let location = CodeLocation { let location = CodeLocation {
file_path: String::new(), file_path: String::new(),
crate_path: String::new(), crate_path: String::new(),
line: 2, line: 3,
column: 0, column: 0,
}; };
@@ -127,6 +177,7 @@ fn render_component() {
expressions: Vec::new(), expressions: Vec::new(),
listeners: Vec::new(), listeners: Vec::new(),
location: location.clone(), location: location.clone(),
custom_attributes: &[],
}; };
dioxus_rsx_interpreter::resolve_scope( dioxus_rsx_interpreter::resolve_scope(
location, location,
@@ -162,7 +213,7 @@ fn render_iterator() {
let location = CodeLocation { let location = CodeLocation {
file_path: String::new(), file_path: String::new(),
crate_path: String::new(), crate_path: String::new(),
line: 3, line: 4,
column: 0, column: 0,
}; };
@@ -180,6 +231,7 @@ fn render_iterator() {
expressions: Vec::new(), expressions: Vec::new(),
listeners: Vec::new(), listeners: Vec::new(),
location: location.clone(), location: location.clone(),
custom_attributes: &[],
}; };
dioxus_rsx_interpreter::resolve_scope( dioxus_rsx_interpreter::resolve_scope(
location, location,
@@ -216,7 +268,7 @@ fn render_captured_variable() {
let location = CodeLocation { let location = CodeLocation {
file_path: String::new(), file_path: String::new(),
crate_path: String::new(), crate_path: String::new(),
line: 4, line: 5,
column: 0, column: 0,
}; };
@@ -234,6 +286,7 @@ fn render_captured_variable() {
expressions: Vec::new(), expressions: Vec::new(),
listeners: Vec::new(), listeners: Vec::new(),
location: location.clone(), location: location.clone(),
custom_attributes: &[],
}; };
dioxus_rsx_interpreter::resolve_scope( dioxus_rsx_interpreter::resolve_scope(
location, location,
@@ -268,7 +321,7 @@ fn render_listener() {
let location = CodeLocation { let location = CodeLocation {
file_path: String::new(), file_path: String::new(),
crate_path: String::new(), crate_path: String::new(),
line: 5, line: 6,
column: 0, column: 0,
}; };
@@ -287,6 +340,7 @@ fn render_listener() {
dioxus_elements::on::onclick(factory, f), dioxus_elements::on::onclick(factory, f),
)], )],
location: location.clone(), location: location.clone(),
custom_attributes: &[],
}; };
dioxus_rsx_interpreter::resolve_scope( dioxus_rsx_interpreter::resolve_scope(
location, location,