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/// - `&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<F>(selector: &str, render_fn: F)
16where
17    F: FnOnce() -> VirtualNode,
18{
19    let window: Window = match window() {
20        Some(window_instance) => window_instance,
21        None => return,
22    };
23    let document: Document = match window.document() {
24        Some(document_instance) => document_instance,
25        None => return,
26    };
27    let target: Element = if selector == BODY_TAG {
28        match document.body() {
29            Some(body) => body.into(),
30            None => return,
31        }
32    } else if let Some(id) = selector.strip_prefix(ID_SELECTOR_PREFIX) {
33        match document.get_element_by_id(id) {
34            Some(element) => element,
35            None => return,
36        }
37    } else if let Some(class) = selector.strip_prefix(CLASS_SELECTOR_PREFIX) {
38        match document.get_elements_by_class_name(class).item(0) {
39            Some(element) => element,
40            None => return,
41        }
42    } else {
43        match document.get_elements_by_tag_name(selector).item(0) {
44            Some(element) => element,
45            None => return,
46        }
47    };
48    Renderer::new(target).render(render_fn());
49}