Skip to main content

strata_js/engine/
dom.rs

1//! W3C DOM Tree representation, client-side mutations, and HTML5 fragment serialization.
2
3use super::JsEngine;
4use crate::JsValue;
5use std::cell::RefCell;
6use std::collections::HashMap;
7use std::rc::{Rc, Weak};
8use std::sync::atomic::{AtomicU64, Ordering};
9
10static NEXT_DOM_UID: AtomicU64 = AtomicU64::new(1);
11
12/// Types of live client-side DOM mutations emitted during script evaluation or native DOM manipulation.
13#[derive(Debug, Clone, PartialEq)]
14pub enum DomMutationType {
15    ChildAppended {
16        parent_uid: u64,
17        child_uid: u64,
18    },
19    ChildPrepended {
20        parent_uid: u64,
21        child_uid: u64,
22    },
23    ChildInserted {
24        parent_uid: u64,
25        child_uid: u64,
26        before_uid: Option<u64>,
27    },
28    ChildRemoved {
29        parent_uid: u64,
30        child_uid: u64,
31    },
32    ChildReplaced {
33        parent_uid: u64,
34        new_child_uid: u64,
35        old_child_uid: u64,
36    },
37    AttributeSet {
38        node_uid: u64,
39        name: String,
40        value: String,
41    },
42    AttributeRemoved {
43        node_uid: u64,
44        name: String,
45    },
46    TextContentChanged {
47        node_uid: u64,
48        new_text: String,
49    },
50    InnerHtmlChanged {
51        node_uid: u64,
52        html: String,
53    },
54    StyleChanged {
55        node_uid: u64,
56        property: String,
57        value: String,
58    },
59}
60
61/// A fine-grained record describing an individual DOM mutation.
62#[derive(Debug, Clone, PartialEq)]
63pub struct DomMutationRecord {
64    pub target_uid: u64,
65    pub mutation: DomMutationType,
66}
67
68pub type MutationListener = Rc<RefCell<dyn FnMut(&DomMutationRecord)>>;
69
70/// Notification sink shared across DOM nodes and the containing Document.
71pub struct MutationSink {
72    pub queue: Vec<DomMutationRecord>,
73    pub listeners: Vec<MutationListener>,
74    pub sender: Option<std::sync::mpsc::Sender<DomMutationRecord>>,
75    pub mutated: bool,
76}
77
78impl Default for MutationSink {
79    fn default() -> Self {
80        Self::new()
81    }
82}
83
84impl MutationSink {
85    pub fn new() -> Self {
86        Self {
87            queue: Vec::new(),
88            listeners: Vec::new(),
89            sender: None,
90            mutated: false,
91        }
92    }
93
94    pub fn emit(&mut self, record: DomMutationRecord) {
95        self.mutated = true;
96        self.queue.push(record.clone());
97        for listener in &self.listeners {
98            if let Ok(mut l) = listener.try_borrow_mut() {
99                (l)(&record);
100            }
101        }
102        if let Some(ref sender) = self.sender {
103            let _ = sender.send(record);
104        }
105    }
106}
107
108/// Types of DOM nodes supported by the engine.
109#[derive(Debug, Clone, PartialEq)]
110pub enum DomNodeType {
111    Element {
112        tag: String,
113        attributes: HashMap<String, String>,
114        style: HashMap<String, String>,
115    },
116    Text(String),
117    Comment(String),
118}
119
120/// A node in the Document Object Model tree.
121#[derive(Clone)]
122pub struct DomNode {
123    pub inner: Rc<RefCell<DomNodeInner>>,
124}
125
126pub struct DomNodeInner {
127    pub uid: u64,
128    pub node_type: DomNodeType,
129    pub parent: Option<Weak<RefCell<DomNodeInner>>>,
130    pub children: Vec<DomNode>,
131    pub event_listeners: HashMap<String, Vec<JsValue>>,
132    pub mutation_sink: Option<Rc<RefCell<MutationSink>>>,
133}
134
135impl DomNode {
136    pub fn element(tag: &str, attributes: HashMap<String, String>) -> Self {
137        Self {
138            inner: Rc::new(RefCell::new(DomNodeInner {
139                uid: NEXT_DOM_UID.fetch_add(1, Ordering::Relaxed),
140                node_type: DomNodeType::Element {
141                    tag: tag.to_ascii_lowercase(),
142                    attributes,
143                    style: HashMap::new(),
144                },
145                parent: None,
146                children: Vec::new(),
147                event_listeners: HashMap::new(),
148                mutation_sink: None,
149            })),
150        }
151    }
152
153    pub fn text(content: &str) -> Self {
154        Self {
155            inner: Rc::new(RefCell::new(DomNodeInner {
156                uid: NEXT_DOM_UID.fetch_add(1, Ordering::Relaxed),
157                node_type: DomNodeType::Text(content.to_string()),
158                parent: None,
159                children: Vec::new(),
160                event_listeners: HashMap::new(),
161                mutation_sink: None,
162            })),
163        }
164    }
165
166    pub fn comment(content: &str) -> Self {
167        Self {
168            inner: Rc::new(RefCell::new(DomNodeInner {
169                uid: NEXT_DOM_UID.fetch_add(1, Ordering::Relaxed),
170                node_type: DomNodeType::Comment(content.to_string()),
171                parent: None,
172                children: Vec::new(),
173                event_listeners: HashMap::new(),
174                mutation_sink: None,
175            })),
176        }
177    }
178
179    pub(crate) fn emit_mutation(&self, mutation: DomMutationType, target_uid: u64) {
180        let inner = self.inner.borrow();
181        if let Some(ref sink) = inner.mutation_sink {
182            sink.borrow_mut().emit(DomMutationRecord {
183                target_uid,
184                mutation,
185            });
186        }
187    }
188
189    pub(crate) fn set_mutation_sink_recursive(&self, sink: &Rc<RefCell<MutationSink>>) {
190        let mut inner = self.inner.borrow_mut();
191        inner.mutation_sink = Some(sink.clone());
192        for child in &inner.children {
193            child.set_mutation_sink_recursive(sink);
194        }
195    }
196
197    pub fn tag_name(&self) -> Option<String> {
198        let inner = self.inner.borrow();
199        match &inner.node_type {
200            DomNodeType::Element { tag, .. } => Some(tag.to_ascii_uppercase()),
201            _ => None,
202        }
203    }
204
205    pub fn id(&self) -> Option<String> {
206        self.get_attribute("id")
207    }
208
209    pub fn class_name(&self) -> String {
210        self.get_attribute("class").unwrap_or_default()
211    }
212
213    pub fn set_class_name(&self, val: &str) {
214        self.set_attribute("class", val);
215    }
216
217    pub fn get_attribute(&self, name: &str) -> Option<String> {
218        let inner = self.inner.borrow();
219        match &inner.node_type {
220            DomNodeType::Element { attributes, .. } => {
221                let name_lower = name.to_ascii_lowercase();
222                attributes.get(&name_lower).cloned()
223            }
224            _ => None,
225        }
226    }
227
228    pub fn set_attribute(&self, name: &str, val: &str) {
229        let mut inner = self.inner.borrow_mut();
230        let uid = inner.uid;
231        if let DomNodeType::Element {
232            ref mut attributes, ..
233        } = inner.node_type
234        {
235            attributes.insert(name.to_ascii_lowercase(), val.to_string());
236        }
237        drop(inner);
238        self.emit_mutation(
239            DomMutationType::AttributeSet {
240                node_uid: uid,
241                name: name.to_ascii_lowercase(),
242                value: val.to_string(),
243            },
244            uid,
245        );
246    }
247
248    pub fn remove_attribute(&self, name: &str) {
249        let mut inner = self.inner.borrow_mut();
250        let uid = inner.uid;
251        if let DomNodeType::Element {
252            ref mut attributes, ..
253        } = inner.node_type
254        {
255            attributes.remove(&name.to_ascii_lowercase());
256        }
257        drop(inner);
258        self.emit_mutation(
259            DomMutationType::AttributeRemoved {
260                node_uid: uid,
261                name: name.to_ascii_lowercase(),
262            },
263            uid,
264        );
265    }
266
267    pub fn has_attribute(&self, name: &str) -> bool {
268        self.get_attribute(name).is_some()
269    }
270
271    pub fn get_style(&self, prop: &str) -> Option<String> {
272        let inner = self.inner.borrow();
273        match &inner.node_type {
274            DomNodeType::Element { style, .. } => style.get(&prop.to_ascii_lowercase()).cloned(),
275            _ => None,
276        }
277    }
278
279    pub fn set_style(&self, prop: &str, val: &str) {
280        let mut inner = self.inner.borrow_mut();
281        let uid = inner.uid;
282        if let DomNodeType::Element { ref mut style, .. } = inner.node_type {
283            style.insert(prop.to_ascii_lowercase(), val.to_string());
284        }
285        drop(inner);
286        self.emit_mutation(
287            DomMutationType::StyleChanged {
288                node_uid: uid,
289                property: prop.to_ascii_lowercase(),
290                value: val.to_string(),
291            },
292            uid,
293        );
294    }
295
296    pub fn text_content(&self) -> String {
297        let inner = self.inner.borrow();
298        match &inner.node_type {
299            DomNodeType::Text(s) => s.clone(),
300            DomNodeType::Comment(_) => String::new(),
301            DomNodeType::Element { .. } => {
302                let mut out = String::new();
303                for child in &inner.children {
304                    out.push_str(&child.text_content());
305                }
306                out
307            }
308        }
309    }
310
311    pub fn uid(&self) -> u64 {
312        self.inner.borrow().uid
313    }
314
315    pub fn set_text_content(&self, text: &str) {
316        let child = DomNode::text(text);
317        let sink = self.inner.borrow().mutation_sink.clone();
318        if let Some(ref s) = sink {
319            child.set_mutation_sink_recursive(s);
320        }
321        child.inner.borrow_mut().parent = Some(Rc::downgrade(&self.inner));
322        let mut inner = self.inner.borrow_mut();
323        let uid = inner.uid;
324        inner.children.clear();
325        inner.children.push(child);
326        drop(inner);
327        self.emit_mutation(
328            DomMutationType::TextContentChanged {
329                node_uid: uid,
330                new_text: text.to_string(),
331            },
332            uid,
333        );
334    }
335
336    pub fn inner_html(&self) -> String {
337        let inner = self.inner.borrow();
338        let mut out = String::new();
339        for child in &inner.children {
340            out.push_str(&child.outer_html());
341        }
342        out
343    }
344
345    pub fn set_inner_html(&self, html: &str) {
346        let parsed = parse_html_fragment(html);
347        let sink = self.inner.borrow().mutation_sink.clone();
348        for child in &parsed {
349            if let Some(ref s) = sink {
350                child.set_mutation_sink_recursive(s);
351            }
352            child.inner.borrow_mut().parent = Some(Rc::downgrade(&self.inner));
353        }
354        let mut inner = self.inner.borrow_mut();
355        let uid = inner.uid;
356        inner.children = parsed;
357        drop(inner);
358        self.emit_mutation(
359            DomMutationType::InnerHtmlChanged {
360                node_uid: uid,
361                html: html.to_string(),
362            },
363            uid,
364        );
365    }
366
367    pub fn outer_html(&self) -> String {
368        let inner = self.inner.borrow();
369        match &inner.node_type {
370            DomNodeType::Text(s) => s.clone(),
371            DomNodeType::Comment(c) => format!("<!--{c}-->"),
372            DomNodeType::Element {
373                tag, attributes, ..
374            } => {
375                let mut out = format!("<{tag}");
376                for (k, v) in attributes {
377                    out.push_str(&format!(" {k}=\"{v}\""));
378                }
379                if is_void_element(tag) && inner.children.is_empty() {
380                    out.push_str(" />");
381                } else {
382                    out.push('>');
383                    for child in &inner.children {
384                        out.push_str(&child.outer_html());
385                    }
386                    out.push_str(&format!("</{tag}>"));
387                }
388                out
389            }
390        }
391    }
392
393    pub fn parent_node(&self) -> Option<DomNode> {
394        self.inner
395            .borrow()
396            .parent
397            .as_ref()
398            .and_then(|w| w.upgrade())
399            .map(|inner| DomNode { inner })
400    }
401
402    pub fn parent_element(&self) -> Option<DomNode> {
403        let parent = self.parent_node()?;
404        if matches!(parent.inner.borrow().node_type, DomNodeType::Element { .. }) {
405            Some(parent)
406        } else {
407            None
408        }
409    }
410
411    pub fn first_child(&self) -> Option<DomNode> {
412        self.inner.borrow().children.first().cloned()
413    }
414
415    pub fn last_child(&self) -> Option<DomNode> {
416        self.inner.borrow().children.last().cloned()
417    }
418
419    pub fn first_element_child(&self) -> Option<DomNode> {
420        let inner = self.inner.borrow();
421        inner
422            .children
423            .iter()
424            .find(|c| matches!(c.inner.borrow().node_type, DomNodeType::Element { .. }))
425            .cloned()
426    }
427
428    pub fn last_element_child(&self) -> Option<DomNode> {
429        let inner = self.inner.borrow();
430        inner
431            .children
432            .iter()
433            .rfind(|c| matches!(c.inner.borrow().node_type, DomNodeType::Element { .. }))
434            .cloned()
435    }
436
437    pub fn previous_sibling(&self) -> Option<DomNode> {
438        let parent = self.parent_node()?;
439        let siblings = parent.children();
440        let idx = siblings
441            .iter()
442            .position(|c| Rc::ptr_eq(&c.inner, &self.inner))?;
443        if idx > 0 {
444            Some(siblings[idx - 1].clone())
445        } else {
446            None
447        }
448    }
449
450    pub fn next_sibling(&self) -> Option<DomNode> {
451        let parent = self.parent_node()?;
452        let siblings = parent.children();
453        let idx = siblings
454            .iter()
455            .position(|c| Rc::ptr_eq(&c.inner, &self.inner))?;
456        if idx + 1 < siblings.len() {
457            Some(siblings[idx + 1].clone())
458        } else {
459            None
460        }
461    }
462
463    pub fn previous_element_sibling(&self) -> Option<DomNode> {
464        let mut curr = self.previous_sibling();
465        while let Some(node) = curr {
466            if matches!(node.inner.borrow().node_type, DomNodeType::Element { .. }) {
467                return Some(node);
468            }
469            curr = node.previous_sibling();
470        }
471        None
472    }
473
474    pub fn next_element_sibling(&self) -> Option<DomNode> {
475        let mut curr = self.next_sibling();
476        while let Some(node) = curr {
477            if matches!(node.inner.borrow().node_type, DomNodeType::Element { .. }) {
478                return Some(node);
479            }
480            curr = node.next_sibling();
481        }
482        None
483    }
484
485    pub fn child_element_count(&self) -> usize {
486        let inner = self.inner.borrow();
487        inner
488            .children
489            .iter()
490            .filter(|c| matches!(c.inner.borrow().node_type, DomNodeType::Element { .. }))
491            .count()
492    }
493
494    pub fn child_nodes(&self) -> Vec<DomNode> {
495        self.children()
496    }
497
498    pub fn append_child(&self, child: DomNode) -> DomNode {
499        child.remove();
500        let sink = self.inner.borrow().mutation_sink.clone();
501        if let Some(ref s) = sink {
502            child.set_mutation_sink_recursive(s);
503        }
504        child.inner.borrow_mut().parent = Some(Rc::downgrade(&self.inner));
505        self.inner.borrow_mut().children.push(child.clone());
506        let parent_uid = self.uid();
507        let child_uid = child.uid();
508        self.emit_mutation(
509            DomMutationType::ChildAppended {
510                parent_uid,
511                child_uid,
512            },
513            parent_uid,
514        );
515        child
516    }
517
518    pub fn prepend_child(&self, child: DomNode) -> DomNode {
519        child.remove();
520        let sink = self.inner.borrow().mutation_sink.clone();
521        if let Some(ref s) = sink {
522            child.set_mutation_sink_recursive(s);
523        }
524        child.inner.borrow_mut().parent = Some(Rc::downgrade(&self.inner));
525        self.inner.borrow_mut().children.insert(0, child.clone());
526        let parent_uid = self.uid();
527        let child_uid = child.uid();
528        self.emit_mutation(
529            DomMutationType::ChildPrepended {
530                parent_uid,
531                child_uid,
532            },
533            parent_uid,
534        );
535        child
536    }
537
538    pub fn insert_before(
539        &self,
540        new_child: DomNode,
541        reference_child: Option<&DomNode>,
542    ) -> Result<DomNode, String> {
543        match reference_child {
544            None => Ok(self.append_child(new_child)),
545            Some(ref_node) => {
546                let inner = self.inner.borrow();
547                let idx = inner
548                    .children
549                    .iter()
550                    .position(|c| Rc::ptr_eq(&c.inner, &ref_node.inner))
551                    .ok_or_else(|| {
552                        "NotFoundError: reference node is not a child of this node".to_string()
553                    })?;
554                let before_uid = Some(ref_node.uid());
555                let sink = inner.mutation_sink.clone();
556                drop(inner);
557                new_child.remove();
558                if let Some(ref s) = sink {
559                    new_child.set_mutation_sink_recursive(s);
560                }
561                let mut inner = self.inner.borrow_mut();
562                new_child.inner.borrow_mut().parent = Some(Rc::downgrade(&self.inner));
563                inner.children.insert(idx, new_child.clone());
564                let parent_uid = inner.uid;
565                let child_uid = new_child.uid();
566                drop(inner);
567                self.emit_mutation(
568                    DomMutationType::ChildInserted {
569                        parent_uid,
570                        child_uid,
571                        before_uid,
572                    },
573                    parent_uid,
574                );
575                Ok(new_child)
576            }
577        }
578    }
579
580    pub fn replace_child(
581        &self,
582        new_child: DomNode,
583        old_child: &DomNode,
584    ) -> Result<DomNode, String> {
585        let inner = self.inner.borrow();
586        let idx = inner
587            .children
588            .iter()
589            .position(|c| Rc::ptr_eq(&c.inner, &old_child.inner))
590            .ok_or_else(|| {
591                "NotFoundError: node to be replaced is not a child of this node".to_string()
592            })?;
593        let sink = inner.mutation_sink.clone();
594        drop(inner);
595        new_child.remove();
596        if let Some(ref s) = sink {
597            new_child.set_mutation_sink_recursive(s);
598        }
599        let mut inner = self.inner.borrow_mut();
600        old_child.inner.borrow_mut().parent = None;
601        new_child.inner.borrow_mut().parent = Some(Rc::downgrade(&self.inner));
602        inner.children[idx] = new_child.clone();
603        let parent_uid = inner.uid;
604        let new_child_uid = new_child.uid();
605        let old_child_uid = old_child.uid();
606        drop(inner);
607        self.emit_mutation(
608            DomMutationType::ChildReplaced {
609                parent_uid,
610                new_child_uid,
611                old_child_uid,
612            },
613            parent_uid,
614        );
615        Ok(old_child.clone())
616    }
617
618    pub fn remove_child(&self, child: &DomNode) -> bool {
619        let parent_uid = self.uid();
620        let child_uid = child.uid();
621        let mut inner = self.inner.borrow_mut();
622        let before_len = inner.children.len();
623        if let Some(pos) = inner
624            .children
625            .iter()
626            .position(|c| Rc::ptr_eq(&c.inner, &child.inner))
627        {
628            inner.children.remove(pos);
629            child.inner.borrow_mut().parent = None;
630        }
631        let removed = inner.children.len() < before_len;
632        drop(inner);
633        if removed {
634            self.emit_mutation(
635                DomMutationType::ChildRemoved {
636                    parent_uid,
637                    child_uid,
638                },
639                parent_uid,
640            );
641        }
642        removed
643    }
644
645    pub fn remove(&self) -> bool {
646        if let Some(parent) = self.parent_node() {
647            parent.remove_child(self)
648        } else {
649            false
650        }
651    }
652
653    pub fn replace_with(&self, new_node: DomNode) -> bool {
654        if let Some(parent) = self.parent_node() {
655            parent.replace_child(new_node, self).is_ok()
656        } else {
657            false
658        }
659    }
660
661    pub fn contains(&self, other: &DomNode) -> bool {
662        if Rc::ptr_eq(&self.inner, &other.inner) {
663            return true;
664        }
665        for child in self.children() {
666            if child.contains(other) {
667                return true;
668            }
669        }
670        false
671    }
672
673    pub fn clone_node(&self, deep: bool) -> DomNode {
674        let inner = self.inner.borrow();
675        let cloned_inner = DomNodeInner {
676            uid: NEXT_DOM_UID.fetch_add(1, Ordering::Relaxed),
677            node_type: inner.node_type.clone(),
678            parent: None,
679            children: if deep {
680                inner.children.iter().map(|c| c.clone_node(true)).collect()
681            } else {
682                Vec::new()
683            },
684            event_listeners: HashMap::new(),
685            mutation_sink: None,
686        };
687        let node = DomNode {
688            inner: Rc::new(RefCell::new(cloned_inner)),
689        };
690        if deep {
691            for child in &node.inner.borrow().children {
692                child.inner.borrow_mut().parent = Some(Rc::downgrade(&node.inner));
693            }
694        }
695        node
696    }
697
698    pub fn children(&self) -> Vec<DomNode> {
699        self.inner.borrow().children.clone()
700    }
701
702    pub fn get_element_by_id(&self, id: &str) -> Option<DomNode> {
703        let id_lower = id.to_ascii_lowercase();
704        if let Some(this_id) = self.id() {
705            if this_id.to_ascii_lowercase() == id_lower {
706                return Some(self.clone());
707            }
708        }
709        let children = self.children();
710        for child in children {
711            if let Some(found) = child.get_element_by_id(id) {
712                return Some(found);
713            }
714        }
715        None
716    }
717
718    pub fn query_selector(&self, selector: &str) -> Option<DomNode> {
719        let all = self.query_selector_all(selector);
720        all.into_iter().next()
721    }
722
723    pub fn query_selector_all(&self, selector: &str) -> Vec<DomNode> {
724        let mut results = Vec::new();
725        self.collect_matching(selector.trim(), &mut results);
726        results
727    }
728
729    fn collect_matching(&self, selector: &str, results: &mut Vec<DomNode>) {
730        if self.matches_simple_selector(selector) {
731            results.push(self.clone());
732        }
733        for child in self.children() {
734            child.collect_matching(selector, results);
735        }
736    }
737
738    fn matches_simple_selector(&self, selector: &str) -> bool {
739        if selector.is_empty() {
740            return false;
741        }
742        if let Some(id) = selector.strip_prefix('#') {
743            return self.id().map(|v| v == id).unwrap_or(false);
744        }
745        if let Some(class) = selector.strip_prefix('.') {
746            return self.class_name().split_whitespace().any(|c| c == class);
747        }
748        if let Some(tag) = self.tag_name() {
749            if tag.eq_ignore_ascii_case(selector) {
750                return true;
751            }
752        }
753        false
754    }
755
756    pub fn add_event_listener(&self, event: &str, callback: JsValue) {
757        let mut inner = self.inner.borrow_mut();
758        inner
759            .event_listeners
760            .entry(event.to_ascii_lowercase())
761            .or_default()
762            .push(callback);
763    }
764
765    pub fn dispatch_event(&self, event: &str, engine: &mut JsEngine) {
766        self.dispatch_event_with_args(event, vec![], engine);
767    }
768
769    pub fn dispatch_event_with_args(&self, event: &str, args: Vec<JsValue>, engine: &mut JsEngine) {
770        let attr_name = format!("on{}", event.to_ascii_lowercase());
771        let inline_code = {
772            let inner = self.inner.borrow();
773            match &inner.node_type {
774                DomNodeType::Element { attributes, .. } => attributes.get(&attr_name).cloned(),
775                _ => None,
776            }
777        };
778
779        if let Some(code) = inline_code {
780            let this_val = engine.dom_node_to_js(self);
781            engine.current_scope.borrow_mut().declare("this", this_val);
782            if let Some(ev_val) = args.first() {
783                engine
784                    .current_scope
785                    .borrow_mut()
786                    .declare("event", ev_val.clone());
787            }
788            let _ = engine.eval(&code);
789        }
790
791        let listeners = {
792            let inner = self.inner.borrow();
793            inner
794                .event_listeners
795                .get(&event.to_ascii_lowercase())
796                .cloned()
797                .unwrap_or_default()
798        };
799
800        for listener in listeners {
801            let _ = engine.call_value(&listener, args.clone());
802        }
803    }
804
805    pub fn dispatch_event_with_bubbling(
806        &self,
807        event: &str,
808        event_obj: JsValue,
809        engine: &mut JsEngine,
810    ) {
811        let mut current = Some(self.clone());
812        while let Some(node) = current {
813            node.dispatch_event_with_args(event, vec![event_obj.clone()], engine);
814
815            let propagation_stopped =
816                event_obj.get_prop("__propagation_stopped__") == Some(JsValue::Bool(true));
817            if propagation_stopped {
818                break;
819            }
820
821            current = node.parent_element();
822        }
823    }
824}
825
826fn is_void_element(tag: &str) -> bool {
827    matches!(
828        tag.to_ascii_lowercase().as_str(),
829        "area"
830            | "base"
831            | "br"
832            | "col"
833            | "embed"
834            | "hr"
835            | "img"
836            | "input"
837            | "link"
838            | "meta"
839            | "param"
840            | "source"
841            | "track"
842            | "wbr"
843    )
844}
845
846fn find_matching_close_pos(html: &str, tag_name: &str) -> Option<usize> {
847    let open_prefix = format!("<{}", tag_name);
848    let close_tag = format!("</{}>", tag_name);
849    let bytes = html.as_bytes();
850    let mut depth = 1usize;
851    let mut pos = 0;
852
853    while pos < bytes.len() {
854        if bytes[pos] == b'<' {
855            let rem = &html[pos..];
856            if rem.to_ascii_lowercase().starts_with(&close_tag) {
857                depth -= 1;
858                if depth == 0 {
859                    return Some(pos);
860                }
861                pos += close_tag.len();
862                continue;
863            } else if rem.to_ascii_lowercase().starts_with(&open_prefix) {
864                let next_char = rem[open_prefix.len()..].chars().next();
865                if matches!(
866                    next_char,
867                    Some(' ') | Some('\t') | Some('\n') | Some('\r') | Some('>') | Some('/')
868                ) {
869                    if let Some(end_idx) = rem.find('>') {
870                        let tag_str = &rem[..end_idx + 1];
871                        if !tag_str.ends_with("/>") && !is_void_element(tag_name) {
872                            depth += 1;
873                        }
874                        pos += end_idx + 1;
875                        continue;
876                    }
877                }
878            }
879        }
880        pos += 1;
881    }
882    None
883}
884
885/// Parses a basic HTML snippet into a vector of DOM nodes.
886pub fn parse_html_fragment(html: &str) -> Vec<DomNode> {
887    let mut nodes = Vec::new();
888    let bytes = html.as_bytes();
889    let mut i = 0;
890
891    while i < bytes.len() {
892        if bytes[i] == b'<' {
893            if i + 1 < bytes.len() && bytes[i + 1] == b'/' {
894                // Unexpected closing tag, advance past '>'
895                while i < bytes.len() && bytes[i] != b'>' {
896                    i += 1;
897                }
898                if i < bytes.len() {
899                    i += 1;
900                }
901                continue;
902            }
903
904            // Find tag end
905            let start_tag = i + 1;
906            while i < bytes.len() && bytes[i] != b'>' {
907                i += 1;
908            }
909            if i >= bytes.len() {
910                break;
911            }
912            let tag_content = std::str::from_utf8(&bytes[start_tag..i]).unwrap_or("");
913            i += 1; // skip '>'
914
915            let is_self_closing = tag_content.ends_with('/');
916            let tag_str = tag_content.trim_end_matches('/').trim();
917
918            let mut parts = tag_str.split_whitespace();
919            let tag_name = parts.next().unwrap_or("div").to_ascii_lowercase();
920
921            let mut attributes = HashMap::new();
922            for part in parts {
923                if let Some((k, v)) = part.split_once('=') {
924                    let val_clean = v.trim_matches('"').trim_matches('\'');
925                    attributes.insert(k.to_ascii_lowercase(), val_clean.to_string());
926                } else if !part.is_empty() {
927                    attributes.insert(part.to_ascii_lowercase(), String::new());
928                }
929            }
930
931            let elem = DomNode::element(&tag_name, attributes);
932
933            if !is_self_closing && !is_void_element(&tag_name) {
934                // Find matching closing tag `</tag_name>`
935                let close_tag = format!("</{}>", tag_name);
936                let remaining = &html[i..];
937                if let Some(close_pos) = find_matching_close_pos(remaining, &tag_name) {
938                    let inner_str = &remaining[..close_pos];
939                    let children = parse_html_fragment(inner_str);
940                    for child in &children {
941                        child.inner.borrow_mut().parent = Some(Rc::downgrade(&elem.inner));
942                    }
943                    elem.inner.borrow_mut().children = children;
944                    i += close_pos + close_tag.len();
945                }
946            }
947
948            nodes.push(elem);
949        } else {
950            // Text node
951            let text_start = i;
952            while i < bytes.len() && bytes[i] != b'<' {
953                i += 1;
954            }
955            let text_str = std::str::from_utf8(&bytes[text_start..i]).unwrap_or("");
956            if !text_str.is_empty() {
957                nodes.push(DomNode::text(text_str));
958            }
959        }
960    }
961
962    nodes
963}
964
965// ============================================================================
966// 2. Document Model
967// ============================================================================
968
969/// W3C-compliant document node container holding root, head, body, and DOM elements.
970#[derive(Clone)]
971pub struct Document {
972    pub html: DomNode,
973    pub head: DomNode,
974    pub body: DomNode,
975    pub title: Rc<RefCell<String>>,
976    pub mutated: Rc<RefCell<bool>>,
977    pub mutation_sink: Rc<RefCell<MutationSink>>,
978}
979
980impl Default for Document {
981    fn default() -> Self {
982        Self::new()
983    }
984}
985
986impl Document {
987    pub fn new() -> Self {
988        let sink = Rc::new(RefCell::new(MutationSink::new()));
989        let html = DomNode::element("html", HashMap::new());
990        let head = DomNode::element("head", HashMap::new());
991        let body = DomNode::element("body", HashMap::new());
992
993        html.set_mutation_sink_recursive(&sink);
994        head.set_mutation_sink_recursive(&sink);
995        body.set_mutation_sink_recursive(&sink);
996
997        html.append_child(head.clone());
998        html.append_child(body.clone());
999
1000        // Clear initial tree creation events from queue so initial document tree starts clean
1001        sink.borrow_mut().queue.clear();
1002        sink.borrow_mut().mutated = false;
1003
1004        Self {
1005            html,
1006            head,
1007            body,
1008            title: Rc::new(RefCell::new("Strata Document".to_string())),
1009            mutated: Rc::new(RefCell::new(false)),
1010            mutation_sink: sink,
1011        }
1012    }
1013
1014    pub fn mark_mutated(&self) {
1015        *self.mutated.borrow_mut() = true;
1016        self.mutation_sink.borrow_mut().mutated = true;
1017    }
1018
1019    pub fn has_mutated(&self) -> bool {
1020        *self.mutated.borrow() || self.mutation_sink.borrow().mutated
1021    }
1022
1023    pub fn clear_mutated(&self) {
1024        *self.mutated.borrow_mut() = false;
1025        let mut sink = self.mutation_sink.borrow_mut();
1026        sink.mutated = false;
1027        sink.queue.clear();
1028    }
1029
1030    pub fn add_mutation_listener<F>(&self, listener: F)
1031    where
1032        F: FnMut(&DomMutationRecord) + 'static,
1033    {
1034        self.mutation_sink
1035            .borrow_mut()
1036            .listeners
1037            .push(Rc::new(RefCell::new(listener)));
1038    }
1039
1040    pub fn set_mutation_channel(&self, sender: std::sync::mpsc::Sender<DomMutationRecord>) {
1041        self.mutation_sink.borrow_mut().sender = Some(sender);
1042    }
1043
1044    pub fn drain_mutations(&self) -> Vec<DomMutationRecord> {
1045        let mut sink = self.mutation_sink.borrow_mut();
1046        sink.mutated = false;
1047        *self.mutated.borrow_mut() = false;
1048        std::mem::take(&mut sink.queue)
1049    }
1050
1051    pub fn pending_mutations(&self) -> Vec<DomMutationRecord> {
1052        self.mutation_sink.borrow().queue.clone()
1053    }
1054
1055    pub fn from_html(html_str: &str) -> Self {
1056        let doc = Self::new();
1057        let parsed = parse_html_fragment(html_str);
1058
1059        // Check if root has <html> or <body>
1060        for node in parsed {
1061            if let Some(tag) = node.tag_name() {
1062                match tag.as_str() {
1063                    "HTML" => {
1064                        for child in node.children() {
1065                            if let Some(c_tag) = child.tag_name() {
1066                                if c_tag == "HEAD" {
1067                                    for c in child.children() {
1068                                        doc.head.append_child(c);
1069                                    }
1070                                } else if c_tag == "BODY" {
1071                                    for c in child.children() {
1072                                        doc.body.append_child(c);
1073                                    }
1074                                }
1075                            }
1076                        }
1077                    }
1078                    "HEAD" => {
1079                        for c in node.children() {
1080                            doc.head.append_child(c);
1081                        }
1082                    }
1083                    "BODY" => {
1084                        for c in node.children() {
1085                            doc.body.append_child(c);
1086                        }
1087                    }
1088                    _ => {
1089                        doc.body.append_child(node);
1090                    }
1091                }
1092            } else {
1093                doc.body.append_child(node);
1094            }
1095        }
1096
1097        doc.clear_mutated();
1098        doc
1099    }
1100
1101    pub fn create_element(&self, tag: &str) -> DomNode {
1102        let node = DomNode::element(tag, HashMap::new());
1103        node.set_mutation_sink_recursive(&self.mutation_sink);
1104        node
1105    }
1106
1107    pub fn create_text_node(&self, text: &str) -> DomNode {
1108        let node = DomNode::text(text);
1109        node.set_mutation_sink_recursive(&self.mutation_sink);
1110        node
1111    }
1112
1113    pub fn create_comment(&self, comment: &str) -> DomNode {
1114        let node = DomNode::comment(comment);
1115        node.set_mutation_sink_recursive(&self.mutation_sink);
1116        node
1117    }
1118
1119    pub fn get_element_by_id(&self, id: &str) -> Option<DomNode> {
1120        self.html.get_element_by_id(id)
1121    }
1122
1123    pub fn get_element_by_uid(&self, uid: u64) -> Option<DomNode> {
1124        self.find_by_uid(&self.html, uid)
1125    }
1126
1127    fn find_by_uid(&self, current: &DomNode, target_uid: u64) -> Option<DomNode> {
1128        if current.uid() == target_uid {
1129            return Some(current.clone());
1130        }
1131        for child in current.children() {
1132            if let Some(found) = self.find_by_uid(&child, target_uid) {
1133                return Some(found);
1134            }
1135        }
1136        None
1137    }
1138
1139    pub fn query_selector(&self, selector: &str) -> Option<DomNode> {
1140        self.html.query_selector(selector)
1141    }
1142
1143    pub fn query_selector_all(&self, selector: &str) -> Vec<DomNode> {
1144        self.html.query_selector_all(selector)
1145    }
1146
1147    pub fn to_html(&self) -> String {
1148        self.html.outer_html()
1149    }
1150}