Skip to content

Commit

Permalink
Add a generic from_web_sys function (#432)
Browse files Browse the repository at this point in the history
* Add a generic from_web_sys function

Adds a new function that creates a `GenericNode` from a
`web_sys::Element` and depending on the type will reuse
the element in the DOM.

* Fix suggestions

* Fix panic case and imports
  • Loading branch information
mc1098 authored Jun 11, 2022
1 parent 215a015 commit 53ec292
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/sycamore-web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ mod hydrate_node;
#[cfg(feature = "ssr")]
mod ssr_node;

use std::any::{Any, TypeId};

pub use dom_node::*;
#[cfg(feature = "hydrate")]
pub use hydrate_node::*;
Expand All @@ -35,6 +37,26 @@ pub trait Html: GenericNode<EventType = Event, PropertyType = JsValue> {
const IS_BROWSER: bool;
}

/// Create a generic `Html` node from a `web_sys::Node`.
///
/// # Panics
/// When G is not either a `DomNode` or a `HydrateNode`.
pub fn from_web_sys<G: Html>(node: web_sys::Node) -> G {
let type_id = TypeId::of::<G>();

if TypeId::of::<DomNode>() == type_id {
let node = DomNode::from_web_sys(node);
return (&node as &dyn Any).downcast_ref().cloned().unwrap();
}
#[cfg(feature = "hydrate")]
if TypeId::of::<HydrateNode>() == type_id {
let node = HydrateNode::from_web_sys(node);
return (&node as &dyn Any).downcast_ref().cloned().unwrap();
}

panic!("expected GenericNode to either be a DomNode or a HydrateNode");
}

/// Queue up a callback to be executed when the component is mounted.
///
/// If not on `wasm32` target, does nothing.
Expand Down

0 comments on commit 53ec292

Please sign in to comment.