Просмотр исходного кода

derive serde for Errors and Location, and add error handler

Evan Almloff 3 лет назад
Родитель
Сommit
51b87dafcc

+ 6 - 5
examples/hot_reload.rs

@@ -1,7 +1,7 @@
 use dioxus::prelude::*;
 
 fn main() {
-    dioxus::desktop::launch_with_props(with_hot_reload, app, |c| c);
+    dioxus::desktop::launch(app);
 }
 
 fn app(cx: Scope) -> Element {
@@ -46,13 +46,14 @@ fn app(cx: Scope) -> Element {
             display: "flex",
             flex_direction: "row",
             width: "100%",
-            height: "50%",
+            height: "100%",
             Editable{
                current_code: submitted_rsx_code.get().clone(),
             },
 
             textarea {
-                width: "90%",
+                width: "50em",
+                height: "50em",
                 value: rsx_code,
                 oninput: move |evt| {
                     rsx_code.set(evt.value.clone());
@@ -80,11 +81,11 @@ struct EditableProps {
 fn Editable(cx: Scope<EditableProps>) -> Element {
     let count = use_state(&cx, || 170);
     if let Some(code) = cx.props.current_code.as_ref() {
-        let rsx_index: RsxTextIndex = cx.consume_context().unwrap();
+        let rsx_index: RsxContext = cx.consume_context().unwrap();
         rsx_index.insert(
             CodeLocation {
                 file: r"examples\hot_reload.rs".to_string(),
-                line: 93,
+                line: 94,
                 column: 15,
             },
             code.clone(),

+ 4 - 4
packages/core-macro/src/lib.rs

@@ -193,9 +193,9 @@ pub fn rsx(s: TokenStream) -> TokenStream {
                         quote::quote! {
                             {
                                 let __line_num = get_line_num();
-                                let __rsx_text_index: RsxTextIndex = cx.consume_context().unwrap();
+                                let __rsx_text_index: RsxContext = cx.consume_context().expect("Hot reload is not avalable on this platform");
                                 // only the insert the rsx text once
-                                if !__rsx_text_index.read().contains_key(&__line_num){
+                                if !__rsx_text_index.read().hm.contains_key(&__line_num){
                                     __rsx_text_index.insert(
                                         __line_num.clone(),
                                         #rsx_text.to_string(),
@@ -205,7 +205,7 @@ pub fn rsx(s: TokenStream) -> TokenStream {
                                     if let Some(__text) = {
                                         let read = __rsx_text_index.read();
                                         // clone prevents deadlock on nested rsx calls
-                                        read.get(&__line_num).cloned()
+                                        read.hm.get(&__line_num).cloned()
                                     } {
                                         match interpert_rsx(
                                             __cx,
@@ -213,7 +213,7 @@ pub fn rsx(s: TokenStream) -> TokenStream {
                                             #captured
                                         ){
                                             Ok(vnode) => vnode,
-                                            Err(err) => __cx.text(format_args!("{:?}", err))
+                                            Err(_) => __cx.text(format_args!(""))
                                         }
                                     }
                                     else {

+ 0 - 1
packages/desktop/Cargo.toml

@@ -42,7 +42,6 @@ fullscreen = ["wry/fullscreen"]
 transparent = ["wry/transparent"]
 tray = ["wry/tray"]
 
-
 [dev-dependencies]
 dioxus-core-macro = { path = "../core-macro" }
 dioxus-hooks = { path = "../hooks" }

+ 3 - 0
packages/rsx_interperter/Cargo.toml

@@ -7,6 +7,9 @@ license = "MIT/Apache-2.0"
 [dependencies]
 syn = { version = "1.0", features = ["extra-traits"] }
 quote = "1.0"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = { vesion = "1.0" }
+
 dioxus-rsx = { path = "../rsx", default-features = false }
 dioxus-ssr = { path = "../ssr" }
 dioxus-core = { path = "../core" }

+ 3 - 1
packages/rsx_interperter/src/error.rs

@@ -1,10 +1,12 @@
+use serde::{Deserialize, Serialize};
+
 #[derive(Debug)]
 pub enum Error {
     ParseError(syn::Error),
     RecompileRequiredError(RecompileReason),
 }
 
-#[derive(Debug)]
+#[derive(Debug, Serialize, Deserialize)]
 pub enum RecompileReason {
     CapturedVariable(String),
     CapturedExpression(String),

+ 25 - 22
packages/rsx_interperter/src/lib.rs

@@ -2,10 +2,10 @@ use dioxus_core::{Component, Element, LazyNodes, Scope, VNode};
 use dioxus_hooks::*;
 use error::Error;
 use interperter::build;
+use serde::{Deserialize, Serialize};
 use std::collections::HashMap;
 use std::panic::Location;
-use std::rc::Rc;
-use std::sync::{RwLock, RwLockReadGuard};
+use std::sync::{Arc, RwLock, RwLockReadGuard};
 use syn::parse_str;
 
 mod attributes;
@@ -14,25 +14,13 @@ mod elements;
 mod error;
 mod interperter;
 
-#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
 pub struct CodeLocation {
     pub file: String,
     pub line: u32,
     pub column: u32,
 }
 
-pub fn with_hot_reload(cx: Scope<Component>) -> Element {
-    use_state(&cx, || {
-        if cx.consume_context::<RsxTextIndex>().is_none() {
-            let index = RsxTextIndex::default();
-            cx.provide_context(index);
-        }
-    });
-    cx.render(LazyNodes::new(|node_factory| {
-        node_factory.component(*cx.props, (), None, "app")
-    }))
-}
-
 pub fn interpert_rsx<'a, 'b>(
     factory: dioxus_core::NodeFactory<'a>,
     text: &str,
@@ -55,17 +43,32 @@ pub fn get_line_num() -> CodeLocation {
     }
 }
 
-#[derive(Debug, Default, Clone)]
-pub struct RsxTextIndex {
-    hm: Rc<RwLock<HashMap<CodeLocation, String>>>,
+#[derive(Debug, Clone)]
+pub struct RsxContext {
+    data: Arc<RwLock<RsxData>>,
 }
 
-impl RsxTextIndex {
+pub struct RsxData {
+    pub hm: HashMap<CodeLocation, String>,
+    error_handle: Box<dyn FnMut(Error)>,
+}
+
+impl std::fmt::Debug for RsxData {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("RsxData").field("hm", &self.hm).finish()
+    }
+}
+
+impl RsxContext {
     pub fn insert(&self, loc: CodeLocation, text: String) {
-        self.hm.write().unwrap().insert(loc, text);
+        self.data.write().unwrap().hm.insert(loc, text);
+    }
+
+    pub fn read(&self) -> RwLockReadGuard<RsxData> {
+        self.data.read().unwrap()
     }
 
-    pub fn read(&self) -> RwLockReadGuard<HashMap<CodeLocation, String>> {
-        self.hm.read().unwrap()
+    pub fn report_error(&self, error: Error) {
+        (self.data.write().unwrap().error_handle)(error)
     }
 }

+ 1 - 1
src/lib.rs

@@ -62,6 +62,6 @@ pub mod prelude {
     #[cfg(feature = "hot_reload")]
     pub use dioxus_rsx_interperter::{
         captuered_context::{CapturedContext, FormattedArg, IfmtArgs},
-        get_line_num, interpert_rsx, with_hot_reload, CodeLocation, RsxTextIndex,
+        get_line_num, interpert_rsx, CodeLocation, RsxContext,
     };
 }