Skip to main content

euv_core/renderer/render/
fn.rs

1use crate::*;
2
3/// Mounts the given virtual DOM tree to the document body.
4///
5/// # Arguments
6///
7/// - `FnOnce() -> VirtualNode + 'static` - A closure that returns the virtual DOM tree to render.
8///
9/// # Panics
10///
11/// Panics if the document body cannot be found.
12pub fn mount_body<F>(render_fn: F)
13where
14    F: FnOnce() -> VirtualNode,
15{
16    mount("body", render_fn);
17}
18
19/// Mounts the given virtual DOM tree to a specific element matched by a CSS selector.
20///
21/// Supported selector syntax:
22/// - `"#id"` — select by element ID
23/// - `".class"` — select by class name (uses the first match)
24/// - `"tag"` — select by tag name (uses the first match)
25///
26/// # Arguments
27///
28/// - `&str` - A CSS selector string to locate the target element.
29/// - `FnOnce() -> VirtualNode + 'static` - A closure that returns the virtual DOM tree to render.
30///
31/// # Panics
32///
33/// Panics if no global `window` or `document` exists, or if the selector does not match any element.
34pub fn mount<F>(selector: &str, render_fn: F)
35where
36    F: FnOnce() -> VirtualNode,
37{
38    let window: Window = web_sys::window().expect("no global window exists");
39    let document: Document = window.document().expect("should have a document");
40    let target: Element = if selector == "body" {
41        document.body().expect("document should have a body").into()
42    } else if let Some(id) = selector.strip_prefix('#') {
43        document
44            .get_element_by_id(id)
45            .unwrap_or_else(|| panic!("no element found with id '{}'", id))
46    } else if let Some(class) = selector.strip_prefix('.') {
47        document
48            .get_elements_by_class_name(class)
49            .item(0)
50            .unwrap_or_else(|| panic!("no element found with class '{}'", class))
51    } else {
52        document
53            .get_elements_by_tag_name(selector)
54            .item(0)
55            .unwrap_or_else(|| panic!("no element found with tag '{}'", selector))
56    };
57    let mut renderer: Renderer = Renderer::new(target);
58    let vnode: VirtualNode = render_fn();
59    renderer.render(vnode);
60}