Skip to main content

euv_core/renderer/render/
fn.rs

1use crate::*;
2
3/// Mounts the given virtual DOM tree to a specific element matched by a CSS selector.
4///
5/// Supported selector syntax:
6/// - `"#id"` — select by element ID
7/// - `".class"` — select by class name (uses the first match)
8/// - `"tag"` — select by tag name (uses the first match)
9///
10/// # Arguments
11///
12/// - `S: AsRef<str>` - A CSS selector string to locate the target element.
13/// - `FnOnce() -> VirtualNode + 'static` - A closure that returns the virtual DOM tree to render.
14///
15pub fn mount<S, F>(selector: S, render_fn: F)
16where
17    S: AsRef<str>,
18    F: FnOnce() -> VirtualNode,
19{
20    let selector: &str = selector.as_ref();
21    let window: Window = match window() {
22        Some(window_instance) => window_instance,
23        None => return,
24    };
25    let document: Document = match window.document() {
26        Some(document_instance) => document_instance,
27        None => return,
28    };
29    let target: Element = if selector == BODY_TAG {
30        match document.body() {
31            Some(body) => body.into(),
32            None => return,
33        }
34    } else if let Some(id) = selector.strip_prefix(ID_SELECTOR_PREFIX) {
35        match document.get_element_by_id(id) {
36            Some(element) => element,
37            None => return,
38        }
39    } else if let Some(class) = selector.strip_prefix(CLASS_SELECTOR_PREFIX) {
40        match document.get_elements_by_class_name(class).item(0) {
41            Some(element) => element,
42            None => return,
43        }
44    } else {
45        match document.get_elements_by_tag_name(selector).item(0) {
46            Some(element) => element,
47            None => return,
48        }
49    };
50    Renderer::new(target).render(render_fn());
51}