eval.rs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. use std::rc::Rc;
  2. use crate::query::Query;
  3. use crate::query::QueryError;
  4. use crate::use_window;
  5. use dioxus_core::ScopeState;
  6. use std::future::Future;
  7. use std::future::IntoFuture;
  8. use std::pin::Pin;
  9. /// A future that resolves to the result of a JavaScript evaluation.
  10. pub struct EvalResult {
  11. pub(crate) query: Query<serde_json::Value>,
  12. }
  13. impl EvalResult {
  14. pub(crate) fn new(query: Query<serde_json::Value>) -> Self {
  15. Self { query }
  16. }
  17. }
  18. impl IntoFuture for EvalResult {
  19. type Output = Result<serde_json::Value, QueryError>;
  20. type IntoFuture = Pin<Box<dyn Future<Output = Result<serde_json::Value, QueryError>>>>;
  21. fn into_future(self) -> Self::IntoFuture {
  22. Box::pin(self.query.resolve())
  23. as Pin<Box<dyn Future<Output = Result<serde_json::Value, QueryError>>>>
  24. }
  25. }
  26. /// Get a closure that executes any JavaScript in the WebView context.
  27. pub fn use_eval(cx: &ScopeState) -> &Rc<dyn Fn(String) -> EvalResult> {
  28. let desktop = use_window(cx);
  29. &*cx.use_hook(|| {
  30. let desktop = desktop.clone();
  31. Rc::new(move |script: String| desktop.eval(&script)) as Rc<dyn Fn(String) -> EvalResult>
  32. })
  33. }