handle formatting options
This commit is contained in:
1 parent
2183ecf3fb
commit
94448ea4aa
10 files changed
+278
-386
No files matched your search
@@ -1,8 +1,10 @@
|
||||
use dioxus_core::{Listener, VNode};
|
||||
use dioxus_rsx::{BodyNode, CallBody, Component, ElementAttr, ElementAttrNamed, IfmtInput};
|
||||
use dioxus_rsx::{
|
||||
BodyNode, CallBody, Component, ElementAttr, ElementAttrNamed, IfmtInput, Segment,
|
||||
};
|
||||
use quote::{quote, ToTokens, TokenStreamExt};
|
||||
use std::collections::HashMap;
|
||||
use syn::Expr;
|
||||
use syn::{Expr, Result};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct CapturedContextBuilder {
|
||||
@@ -24,15 +26,15 @@ impl CapturedContextBuilder {
|
||||
self.captured_expressions.extend(other.captured_expressions);
|
||||
}
|
||||
|
||||
pub fn from_call_body(body: CallBody) -> Self {
|
||||
pub fn from_call_body(body: CallBody) -> Result<Self> {
|
||||
let mut new = Self::default();
|
||||
for node in body.roots {
|
||||
new.extend(Self::find_captured(node));
|
||||
new.extend(Self::find_captured(node)?);
|
||||
}
|
||||
new
|
||||
Ok(new)
|
||||
}
|
||||
|
||||
fn find_captured(node: BodyNode) -> Self {
|
||||
fn find_captured(node: BodyNode) -> Result<Self> {
|
||||
let mut captured = CapturedContextBuilder::default();
|
||||
match node {
|
||||
BodyNode::Element(el) => {
|
||||
@@ -40,7 +42,7 @@ impl CapturedContextBuilder {
|
||||
match attr.attr {
|
||||
ElementAttr::AttrText { name, value } => {
|
||||
let (name, value_tokens) = (name.to_string(), value.to_token_stream());
|
||||
let formated: IfmtInput = syn::parse2(value_tokens).unwrap();
|
||||
let formated: IfmtInput = syn::parse2(value_tokens)?;
|
||||
captured.attributes.insert(name, formated);
|
||||
}
|
||||
ElementAttr::AttrExpression { name: _, value } => {
|
||||
@@ -48,7 +50,7 @@ impl CapturedContextBuilder {
|
||||
}
|
||||
ElementAttr::CustomAttrText { name, value } => {
|
||||
let (name, value_tokens) = (name.value(), value.to_token_stream());
|
||||
let formated: IfmtInput = syn::parse2(value_tokens).unwrap();
|
||||
let formated: IfmtInput = syn::parse2(value_tokens)?;
|
||||
captured.attributes.insert(name, formated);
|
||||
}
|
||||
ElementAttr::CustomAttrExpression { name: _, value } => {
|
||||
@@ -58,7 +60,7 @@ impl CapturedContextBuilder {
|
||||
}
|
||||
}
|
||||
for child in el.children {
|
||||
captured.extend(Self::find_captured(child));
|
||||
captured.extend(Self::find_captured(child)?);
|
||||
}
|
||||
}
|
||||
BodyNode::Component(comp) => {
|
||||
@@ -71,7 +73,7 @@ impl CapturedContextBuilder {
|
||||
}
|
||||
BodyNode::RawExpr(_) => captured.iterators.push(node),
|
||||
}
|
||||
captured
|
||||
Ok(captured)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,34 +97,41 @@ impl ToTokens for CapturedContextBuilder {
|
||||
BodyNode::RawExpr(expr) => expr.to_token_stream().to_string(),
|
||||
_ => unreachable!(),
|
||||
});
|
||||
let captured_named: Vec<_> = attributes
|
||||
.iter()
|
||||
.map(|(_, fmt)| fmt.named_args.iter())
|
||||
.chain(text.iter().map(|fmt| fmt.named_args.iter()))
|
||||
let captured: Vec<_> = attributes
|
||||
.values()
|
||||
.chain(text.iter())
|
||||
.map(|input| input.segments.iter())
|
||||
.flatten()
|
||||
.filter_map(|seg| match seg {
|
||||
Segment::Formatted {
|
||||
format_args,
|
||||
segment,
|
||||
} => {
|
||||
let expr = segment.to_token_stream();
|
||||
let as_string = expr.to_string();
|
||||
let format_expr = if format_args.is_empty() {
|
||||
"{".to_string() + format_args + "}"
|
||||
} else {
|
||||
"{".to_string() + ":" + format_args + "}"
|
||||
};
|
||||
Some(quote! {
|
||||
FormattedArg{
|
||||
expr: #as_string,
|
||||
format_args: #format_args,
|
||||
result: format!(#format_expr, #expr)
|
||||
}
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let captured_expr: Vec<_> = attributes
|
||||
.iter()
|
||||
.map(|(_, fmt)| fmt.positional_args.iter())
|
||||
.chain(text.iter().map(|fmt| fmt.positional_args.iter()))
|
||||
.flatten()
|
||||
.collect();
|
||||
let captured_names = captured_named.iter().map(|(n, _)| n.to_string()).chain(
|
||||
captured_expr
|
||||
.iter()
|
||||
.map(|expr| expr.to_token_stream().to_string()),
|
||||
);
|
||||
let captured_expr = captured_named
|
||||
.iter()
|
||||
.map(|(_, e)| e)
|
||||
.chain(captured_expr.iter().map(|expr| *expr));
|
||||
let captured_attr_expressions_text = captured_expressions
|
||||
.iter()
|
||||
.map(|e| format!("{}", e.to_token_stream()));
|
||||
tokens.append_all(quote! {
|
||||
CapturedContext {
|
||||
captured: IfmtArgs{
|
||||
named_args: vec![#((#captured_names, #captured_expr.to_string())),*]
|
||||
named_args: vec![#(#captured),*]
|
||||
},
|
||||
components: vec![#((#compontents_str, #components)),*],
|
||||
iterators: vec![#((#iterators_str, #iterators)),*],
|
||||
@@ -149,6 +158,12 @@ pub struct CapturedContext<'a> {
|
||||
}
|
||||
|
||||
pub struct IfmtArgs {
|
||||
// live reload only supports named arguments
|
||||
pub named_args: Vec<(&'static str, String)>,
|
||||
// map expressions to the value string they produced
|
||||
pub named_args: Vec<FormattedArg>,
|
||||
}
|
||||
|
||||
pub struct FormattedArg {
|
||||
pub expr: &'static str,
|
||||
pub format_args: &'static str,
|
||||
pub result: String,
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use dioxus_core::{Attribute, AttributeValue, NodeFactory, VNode};
|
||||
use dioxus_rsx::{BodyNode, CallBody, ElementAttr};
|
||||
use dioxus_rsx::{BodyNode, CallBody, ElementAttr, IfmtInput, Segment};
|
||||
use quote::ToTokens;
|
||||
use std::str::FromStr;
|
||||
use syn::{parse2, parse_str, Expr};
|
||||
|
||||
use crate::attributes::attrbute_to_static_str;
|
||||
@@ -9,28 +8,31 @@ use crate::captuered_context::{CapturedContext, IfmtArgs};
|
||||
use crate::elements::element_to_static_str;
|
||||
use crate::error::{Error, RecompileReason};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Segment {
|
||||
Ident(String),
|
||||
Literal(String),
|
||||
}
|
||||
struct InterpertedIfmt(IfmtInput);
|
||||
|
||||
struct InterperedIfmt {
|
||||
segments: Vec<Segment>,
|
||||
}
|
||||
|
||||
impl InterperedIfmt {
|
||||
impl InterpertedIfmt {
|
||||
fn resolve(&self, captured: &IfmtArgs) -> String {
|
||||
let mut result = String::new();
|
||||
for seg in &self.segments {
|
||||
for seg in &self.0.segments {
|
||||
match seg {
|
||||
Segment::Ident(name) => {
|
||||
let (_, value) = captured
|
||||
Segment::Formatted {
|
||||
segment,
|
||||
format_args,
|
||||
} => {
|
||||
let expr = segment.to_token_stream();
|
||||
let expr_str = expr.to_string();
|
||||
let expr: Expr = parse2(expr).unwrap();
|
||||
let formatted = captured
|
||||
.named_args
|
||||
.iter()
|
||||
.find(|(n, _)| *n == name)
|
||||
.expect(format!("could not resolve {}", name).as_str());
|
||||
result.push_str(value);
|
||||
.find(|fmted| {
|
||||
parse_str::<Expr>(fmted.expr).unwrap() == expr
|
||||
&& fmted.format_args == format_args
|
||||
})
|
||||
.expect(
|
||||
format!("could not resolve {{{}:{}}}", expr_str, format_args).as_str(),
|
||||
);
|
||||
result.push_str(&formatted.result);
|
||||
}
|
||||
Segment::Literal(lit) => result.push_str(lit),
|
||||
}
|
||||
@@ -39,52 +41,6 @@ impl InterperedIfmt {
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for InterperedIfmt {
|
||||
type Err = ();
|
||||
fn from_str(input: &str) -> Result<Self, ()> {
|
||||
let mut segments = Vec::new();
|
||||
let mut segment = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '{' {
|
||||
if chars.peek().copied() != Some('{') {
|
||||
let old;
|
||||
(old, segment) = (segment, String::new());
|
||||
if !old.is_empty() {
|
||||
segments.push(Segment::Literal(old));
|
||||
}
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '}' {
|
||||
let old;
|
||||
(old, segment) = (segment, String::new());
|
||||
if !old.is_empty() {
|
||||
segments.push(Segment::Ident(old));
|
||||
}
|
||||
break;
|
||||
}
|
||||
if c == ':' {
|
||||
while Some('}') != chars.next() {}
|
||||
let old;
|
||||
(old, segment) = (segment, String::new());
|
||||
if !old.is_empty() {
|
||||
segments.push(Segment::Ident(old));
|
||||
}
|
||||
break;
|
||||
}
|
||||
segment.push(c);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
segment.push(c);
|
||||
}
|
||||
}
|
||||
if !segment.is_empty() {
|
||||
segments.push(Segment::Literal(segment));
|
||||
}
|
||||
Ok(Self { segments })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build<'a>(
|
||||
rsx: CallBody,
|
||||
mut ctx: CapturedContext<'a>,
|
||||
@@ -105,7 +61,9 @@ fn build_node<'a>(
|
||||
let bump = factory.bump();
|
||||
match node {
|
||||
BodyNode::Text(text) => {
|
||||
let ifmt: InterperedIfmt = text.value().parse().unwrap();
|
||||
let ifmt = InterpertedIfmt(
|
||||
IfmtInput::from_str(&text.value()).map_err(|err| Error::ParseError(err))?,
|
||||
);
|
||||
let text = bump.alloc(ifmt.resolve(&ctx.captured));
|
||||
Ok(factory.text(format_args!("{}", text)))
|
||||
}
|
||||
@@ -114,13 +72,21 @@ fn build_node<'a>(
|
||||
for attr in &el.attributes {
|
||||
match &attr.attr {
|
||||
ElementAttr::AttrText { .. } | ElementAttr::CustomAttrText { .. } => {
|
||||
let (name, value): (String, InterperedIfmt) = match &attr.attr {
|
||||
ElementAttr::AttrText { name, value } => {
|
||||
(name.to_string(), value.value().parse().unwrap())
|
||||
}
|
||||
ElementAttr::CustomAttrText { name, value } => {
|
||||
(name.value(), value.value().parse().unwrap())
|
||||
}
|
||||
let (name, value): (String, InterpertedIfmt) = match &attr.attr {
|
||||
ElementAttr::AttrText { name, value } => (
|
||||
name.to_string(),
|
||||
InterpertedIfmt(
|
||||
IfmtInput::from_str(&value.value())
|
||||
.map_err(|err| Error::ParseError(err))?,
|
||||
),
|
||||
),
|
||||
ElementAttr::CustomAttrText { name, value } => (
|
||||
name.value(),
|
||||
InterpertedIfmt(
|
||||
IfmtInput::from_str(&value.value())
|
||||
.map_err(|err| Error::ParseError(err))?,
|
||||
),
|
||||
),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
@@ -145,7 +111,6 @@ fn build_node<'a>(
|
||||
ElementAttr::CustomAttrExpression { name, value } => {
|
||||
(name.value(), value)
|
||||
}
|
||||
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if let Some((_, resulting_value)) = ctx
|
||||
@@ -219,7 +184,9 @@ fn build_node<'a>(
|
||||
None,
|
||||
)),
|
||||
Some(lit) => {
|
||||
let ifmt: InterperedIfmt = lit.value().parse().unwrap();
|
||||
let ifmt: InterpertedIfmt = InterpertedIfmt(
|
||||
parse_str(&lit.value()).map_err(|err| Error::ParseError(err))?,
|
||||
);
|
||||
let key = bump.alloc(ifmt.resolve(&ctx.captured));
|
||||
|
||||
Ok(factory.raw_element(
|
||||
|
||||
Reference in new issue
Block a user