1use alloc::collections::BTreeMap;
13use alloc::collections::BTreeSet;
14use alloc::format;
15use alloc::string::String;
16use alloc::string::ToString;
17use alloc::vec::Vec;
18
19use crate::os_lib::ecma::value::{HostRef, Obj, ObjKind, ObjRef, Value, HOST_CLASS_BY_ID};
20use crate::os_lib::dom::{Node, NodeType};
21use crate::os_lib::viewport::intersection_observer::RootMargin;
22use crate::os_lib::viewport::resize_observer::ResizeObserverBoxOptions;
23
24pub struct DomNode {
26 pub tag: String,
28 pub is_text: bool,
29 pub id: String,
30 pub classes: Vec<String>,
31 pub style: BTreeMap<String, String>,
33 pub attrs: BTreeMap<String, String>,
35 pub text_override: Option<String>,
37 pub initial_text: String,
39 pub parent: Option<usize>,
40 pub children: Vec<usize>,
41 pub classes_dirty: bool,
43 pub style_dirty: bool,
45}
46
47#[derive(Clone)]
49pub struct ObservedTarget {
50 pub target: Value,
51 pub target_idx: usize,
52 pub prev_ratio: Option<f64>,
53 pub prev_is_intersecting: bool,
54}
55
56#[derive(Clone)]
58pub struct IntersectionObserverReg {
59 pub id: u32,
60 pub callback: Value,
61 pub root: Value,
62 pub root_margin: RootMargin,
63 pub thresholds: Vec<f64>,
64 pub targets: Vec<ObservedTarget>,
65 pub queued_records: Vec<Value>,
66}
67
68#[derive(Clone)]
70pub struct ObservedResizeTarget {
71 pub target: Value,
72 pub target_idx: usize,
73 pub box_option: ResizeObserverBoxOptions,
74 pub last_inline_size: f64,
75 pub last_block_size: f64,
76}
77
78#[derive(Clone)]
80pub struct ResizeObserverReg {
81 pub id: u32,
82 pub callback: Value,
83 pub targets: Vec<ObservedResizeTarget>,
84}
85
86#[derive(Clone)]
88pub struct MutObsReg {
89 pub id: u32,
90 pub target_idx: usize,
91 pub child_list: bool,
92 pub attributes: bool,
93 pub subtree: bool,
94 pub callback: Value,
95 pub observer: Value,
96 pub attribute_old_value: bool,
99 pub attribute_filter: Option<Vec<String>>,
102 pub character_data: bool,
109 pub character_data_old_value: bool,
113 pub transient_source: Option<usize>,
115}
116
117pub struct MutRec {
119 pub type_: &'static str, pub target_idx: usize,
121 pub added: Vec<usize>,
122 pub removed: Vec<usize>,
123 pub prev_sibling: Option<usize>,
124 pub next_sibling: Option<usize>,
125 pub attribute_name: Option<String>,
126 pub attribute_namespace: Option<String>,
127 pub old_value: Option<String>,
129}
130
131pub struct Listener {
133 pub node: usize,
134 pub event: String,
135 pub func: Value,
136 pub capture: bool,
138 pub once: bool,
140 pub passive: bool,
142 pub id: u64,
144 pub signal: Option<Value>,
151}
152
153pub fn is_signal_aborted(signal: &Value) -> bool {
155 matches!(signal, Value::Object(o) if matches!(o.borrow().props.get("aborted"), Some(Value::Bool(true))))
156}
157
158fn is_listener_aborted(l: &Listener) -> bool {
159 l.signal.as_ref().is_some_and(is_signal_aborted)
160}
161
162pub const MAIN_DOC: usize = usize::MAX - 1;
164
165#[derive(Clone)]
167pub struct RangeRec {
168 pub obj: alloc::rc::Weak<core::cell::RefCell<crate::os_lib::ecma::value::Obj>>,
169 pub sc: usize,
170 pub so: usize,
171 pub ec: usize,
172 pub eo: usize,
173}
174
175#[derive(Clone)]
177pub struct NiRec {
178 pub obj: alloc::rc::Weak<core::cell::RefCell<crate::os_lib::ecma::value::Obj>>,
179 pub root: usize,
180 pub reference: usize,
181 pub before: bool,
182 pub in_flight: Option<(usize, bool)>,
183}
184
185pub struct DomBridge {
187 pub nodes: Vec<DomNode>,
188 pub extra_docs: usize,
191 pub attr_nodes: BTreeMap<(usize, String), usize>,
193 pub has_attr_nodes: bool,
195 pub attr_order: BTreeMap<usize, Vec<String>>,
198 pub ns_attrs: BTreeMap<usize, Vec<(String, String, String)>>,
201 pub attr_ns_order: BTreeMap<usize, Vec<(Option<String>, String)>>,
203 pub main_doctype: Option<usize>,
206 pub ranges: BTreeMap<u32, RangeRec>,
208 pub suppress_range_hook: bool,
210 pub next_range_id: u32,
211 pub node_iters: BTreeMap<u32, NiRec>,
213 pub next_ni_id: u32,
214 pub html_collections: Vec<HtmlCollectionKind>,
216 pub html_collection_expandos: BTreeMap<usize, BTreeMap<String, Value>>,
218 pub static_node_lists: Vec<Vec<usize>>,
220 pub has_shells: bool,
222 pub node_doc: BTreeMap<usize, usize>,
224 pub template_owner_docs: BTreeMap<Option<usize>, usize>,
226 pub quirks_mode: bool,
228 pub doc_impls: BTreeMap<usize, Value>,
230 pub listeners: Vec<Listener>,
231 pub dirty: bool,
233 pub id_dirty: bool,
235 pub structural_dirty: bool,
237 pub dirty_causes: BTreeMap<String, u32>,
239 pub pending_style_updates: Vec<(usize, String, String)>,
241 pub pending_text_updates: Vec<(usize, usize, String)>,
243 pub js_created_scripts: alloc::collections::BTreeSet<usize>,
245 pub pending_dynamic_scripts: Vec<usize>,
249 pub js_created_links: alloc::collections::BTreeSet<usize>,
251 pub pending_dynamic_links: Vec<usize>,
256 pub pending_post_connection: Vec<usize>,
260 pub frames_pending_setup: alloc::collections::BTreeSet<usize>,
262 pub frames_dirty: bool,
264 pub frames_check: bool,
266 pub expandos: BTreeMap<usize, BTreeMap<String, Value>>,
271 pub node_accessors: BTreeMap<usize, BTreeMap<String, (Option<Value>, Option<Value>)>>,
274 pub node_protos: BTreeMap<usize, crate::os_lib::ecma::value::ObjRef>,
277 pub ce_queue: Vec<CeEvent>,
280 pub built: bool,
282 pub rects: BTreeMap<usize, (i32, i32, i32, i32)>,
285 pub measured: BTreeMap<usize, (i32, i32)>,
288 pub border_widths: BTreeMap<usize, (i32, i32, i32, i32)>,
290 pub computed_styles: BTreeMap<usize, alloc::rc::Rc<BTreeMap<String, String>>>,
294 pub scroll_tops: BTreeMap<usize, i32>,
297 pub scroll_lefts: BTreeMap<usize, i32>,
300 pub scroll_heights: BTreeMap<usize, i32>,
303 pub scroll_widths: BTreeMap<usize, i32>,
306 pub next_listener_id: u64,
308 pub mut_observers: Vec<MutObsReg>,
310 pub mut_records: Vec<(u32, MutRec)>,
312 pub next_mut_obs_id: u32,
314 pub mut_microtask_pending: bool,
316 pub io_observers: Vec<IntersectionObserverReg>,
318 pub next_io_obs_id: u32,
320 pub ro_observers: Vec<ResizeObserverReg>,
322 pub next_ro_obs_id: u32,
324 pub pointer_captures: BTreeSet<(usize, i32)>,
331 pub focused_idx: Option<usize>,
340 pub pending_scroll_abs_y: Option<i32>,
350 pub pending_scroll_by_y: Option<i32>,
353 pub on_handlers: BTreeMap<(usize, String), Value>,
362 pub selection: Option<Value>,
364 pub custom_elements: crate::os_lib::custom_elements::CustomElementRegistry,
366 pub shadow_tree: crate::os_lib::shadow_dom::ShadowTreeRegistry,
368 pub pending_parent_messages: Vec<(Value, String)>,
370 pub pending_child_messages: Vec<(String, Value, String)>,
372 pub iframe_content_windows: BTreeMap<usize, alloc::rc::Rc<core::cell::RefCell<crate::os_lib::ecma::value::Obj>>>,
374 pub iframe_docs: BTreeMap<usize, usize>,
376 pub iframe_doc_to_elem: BTreeMap<usize, usize>,
378 pub builtin_global_names: Vec<String>,
380 pub css_referenced_attrs: Option<BTreeSet<String>>,
384}
385
386impl Default for DomBridge {
387 fn default() -> Self {
388 Self::new()
389 }
390}
391
392#[derive(Default)]
398pub struct ValidityFlags {
399 pub value_missing: bool,
400 pub type_mismatch: bool,
401 pub pattern_mismatch: bool,
402 pub too_long: bool,
403 pub too_short: bool,
404 pub range_overflow: bool,
405 pub range_underflow: bool,
406 pub step_mismatch: bool,
407 pub bad_input: bool,
408 pub custom_error: bool,
409}
410impl ValidityFlags {
411 pub fn valid(&self) -> bool {
412 !(self.value_missing
413 || self.type_mismatch
414 || self.pattern_mismatch
415 || self.too_long
416 || self.too_short
417 || self.range_overflow
418 || self.range_underflow
419 || self.step_mismatch
420 || self.bad_input
421 || self.custom_error)
422 }
423}
424
425use crate::os_lib::dom_selector::*;
428
429pub fn parse_selector_groups(selector: &str) -> Vec<Vec<SelStep>> {
431 split_top_level_commas(selector)
432 .iter()
433 .map(|part| build_steps(&tokenize_selector_group(part.trim())))
434 .filter(|steps| !steps.is_empty())
435 .collect()
436}
437
438impl DomBridge {
439 pub fn new() -> Self {
440 DomBridge {
441 nodes: Vec::new(),
442 extra_docs: 0,
443 attr_nodes: BTreeMap::new(),
444 has_attr_nodes: false,
445 attr_order: BTreeMap::new(),
446 ns_attrs: BTreeMap::new(),
447 attr_ns_order: BTreeMap::new(),
448 main_doctype: None,
449 ranges: BTreeMap::new(),
450 suppress_range_hook: false,
451 next_range_id: 1,
452 node_iters: BTreeMap::new(),
453 next_ni_id: 1,
454 html_collections: Vec::new(),
455 html_collection_expandos: BTreeMap::new(),
456 static_node_lists: Vec::new(),
457 has_shells: false,
458 node_doc: BTreeMap::new(),
459 template_owner_docs: BTreeMap::new(),
460 quirks_mode: false,
461 doc_impls: BTreeMap::new(),
462 listeners: Vec::new(),
463 dirty: false,
464 id_dirty: true,
465 structural_dirty: false,
466 dirty_causes: BTreeMap::new(),
467 pending_style_updates: Vec::new(),
468 pending_text_updates: Vec::new(),
469 js_created_scripts: alloc::collections::BTreeSet::new(),
470 pending_dynamic_scripts: Vec::new(),
471 js_created_links: alloc::collections::BTreeSet::new(),
472 pending_dynamic_links: Vec::new(),
473 pending_post_connection: Vec::new(),
474 frames_pending_setup: alloc::collections::BTreeSet::new(),
475 frames_dirty: false,
476 frames_check: false,
477 expandos: BTreeMap::new(),
478 node_accessors: BTreeMap::new(),
479 node_protos: BTreeMap::new(),
480 ce_queue: Vec::new(),
481 built: false,
482 rects: BTreeMap::new(),
483 measured: BTreeMap::new(),
484 border_widths: BTreeMap::new(),
485 computed_styles: BTreeMap::new(),
486 scroll_tops: BTreeMap::new(),
487 scroll_lefts: BTreeMap::new(),
488 scroll_heights: BTreeMap::new(),
489 scroll_widths: BTreeMap::new(),
490 next_listener_id: 1,
491 mut_observers: Vec::new(),
492 mut_records: Vec::new(),
493 next_mut_obs_id: 1,
494 mut_microtask_pending: false,
495 io_observers: Vec::new(),
496 next_io_obs_id: 1,
497 ro_observers: Vec::new(),
498 next_ro_obs_id: 1,
499 pointer_captures: BTreeSet::new(),
500 focused_idx: None,
501 pending_scroll_abs_y: None,
502 pending_scroll_by_y: None,
503 on_handlers: BTreeMap::new(),
504 selection: None,
505 custom_elements: crate::os_lib::custom_elements::CustomElementRegistry::new(),
506 shadow_tree: crate::os_lib::shadow_dom::ShadowTreeRegistry::new(),
507 pending_parent_messages: Vec::new(),
508 pending_child_messages: Vec::new(),
509 iframe_content_windows: BTreeMap::new(),
510 iframe_docs: BTreeMap::new(),
511 iframe_doc_to_elem: BTreeMap::new(),
512 builtin_global_names: Vec::new(),
513 css_referenced_attrs: None,
514 }
515 }
516
517 pub fn ensure_default_document(&mut self) {
519 if self.nodes.is_empty() {
520 self.nodes.push(DomNode {
521 tag: String::from("html"),
522 is_text: false,
523 id: String::new(),
524 classes: Vec::new(),
525 style: BTreeMap::new(),
526 attrs: BTreeMap::new(),
527 text_override: None,
528 initial_text: String::new(),
529 parent: None,
530 children: alloc::vec![1, 2],
531 classes_dirty: false,
532 style_dirty: false,
533 });
534 self.nodes.push(DomNode {
535 tag: String::from("head"),
536 is_text: false,
537 id: String::new(),
538 classes: Vec::new(),
539 style: BTreeMap::new(),
540 attrs: BTreeMap::new(),
541 text_override: None,
542 initial_text: String::new(),
543 parent: Some(0),
544 children: Vec::new(),
545 classes_dirty: false,
546 style_dirty: false,
547 });
548 self.nodes.push(DomNode {
549 tag: String::from("body"),
550 is_text: false,
551 id: String::new(),
552 classes: Vec::new(),
553 style: BTreeMap::new(),
554 attrs: BTreeMap::new(),
555 text_override: None,
556 initial_text: String::new(),
557 parent: Some(0),
558 children: Vec::new(),
559 classes_dirty: false,
560 style_dirty: false,
561 });
562 self.built = true;
563 }
564 }
565
566 pub fn set_on_handler(&mut self, node: usize, key: &str, val: Value) {
568 self.on_handlers.insert((node, key.to_string()), val);
569 }
570 pub fn get_on_handler(&self, node: usize, key: &str) -> Option<Value> {
572 self.on_handlers.get(&(node, key.to_string())).cloned()
573 }
574
575 pub fn set_pointer_capture(&mut self, idx: usize, pointer_id: i32) {
577 self.pointer_captures.insert((idx, pointer_id));
578 }
579 pub fn release_pointer_capture(&mut self, idx: usize, pointer_id: i32) {
581 self.pointer_captures.remove(&(idx, pointer_id));
582 }
583 pub fn has_pointer_capture(&self, idx: usize, pointer_id: i32) -> bool {
585 self.pointer_captures.contains(&(idx, pointer_id))
586 }
587
588 fn has_child_list_observer(&self, parent_idx: usize) -> bool {
590 self.mut_observers.iter().any(|obs| {
591 obs.child_list
592 && (obs.target_idx == parent_idx
593 || (obs.subtree && self.is_ancestor_of(obs.target_idx, parent_idx)))
594 })
595 }
596
597 fn notify_child_list(&mut self, parent_idx: usize, added: Vec<usize>, removed: Vec<usize>) {
599 self.notify_child_list_sib(parent_idx, added, removed, None, None);
600 }
601
602 fn notify_child_list_sib(
604 &mut self,
605 parent_idx: usize,
606 added: Vec<usize>,
607 removed: Vec<usize>,
608 prev_sibling: Option<usize>,
609 next_sibling: Option<usize>,
610 ) {
611 self.id_dirty = true;
612 if !removed.is_empty() && !self.iframe_docs.is_empty() {
613 self.frames_check = true;
614 }
615 if !self.custom_elements.is_empty() {
616 for &a in &added {
617 self.ce_queue.push(CeEvent::Inserted(a));
618 }
619 if self.is_attached(parent_idx) {
620 for &r in &removed {
621 self.ce_queue.push(CeEvent::Removed(r));
622 }
623 }
624 }
625 let mut seen_ids: Vec<u32> = Vec::new();
626 for obs in &self.mut_observers {
627 if seen_ids.contains(&obs.id) {
628 continue;
629 }
630 let watches = obs.child_list
631 && (obs.target_idx == parent_idx
632 || (obs.subtree && self.is_ancestor_of(obs.target_idx, parent_idx)));
633 if watches {
634 seen_ids.push(obs.id);
635 self.mut_microtask_pending = true;
636 self.mut_records.push((
637 obs.id,
638 MutRec {
639 type_: "childList",
640 target_idx: parent_idx,
641 added: added.clone(),
642 removed: removed.clone(),
643 prev_sibling,
644 next_sibling,
645 attribute_name: None,
646 attribute_namespace: None,
647 old_value: None,
648 },
649 ));
650 }
651 }
652 if !removed.is_empty() && !self.mut_observers.is_empty() {
654 let mut transients: Vec<MutObsReg> = Vec::new();
655 for obs in &self.mut_observers {
656 if !obs.subtree {
657 continue;
658 }
659 if obs.target_idx == parent_idx || self.is_ancestor_of(obs.target_idx, parent_idx) {
660 let src = obs.transient_source.unwrap_or(obs.target_idx);
661 for &r in &removed {
662 let exists = self.mut_observers.iter().any(|o| o.id == obs.id && o.target_idx == r)
663 || transients.iter().any(|o| o.id == obs.id && o.target_idx == r);
664 if !exists {
665 let mut t = obs.clone();
666 t.target_idx = r;
667 t.transient_source = Some(src);
668 transients.push(t);
669 }
670 }
671 }
672 }
673 if !transients.is_empty() {
674 self.mut_microtask_pending = true;
675 self.mut_observers.extend(transients);
676 }
677 }
678 }
679
680 fn siblings_of_child(&self, parent: usize, child: usize) -> (Option<usize>, Option<usize>) {
682 let Some(kids) = self.nodes.get(parent).map(|n| &n.children) else {
683 return (None, None);
684 };
685 let Some(pos) = kids.iter().position(|&c| c == child) else {
686 return (None, None);
687 };
688 let prev = if pos > 0 { kids.get(pos - 1).copied() } else { None };
689 let next = kids.get(pos + 1).copied();
690 (prev, next)
691 }
692
693 fn detach_with_notify(&mut self, idx: usize) {
695 if idx >= self.nodes.len() {
696 return;
697 }
698 let old = self.nodes[idx].parent.map(|p| (p, self.siblings_of_child(p, idx)));
699 self.detach(idx);
700 if let Some((old_p, (prev, next))) = old {
701 self.notify_child_list_sib(old_p, Vec::new(), alloc::vec![idx], prev, next);
702 }
703 }
704
705 fn notify_attribute(&mut self, idx: usize, attr_name: &str, old_value: Option<&str>) {
711 self.notify_attribute_ns(idx, attr_name, None, old_value);
712 }
713
714 fn notify_attribute_ns(
715 &mut self,
716 idx: usize,
717 attr_name: &str,
718 attr_ns: Option<&str>,
719 old_value: Option<&str>,
720 ) {
721 if attr_ns.is_none() && self.node_protos.contains_key(&idx) && !attr_name.starts_with('_') {
723 let observed = self
724 .nodes
725 .get(idx)
726 .and_then(|n| self.custom_elements.get(&n.tag.to_lowercase()))
727 .is_some_and(|d| d.observes_attribute(attr_name));
728 if observed {
729 let new_value = self.get_attr(idx, attr_name);
730 self.ce_queue.push(CeEvent::Attr(
731 idx,
732 attr_name.to_string(),
733 old_value.map(String::from),
734 new_value,
735 ));
736 }
737 }
738 let mut matched_obs: Vec<(u32, bool)> = Vec::new();
741 for obs in &self.mut_observers {
742 let watches = obs.attributes
743 && (obs.target_idx == idx
744 || (obs.subtree && self.is_ancestor_of(obs.target_idx, idx)))
745 && obs
746 .attribute_filter
747 .as_ref()
748 .is_none_or(|f| f.iter().any(|n| n == attr_name));
749 if watches {
750 if let Some(entry) = matched_obs.iter_mut().find(|(id, _)| *id == obs.id) {
751 entry.1 |= obs.attribute_old_value;
752 } else {
753 matched_obs.push((obs.id, obs.attribute_old_value));
754 }
755 }
756 }
757 for (id, want_old) in matched_obs {
758 self.mut_microtask_pending = true;
759 self.mut_records.push((
760 id,
761 MutRec {
762 type_: "attributes",
763 target_idx: idx,
764 added: Vec::new(),
765 removed: Vec::new(),
766 prev_sibling: None,
767 next_sibling: None,
768 attribute_name: Some(String::from(attr_name)),
769 attribute_namespace: attr_ns.map(String::from),
770 old_value: if want_old {
772 old_value.map(String::from)
773 } else {
774 None
775 },
776 },
777 ));
778 }
779 }
780
781 fn notify_character_data(&mut self, idx: usize, old_value: Option<&str>) {
787 let mut matched_obs: Vec<(u32, bool)> = Vec::new();
788 for obs in &self.mut_observers {
789 let watches = obs.character_data
790 && (obs.target_idx == idx
791 || (obs.subtree && self.is_ancestor_of(obs.target_idx, idx)));
792 if watches {
793 if let Some(entry) = matched_obs.iter_mut().find(|(id, _)| *id == obs.id) {
794 entry.1 |= obs.character_data_old_value;
795 } else {
796 matched_obs.push((obs.id, obs.character_data_old_value));
797 }
798 }
799 }
800 for (id, want_old) in matched_obs {
801 self.mut_microtask_pending = true;
802 self.mut_records.push((
803 id,
804 MutRec {
805 type_: "characterData",
806 target_idx: idx,
807 added: Vec::new(),
808 removed: Vec::new(),
809 prev_sibling: None,
810 next_sibling: None,
811 attribute_name: None,
812 attribute_namespace: None,
813 old_value: if want_old {
814 Some(old_value.unwrap_or("").to_string())
815 } else {
816 None
817 },
818 },
819 ));
820 }
821 }
822
823 pub fn set_rect(&mut self, idx: usize, x: i32, y: i32, w: i32, h: i32) {
825 self.rects.insert(idx, (x, y, w, h));
826 }
827 pub fn get_rect(&self, idx: usize) -> Option<(i32, i32, i32, i32)> {
828 if let Some(r) = self.rects.get(&idx).copied() {
829 return Some(r);
830 }
831 let node = self.nodes.get(idx)?;
833 if node.is_text {
834 return None;
835 }
836 if node.style.get("display").map(|d| d.trim() == "none").unwrap_or(false) {
837 return Some((0, 0, 0, 0));
838 }
839
840 let parse_dim = |val: &str| -> Option<i32> {
841 let v = val.trim();
842 if let Some(px) = v.strip_suffix("px") {
843 px.trim().parse::<f64>().ok().map(|n| n as i32)
844 } else if let Ok(n) = v.parse::<f64>() {
845 Some(n as i32)
846 } else {
847 None
848 }
849 };
850
851 let mut w = node.style.get("width")
852 .and_then(|v| parse_dim(v))
853 .or_else(|| node.attrs.get("width").and_then(|v| parse_dim(v)));
854 let mut h = node.style.get("height")
855 .and_then(|v| parse_dim(v))
856 .or_else(|| node.attrs.get("height").and_then(|v| parse_dim(v)));
857
858 match node.tag.as_str() {
860 "canvas" | "video" => {
861 if w.is_none() { w = Some(300); }
862 if h.is_none() { h = Some(150); }
863 }
864 "audio" => {
865 if w.is_none() { w = Some(300); }
866 if h.is_none() { h = Some(32); }
867 }
868 _ => {}
869 }
870
871 if let (Some(w_val), Some(h_val)) = (w, h) {
872 Some((0, 0, w_val.max(0), h_val.max(0)))
873 } else if let Some(w_val) = w {
874 Some((0, 0, w_val.max(0), 0))
875 } else { h.map(|h_val| (0, 0, 0, h_val.max(0))) }
876 }
877 pub fn note_measured(&mut self, idx: usize) {
879 let (w, h) = self.rects.get(&idx).map(|r| (r.2, r.3)).unwrap_or((0, 0));
880 self.measured.insert(idx, (w, h));
881 }
882 pub fn take_stale_measurements(&mut self) -> bool {
884 let m = core::mem::take(&mut self.measured);
885 m.iter().any(|(i, wh)| self.rects.get(i).map(|r| (r.2, r.3)).unwrap_or((0, 0)) != *wh)
886 }
887 pub fn set_border_widths(&mut self, idx: usize, top: i32, right: i32, bottom: i32, left: i32) {
888 self.border_widths.insert(idx, (top, right, bottom, left));
889 }
890 pub fn get_border_widths(&self, idx: usize) -> (i32, i32, i32, i32) {
891 self.border_widths.get(&idx).copied().unwrap_or((0, 0, 0, 0))
892 }
893 pub fn clear_rects(&mut self) {
894 self.rects.clear();
895 self.border_widths.clear();
896 }
897
898 pub fn set_computed_style(&mut self, idx: usize, prop: &str, val: &str) {
900 alloc::rc::Rc::make_mut(self.computed_styles.entry(idx).or_default())
901 .insert(String::from(prop), String::from(val));
902 }
903 pub fn get_computed(&self, idx: usize, prop: &str) -> String {
905 if prop == "font-size" {
910 return alloc::format!("{}px", self.font_size_px(idx));
911 }
912 let raw = if let Some(v) = self.computed_styles.get(&idx).and_then(|m| m.get(prop)) {
913 v.clone()
914 } else {
915 self.nodes
916 .get(idx)
917 .and_then(|n| n.style.get(prop))
918 .cloned()
919 .unwrap_or_default()
920 };
921 if raw.is_empty() || prop.starts_with("--") {
924 return raw;
925 }
926 let font_px = self.font_size_px(idx) as f32;
927 crate::os_lib::css::serialize_computed_value(prop, &raw, font_px, 0.0).unwrap_or(raw)
928 }
929 fn font_size_px(&self, idx: usize) -> u32 {
932 let mut chain = Vec::new();
933 let mut cur = Some(idx);
934 while let Some(i) = cur {
935 if chain.len() > 256 {
936 break;
937 }
938 chain.push(i);
939 cur = self.nodes.get(i).and_then(|n| n.parent);
940 }
941 let mut px: u32 = 16;
943 for &i in chain.iter().rev() {
944 let computed = self
945 .computed_styles
946 .get(&i)
947 .and_then(|m| m.get("font-size"))
948 .and_then(|v| v.trim().strip_suffix("px").and_then(|n| n.trim().parse::<f32>().ok()));
949 if let Some(v) = computed {
950 px = v as u32;
951 continue;
952 }
953 if let Some(v) = self.nodes.get(i).and_then(|n| n.style.get("font-size")) {
954 if let Some(n) = crate::os_lib::css::units::parse_font_size_with_parent(v, px as f32) {
955 px = n;
956 }
957 }
958 }
959 px
960 }
961
962 pub fn is_in_display_none_subtree(&self, idx: usize) -> bool {
966 if !self.is_attached(idx) {
967 return true;
968 }
969 let mut cur = Some(idx);
970 let mut guard = 0usize;
971 while let Some(i) = cur {
972 let Some(n) = self.nodes.get(i) else { return false };
973 let inline = n.style.get("display").map(|v| v.trim().eq_ignore_ascii_case("none"));
974 let none = match inline {
975 Some(v) => v,
976 None => self
977 .computed_styles
978 .get(&i)
979 .and_then(|m| m.get("display"))
980 .is_some_and(|v| v.trim().eq_ignore_ascii_case("none")),
981 };
982 if none {
983 return true;
984 }
985 cur = n.parent;
986 guard += 1;
987 if guard > 4096 {
988 return false;
989 }
990 }
991 false
992 }
993
994 pub fn clear_computed(&mut self) {
995 self.computed_styles.clear();
996 }
997
998 pub fn clear_dirty(&mut self) {
1000 self.dirty = false;
1001 self.structural_dirty = false;
1002 self.pending_style_updates.clear();
1003 self.pending_text_updates.clear();
1004 }
1005
1006 pub fn record_text_update(&mut self, elem_idx: usize, text_idx: usize, val: &str) {
1009 let is_special_tag = self.nodes.get(elem_idx).is_some_and(|n| {
1010 matches!(
1011 n.tag.as_str(),
1012 "style" | "script" | "title" | "textarea" | "option"
1013 )
1014 });
1015 if val.is_empty() || val.contains('\n') || val.contains('\r') || is_special_tag {
1016 self.mark_structural_dirty_for("textContent");
1017 return;
1018 }
1019 self.dirty = true;
1020 Self::count_relayout_request();
1021 if let Some(pos) = self
1022 .pending_text_updates
1023 .iter()
1024 .position(|(_, t, _)| *t == text_idx)
1025 {
1026 self.pending_text_updates[pos] = (elem_idx, text_idx, val.to_string());
1027 } else {
1028 self.pending_text_updates
1029 .push((elem_idx, text_idx, val.to_string()));
1030 }
1031 }
1032
1033 pub fn mark_structural_dirty(&mut self) {
1035 self.dirty = true;
1036 self.structural_dirty = true;
1037 Self::count_relayout_request();
1038 self.note_dirty_cause("other");
1039 }
1040
1041 pub fn mark_structural_dirty_for(&mut self, cause: &str) {
1043 self.dirty = true;
1044 self.structural_dirty = true;
1045 Self::count_relayout_request();
1046 self.note_dirty_cause(cause);
1047 }
1048
1049 pub fn mark_structural_dirty_attr(&mut self, name: &str) {
1051 self.dirty = true;
1052 self.structural_dirty = true;
1053 Self::count_relayout_request();
1054 let key = alloc::format!("attr:{}", name);
1055 self.note_dirty_cause(&key);
1056 }
1057
1058 fn count_relayout_request() {
1062 crate::os_lib::platform::responsiveness_add(crate::os_lib::platform::Qty::RelayoutRequests, 1);
1063 }
1064
1065 pub fn note_dirty_cause(&mut self, cause: &str) {
1068 if let Some(c) = self.dirty_causes.get_mut(cause) {
1069 *c = c.saturating_add(1);
1070 return;
1071 }
1072 let key = if self.dirty_causes.len() >= 96 { "…" } else { cause };
1073 *self.dirty_causes.entry(String::from(key)).or_insert(0) += 1;
1074 }
1075
1076 pub fn take_dirty_causes(&mut self) -> Vec<(String, u32)> {
1078 let mut v: Vec<(String, u32)> = core::mem::take(&mut self.dirty_causes).into_iter().collect();
1079 v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1080 v
1081 }
1082
1083 pub fn build_from(&mut self, root: &Node) {
1088 self.build_from_ordered(root, None);
1089 }
1090
1091 pub fn build_from_ordered(
1092 &mut self,
1093 root: &Node,
1094 order: Option<&crate::os_lib::dom::treebuilder::AttrOrderNode>,
1095 ) {
1096 self.nodes.clear();
1097 self.extra_docs = 0;
1098 self.attr_nodes.clear();
1099 self.has_attr_nodes = false;
1100 self.attr_order.clear();
1101 self.ns_attrs.clear();
1102 self.attr_ns_order.clear();
1103 self.node_iters.clear();
1104 self.static_node_lists.clear();
1105 self.main_doctype = None;
1106 self.ranges.clear();
1107 self.has_shells = false;
1108 self.node_doc.clear();
1109 self.template_owner_docs.clear();
1110 self.quirks_mode = false;
1111 self.doc_impls.clear();
1112 self.iframe_docs.clear();
1113 self.iframe_doc_to_elem.clear();
1114 self.js_created_scripts.clear();
1115 self.js_created_links.clear();
1116 self.pending_post_connection.clear();
1117 self.frames_pending_setup.clear();
1118 self.frames_dirty = false;
1119 self.frames_check = false;
1120 self.listeners.clear();
1121 self.selection = None;
1122 self.css_referenced_attrs = None;
1123 self.clear_dirty();
1124 self.built = true;
1125 self.nodes = Vec::new();
1130 let total = Self::count_nodes(root);
1131 if self.nodes.try_reserve_exact(total).is_err() {
1132 crate::warn!("[JS] DOM ブリッジ: ノード {} 個の配列を確保できない(ヒープ不足)。ブリッジを組まない", total);
1133 self.built = false;
1134 return;
1135 }
1136 Self::collect(root, None, &mut self.nodes, order, &mut self.attr_order);
1137 if bridge_aborting() {
1138 self.built = false;
1139 return;
1140 }
1141 let n = self.nodes.len();
1147 for i in 0..n {
1148 if bridge_poll() {
1149 self.built = false;
1150 return;
1151 }
1152 self.normalize_foreign_attrs(i);
1153 if !self.nodes[i].is_text && matches!(self.nodes[i].tag.as_str(), "textarea" | "option" | "output" | "title") {
1154 let t = self.collect_text(i);
1155 self.nodes[i].initial_text = t;
1156 }
1157 if !self.nodes[i].is_text && self.nodes[i].tag == "script" && !self.nodes[i].attrs.contains_key("src") {
1160 let (_, _, text) = self.script_source(i);
1161 if text.is_empty() {
1162 self.js_created_scripts.insert(i);
1163 }
1164 }
1165 }
1166 {
1173 let mut last_open_by_name: alloc::collections::BTreeMap<String, usize> = alloc::collections::BTreeMap::new();
1174 for i in 0..n {
1175 let node = &self.nodes[i];
1176 if node.tag == "details" && node.attrs.contains_key("open") {
1177 if let Some(name) = node.attrs.get("name").filter(|s| !s.is_empty()) {
1178 last_open_by_name.insert(name.clone(), i);
1179 }
1180 }
1181 }
1182 for i in 0..n {
1183 let node = &self.nodes[i];
1184 if node.tag == "details" && node.attrs.contains_key("open") {
1185 if let Some(name) = node.attrs.get("name").filter(|s| !s.is_empty()) {
1186 if last_open_by_name.get(name) != Some(&i) {
1187 self.nodes[i].attrs.remove("open");
1188 }
1189 }
1190 }
1191 }
1192 }
1193 }
1194
1195 fn count_nodes(node: &Node) -> usize {
1197 1 + node.children.iter().map(Self::count_nodes).sum::<usize>()
1198 }
1199
1200 fn collect(
1202 node: &Node,
1203 parent: Option<usize>,
1204 out: &mut Vec<DomNode>,
1205 order: Option<&crate::os_lib::dom::treebuilder::AttrOrderNode>,
1206 attr_order: &mut BTreeMap<usize, Vec<String>>,
1207 ) -> usize {
1208 let idx = out.len();
1209 let dn = match &node.node_type {
1210 NodeType::Text(t) => DomNode {
1211 tag: String::new(),
1212 is_text: true,
1213 id: String::new(),
1214 classes: Vec::new(),
1215 style: BTreeMap::new(),
1216 attrs: BTreeMap::new(),
1217 text_override: None,
1218 initial_text: t.clone(),
1219 parent,
1220 children: Vec::new(),
1221 classes_dirty: false,
1222 style_dirty: false,
1223 },
1224 NodeType::Element {
1225 tag_name,
1226 attributes,
1227 classes,
1228 id,
1229 } => {
1230 if let Some(ord) = order {
1231 if !ord.order.is_empty() {
1232 attr_order.insert(idx, ord.order.clone());
1233 }
1234 }
1235 let style =
1236 parse_inline_style(attributes.get("style").map(|s| s.as_str()).unwrap_or(""));
1237 let (attrs, text) = Self::special_node_parts(tag_name, attributes);
1238 let ascii_classes = match attributes.get("class") {
1240 Some(cs) => split_ascii_ws(cs),
1241 None => classes.clone(),
1242 };
1243 DomNode {
1244 tag: tag_name.clone(),
1245 is_text: false,
1246 id: id.clone().unwrap_or_default(),
1247 classes: ascii_classes,
1248 style,
1249 attrs,
1250 text_override: text.clone(),
1251 initial_text: text.unwrap_or_default(),
1252 parent,
1253 children: Vec::new(),
1254 classes_dirty: false,
1255 style_dirty: false,
1256 }
1257 }
1258 };
1259 out.push(dn);
1260 let mut kids = Vec::with_capacity(node.children.len());
1261 for (ci, c) in node.children.iter().enumerate() {
1262 if bridge_poll() {
1264 break;
1265 }
1266 let child_ord = order.and_then(|o| o.children.get(ci));
1267 kids.push(Self::collect(c, Some(idx), out, child_ord, attr_order));
1268 }
1269 out[idx].children = kids;
1270 idx
1271 }
1272
1273 fn special_node_parts(tag: &str, attributes: &BTreeMap<String, String>) -> (BTreeMap<String, String>, Option<String>) {
1276 match tag {
1277 crate::os_lib::dom::COMMENT_TAG => (BTreeMap::new(), Some(attributes.get("data").cloned().unwrap_or_default())),
1278 "#pi" => {
1279 let mut m = BTreeMap::new();
1280 if let Some(t) = attributes.get("_target") {
1281 m.insert(String::from("_target"), t.clone());
1282 }
1283 (m, Some(attributes.get("data").cloned().unwrap_or_default()))
1284 }
1285 crate::os_lib::dom::DOCTYPE_TAG => {
1286 let mut m = BTreeMap::new();
1287 m.insert(String::from("_name"), attributes.get("name").cloned().unwrap_or_default());
1288 m.insert(String::from("_publicId"), attributes.get("publicid").cloned().unwrap_or_default());
1289 m.insert(String::from("_systemId"), attributes.get("systemid").cloned().unwrap_or_default());
1290 (m, None)
1291 }
1292 _ => (attributes.clone(), None),
1293 }
1294 }
1295
1296 pub fn ensure_shells(&mut self) {
1303 if self.has_shells || self.nodes.is_empty() || self.nodes[0].tag != "html" {
1304 return;
1305 }
1306 self.has_shells = true;
1307 let kids = self.nodes[0].children.clone();
1308 let find = |dom: &DomBridge, names: &[&str]| kids.iter().position(|&c| dom.nodes.get(c).is_some_and(|n| !n.is_text && names.contains(&n.tag.as_str())));
1309 let head_pos = find(self, &["head"]);
1310 let body_pos = find(self, &["body", "frameset"]);
1311 if head_pos.is_some() && body_pos.is_some() {
1312 return;
1313 }
1314 let is_meta = |dom: &DomBridge, c: usize| -> bool {
1316 dom.nodes.get(c).is_some_and(|n| {
1317 if n.is_text {
1318 n.text_override.as_deref().unwrap_or(&n.initial_text).trim().is_empty()
1319 } else {
1320 n.tag == "#comment" || matches!(n.tag.as_str(), "title" | "meta" | "link" | "style" | "script" | "base" | "noscript" | "template")
1321 }
1322 })
1323 };
1324 let new_shell = |dom: &mut DomBridge, tag: &str| -> usize {
1325 let i = dom.new_element_node(tag);
1326 dom.nodes[i].attrs.insert(String::from("_implicit"), String::from("1"));
1327 i
1328 };
1329 let mut rest: Vec<usize> = kids.clone();
1330 let mut head_kids: Vec<usize> = Vec::new();
1331 let mut new_head = None;
1332 if head_pos.is_none() {
1333 let limit = body_pos.unwrap_or(kids.len());
1334 let n = (0..limit).take_while(|&i| is_meta(self, kids[i])).count();
1335 head_kids = kids[..n].to_vec();
1337 rest = kids[n..].to_vec();
1338 new_head = Some(new_shell(self, "head"));
1339 }
1340 let mut new_body = None;
1341 if body_pos.is_none() {
1342 let b = new_shell(self, "body");
1343 let mut body_kids = Vec::new();
1344 let mut keep = Vec::new();
1345 let hp = head_pos.map(|p| kids[p]);
1346 let mut after_head = hp.is_none();
1347 for &c in &rest {
1348 if Some(c) == hp {
1349 after_head = true;
1350 keep.push(c);
1351 } else if after_head {
1352 body_kids.push(c);
1353 } else {
1354 keep.push(c);
1355 }
1356 }
1357 for &c in &body_kids {
1358 self.nodes[c].parent = Some(b);
1359 }
1360 self.nodes[b].children = body_kids;
1361 rest = keep;
1362 new_body = Some(b);
1363 }
1364 if let Some(h) = new_head {
1365 for &c in &head_kids {
1366 self.nodes[c].parent = Some(h);
1367 }
1368 self.nodes[h].children = head_kids;
1369 rest.insert(0, h);
1370 }
1371 if let Some(b) = new_body {
1372 rest.push(b);
1373 }
1374 for &c in &rest {
1375 self.nodes[c].parent = Some(0);
1376 }
1377 self.nodes[0].children = rest;
1378 }
1379
1380 fn flat_kids(&self, parent: usize, out: &mut Vec<usize>) {
1382 for &c in &self.nodes[parent].children {
1383 if self.nodes.get(c).is_some_and(|n| n.attrs.contains_key("_implicit")) {
1384 self.flat_kids(c, out);
1385 } else {
1386 out.push(c);
1387 }
1388 }
1389 }
1390
1391 fn collect_text(&self, idx: usize) -> String {
1393 let node = &self.nodes[idx];
1394 if node.tag == "#comment" || node.tag == "#pi" {
1395 return node.text_override.clone().unwrap_or_else(|| node.initial_text.clone());
1396 }
1397 let mut s = String::new();
1398 self.collect_text_into(idx, &mut s);
1399 s
1400 }
1401 fn collect_text_into(&self, idx: usize, out: &mut String) {
1402 let node = &self.nodes[idx];
1403 if node.is_text {
1404 out.push_str(node.text_override.as_deref().unwrap_or(&node.initial_text));
1405 return;
1406 }
1407 for &c in &node.children {
1408 self.collect_text_into(c, out);
1409 }
1410 }
1411
1412 pub fn build_id_index(&self) -> alloc::collections::BTreeMap<&str, usize> {
1428 let mut map: alloc::collections::BTreeMap<&str, usize> =
1429 alloc::collections::BTreeMap::new();
1430 if !self.built {
1431 return map;
1432 }
1433 for i in 0..self.nodes.len() {
1434 let n = &self.nodes[i];
1435 if n.is_text || n.id.is_empty() {
1436 continue;
1437 }
1438 if !self.is_attached(i) {
1439 continue;
1440 }
1441 map.entry(n.id.as_str()).or_insert(i);
1442 }
1443 map
1444 }
1445
1446 pub fn resolve_element_id(id_map: &BTreeMap<&str, usize>, element_id: &str) -> Option<usize> {
1449 if let Some(n) = element_id.strip_prefix("_node_idx_") {
1450 return n.parse().ok();
1451 }
1452 id_map.get(element_id).copied()
1453 }
1454
1455 pub fn get_element_by_id(&self, id: &str) -> Option<usize> {
1456 if !self.built || id.is_empty() {
1457 return None;
1458 }
1459 if let Some(rest) = id.strip_prefix("_node_idx_") {
1460 if let Ok(idx) = rest.parse::<usize>() {
1461 if idx < self.nodes.len() && !self.nodes[idx].is_text && self.is_attached(idx) {
1462 return Some(idx);
1463 }
1464 }
1465 }
1466 (0..self.nodes.len())
1467 .find(|&i| !self.nodes[i].is_text && self.nodes[i].id == id && self.is_attached(i))
1468 }
1469
1470 pub fn is_attached(&self, idx: usize) -> bool {
1474 if self.main_doctype == Some(idx) {
1475 return true;
1476 }
1477 let mut cur = idx;
1478 let mut guard = 0;
1479 let limit = self.nodes.len() + 64;
1480 loop {
1481 if cur == 0 {
1482 return true;
1483 }
1484 match self.nodes.get(cur).and_then(|n| n.parent) {
1485 Some(p) => {
1486 cur = p;
1487 guard += 1;
1488 if guard > limit {
1489 return false;
1490 }
1491 }
1492 None => {
1493 if let Some(host) = self.shadow_tree.get_host_by_root(cur) {
1494 cur = host;
1495 guard += 1;
1496 if guard > limit {
1497 return false;
1498 }
1499 } else {
1500 return false;
1501 }
1502 }
1503 }
1504 }
1505 }
1506
1507 pub fn query(&self, selector: &str) -> Option<usize> {
1509 self.query_scoped(selector, None, true).into_iter().next()
1510 }
1511
1512 pub fn get_elements_by_class_name(&self, root: Option<usize>, class_names: &str) -> Vec<usize> {
1518 let want = split_ascii_ws(class_names);
1519 if want.is_empty() || (!self.built && root.is_none()) || self.nodes.is_empty() {
1520 return Vec::new();
1521 }
1522 let mut out = Vec::new();
1523 let quirks = self.quirks_mode;
1524 let matches_all = |n: &DomNode| -> bool {
1525 !n.is_text
1526 && !n.tag.starts_with('#')
1527 && want.iter().all(|w| {
1528 n.classes.iter().any(|c| {
1529 if quirks {
1530 c.eq_ignore_ascii_case(w)
1531 } else {
1532 c == w
1533 }
1534 })
1535 })
1536 };
1537 let mut stack: Vec<usize> = match root {
1538 Some(r) => self.nodes.get(r).map(|n| n.children.iter().rev().copied().collect()).unwrap_or_default(),
1539 None => alloc::vec![0],
1540 };
1541 let mut guard = 0usize;
1542 while let Some(i) = stack.pop() {
1543 guard += 1;
1544 if guard > self.nodes.len() + 1 {
1545 break;
1546 }
1547 if let Some(n) = self.nodes.get(i) {
1548 if matches_all(n) {
1549 out.push(i);
1550 }
1551 stack.extend(n.children.iter().rev().copied());
1552 }
1553 }
1554 out
1555 }
1556
1557 pub fn query_all(&self, selector: &str) -> Vec<usize> {
1558 self.query_all_scoped(selector, None)
1559 }
1560
1561 pub fn query_all_scoped(&self, selector: &str, scope_root: Option<usize>) -> Vec<usize> {
1566 self.query_scoped(selector, scope_root, false)
1567 }
1568
1569 fn query_scoped(&self, selector: &str, scope_root: Option<usize>, first: bool) -> Vec<usize> {
1576 let sel = selector.trim();
1577 let mut out = Vec::new();
1578 if (!self.built && scope_root.is_none()) || sel.is_empty() {
1579 return out;
1580 }
1581 let groups = parse_selector_groups(sel);
1582 if groups.is_empty() {
1583 return out;
1584 }
1585 if let Some(root) = scope_root {
1586 let mut stack: Vec<usize> = alloc::vec![root];
1588 let mut guard = 0usize;
1589 while let Some(i) = stack.pop() {
1590 guard += 1;
1591 if guard > self.nodes.len() + 1 {
1592 break;
1593 }
1594 if self.node_matches_parsed(i, &groups, scope_root) {
1595 out.push(i);
1596 if first {
1597 return out;
1598 }
1599 }
1600 if let Some(n) = self.nodes.get(i) {
1601 stack.extend(n.children.iter().rev().copied());
1602 }
1603 }
1604 return out;
1605 }
1606 for i in 0..self.nodes.len() {
1607 if self.nodes[i].is_text || !self.node_matches_parsed(i, &groups, None) || !self.is_attached(i) {
1608 continue;
1609 }
1610 out.push(i);
1611 if first {
1612 break;
1613 }
1614 }
1615 out
1616 }
1617
1618 pub fn set_text_content(&mut self, idx: usize, val: &str) {
1623 self.set_text_content_raw(idx, val);
1624 if !self.js_created_scripts.is_empty() {
1626 self.script_children_changed(idx);
1627 }
1628 }
1629
1630 fn set_text_content_raw(&mut self, idx: usize, val: &str) {
1631 if idx >= self.nodes.len() || self.nodes[idx].tag == "#doctype" || self.nodes[idx].tag == "#document" {
1632 return;
1633 }
1634 if self.nodes[idx].tag == "#comment" || self.nodes[idx].tag == "#pi" {
1635 let old_val = self.nodes[idx]
1636 .text_override
1637 .as_deref()
1638 .unwrap_or(&self.nodes[idx].initial_text)
1639 .to_string();
1640 self.nodes[idx].text_override = Some(val.to_string());
1641 if !self.suppress_range_hook {
1642 self.ranges_replace_data(idx, 0, old_val.encode_utf16().count(), val.encode_utf16().count());
1643 }
1644 self.notify_character_data(idx, Some(&old_val));
1645 return;
1646 }
1647 if !self.nodes[idx].is_text {
1653 if self.nodes[idx].children.is_empty() && val.is_empty() {
1654 return;
1655 }
1656 let attached = self.is_attached(idx);
1657 let is_meta_text = matches!(self.nodes[idx].tag.as_str(), "style" | "script" | "title");
1658 if !val.is_empty() && self.nodes[idx].children.len() == 1 {
1663 let c0 = self.nodes[idx].children[0];
1664 if self.nodes.get(c0).is_some_and(|n| n.is_text)
1665 && !self.has_child_list_observer(idx)
1666 && self.ranges.is_empty()
1667 {
1668 let cur_text = self.nodes[c0]
1669 .text_override
1670 .as_deref()
1671 .unwrap_or(&self.nodes[c0].initial_text);
1672 if !cur_text.is_empty() {
1673 let same_text = cur_text == val;
1674 if !same_text {
1675 self.nodes[c0].text_override = Some(val.to_string());
1676 if attached && (is_meta_text || !self.is_in_display_none_subtree(idx)) {
1677 if is_meta_text {
1678 self.mark_structural_dirty_for("textContent");
1679 } else {
1680 self.record_text_update(idx, c0, val);
1681 }
1682 }
1683 }
1684 return;
1685 }
1686 }
1687 }
1688 let removed_now: Vec<usize> = self.nodes[idx].children.clone();
1689 self.ranges_children_cleared(idx, &removed_now);
1690 let removed: Vec<usize> = core::mem::take(&mut self.nodes[idx].children);
1691 for &c in &removed {
1692 if let Some(n) = self.nodes.get_mut(c) {
1693 n.parent = None;
1694 }
1695 }
1696 let mut added = Vec::new();
1697 if !val.is_empty() {
1698 let t = self.new_text_node(val);
1699 self.inherit_owner(t, idx);
1700 self.nodes[t].parent = Some(idx);
1701 self.nodes[idx].children.push(t);
1702 added.push(t);
1703 }
1704 if !removed.is_empty() || !added.is_empty() {
1705 self.notify_child_list(idx, added, removed);
1706 }
1707 if attached && (is_meta_text || !self.is_in_display_none_subtree(idx)) {
1708 self.mark_structural_dirty_for("textContent");
1709 }
1710 return;
1711 }
1712 let text_nodes = self.descendant_text_nodes(idx);
1713 let mut any_changed = false;
1714 {
1715 for (k, t) in text_nodes.iter().enumerate() {
1716 let new_val = if k == 0 { val.to_string() } else { String::new() };
1717 let old_val = self.nodes[*t]
1722 .text_override
1723 .as_deref()
1724 .unwrap_or(&self.nodes[*t].initial_text)
1725 .to_string();
1726 self.nodes[*t].text_override = Some(new_val.clone());
1727 if !self.suppress_range_hook {
1728 self.ranges_replace_data(*t, 0, old_val.encode_utf16().count(), new_val.encode_utf16().count());
1729 }
1730 self.notify_character_data(*t, Some(&old_val));
1731 if old_val != new_val {
1732 any_changed = true;
1733 }
1734 }
1735 }
1736 if any_changed && self.is_attached(idx) && !self.is_in_display_none_subtree(idx) {
1737 if text_nodes.len() == 1 && text_nodes[0] == idx {
1738 if let Some(parent_idx) = self.nodes[idx].parent {
1739 if self
1740 .nodes
1741 .get(parent_idx)
1742 .is_some_and(|p| !p.is_text && p.children.len() == 1)
1743 {
1744 self.record_text_update(parent_idx, idx, val);
1745 return;
1746 }
1747 }
1748 }
1749 self.mark_structural_dirty_for("text-node");
1750 }
1751 }
1752
1753 fn is_exclusive_text(&self, idx: usize) -> bool {
1755 self.nodes
1756 .get(idx)
1757 .is_some_and(|n| n.is_text && !n.attrs.contains_key("_cdata"))
1758 }
1759 pub fn normalize_node(&mut self, idx: usize) {
1762 if idx >= self.nodes.len() || self.nodes[idx].is_text {
1763 return;
1764 }
1765 let mut texts: Vec<usize> = Vec::new();
1768 let mut stack: Vec<usize> = self.nodes[idx].children.iter().rev().copied().collect();
1769 while let Some(i) = stack.pop() {
1770 if self.is_exclusive_text(i) {
1771 texts.push(i);
1772 } else {
1773 stack.extend(self.nodes[i].children.iter().rev().copied());
1774 }
1775 }
1776 for t in texts {
1777 let Some(parent) = self.nodes[t].parent else { continue };
1778 let mut length = self.text_of(t).encode_utf16().count();
1779 if length == 0 {
1780 self.remove_node(t);
1781 continue;
1782 }
1783 let siblings = self.nodes[parent].children.clone();
1784 let Some(pos) = siblings.iter().position(|&c| c == t) else { continue };
1785 let mut merged = self.text_of(t);
1786 let mut run: Vec<usize> = Vec::new();
1787 for &c in siblings.iter().skip(pos + 1) {
1788 if !self.is_exclusive_text(c) {
1789 break;
1790 }
1791 let index = self.nodes[parent].children.iter().position(|&x| x == c).unwrap_or(0);
1792 self.ranges_normalize_merge(t, c, parent, index, length);
1793 let more = self.text_of(c);
1794 length += more.encode_utf16().count();
1795 merged.push_str(&more);
1796 run.push(c);
1797 }
1798 if !run.is_empty() {
1799 self.nodes[t].text_override = Some(merged);
1800 for c in run {
1801 self.remove_node(c);
1802 }
1803 }
1804 }
1805 }
1806 fn text_of(&self, idx: usize) -> String {
1809 let n = &self.nodes[idx];
1810 n.text_override.as_deref().unwrap_or(&n.initial_text).to_string()
1811 }
1812
1813 fn new_element_node(&mut self, tag: &str) -> usize {
1816 let idx = self.nodes.len();
1817 let lower_tag = tag.to_ascii_lowercase();
1818 let mut attrs = BTreeMap::new();
1819 if self.custom_elements.is_defined(&lower_tag) {
1820 attrs.insert(String::from("_defined"), String::from("true"));
1821 }
1822 self.nodes.push(DomNode {
1823 tag: lower_tag,
1824 is_text: false,
1825 id: String::new(),
1826 classes: Vec::new(),
1827 style: BTreeMap::new(),
1828 attrs,
1829 text_override: None,
1830 initial_text: String::new(),
1831 parent: None,
1832 children: Vec::new(),
1833 classes_dirty: false,
1834 style_dirty: false,
1835 });
1836 idx
1837 }
1838
1839 fn new_text_node(&mut self, text: &str) -> usize {
1840 let idx = self.nodes.len();
1841 self.nodes.push(DomNode {
1842 tag: String::new(),
1843 is_text: true,
1844 id: String::new(),
1845 classes: Vec::new(),
1846 style: BTreeMap::new(),
1847 attrs: BTreeMap::new(),
1848 text_override: Some(text.to_string()),
1849 initial_text: text.to_string(),
1850 parent: None,
1851 children: Vec::new(),
1852 classes_dirty: false,
1853 style_dirty: false,
1854 });
1855 idx
1856 }
1857
1858 pub fn create_element_plain(&mut self, tag: &str) -> usize {
1862 self.new_element_node(tag)
1863 }
1864
1865 pub fn create_element(&mut self, tag: &str) -> usize {
1866 let idx = self.new_element_node(tag);
1867 if tag.eq_ignore_ascii_case("script") {
1868 self.js_created_scripts.insert(idx);
1869 self.set_attr(idx, "async", "async");
1870 } else if tag.eq_ignore_ascii_case("link") {
1871 self.js_created_links.insert(idx);
1872 }
1873 idx
1874 }
1875
1876 pub fn script_source(&self, idx: usize) -> (Option<String>, String, String) {
1878 let Some(n) = self.nodes.get(idx) else { return (None, String::new(), String::new()) };
1879 let src = n.attrs.get("src").filter(|s| !s.trim().is_empty()).cloned();
1880 let ty = n.attrs.get("type").cloned().unwrap_or_default();
1881 let text = match &n.text_override {
1882 Some(t) => t.clone(),
1883 None => n
1884 .children
1885 .iter()
1886 .filter_map(|&c| self.nodes.get(c))
1887 .filter(|c| c.is_text)
1888 .map(|c| c.text_override.clone().unwrap_or_else(|| c.initial_text.clone()))
1889 .collect(),
1890 };
1891 (src, ty, text)
1892 }
1893
1894 pub fn is_connected(&self, mut idx: usize) -> bool {
1896 let mut guard = 0;
1897 while let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
1898 idx = p;
1899 guard += 1;
1900 if guard > 10_000 {
1901 return false;
1902 }
1903 }
1904 idx == 0
1905 }
1906
1907 pub fn is_frame_element(&self, idx: usize) -> bool {
1909 self.nodes.get(idx).is_some_and(|n| !n.is_text && matches!(n.tag.as_str(), "iframe" | "frame"))
1910 }
1911
1912 pub fn browsing_context_doc(&self, idx: usize) -> Option<Option<usize>> {
1916 let mut cur = idx;
1917 let mut guard = 0usize;
1918 let limit = self.nodes.len() + 64;
1919 loop {
1920 guard += 1;
1921 if guard > limit {
1922 return None;
1923 }
1924 if cur == 0 || self.main_doctype == Some(cur) {
1925 return Some(None);
1926 }
1927 match self.nodes.get(cur).and_then(|n| n.parent) {
1928 Some(p) => cur = p,
1929 None => {
1930 if let Some(h) = self.shadow_tree.get_host_by_root(cur) {
1931 cur = h;
1932 } else if let Some(&fe) = self.iframe_doc_to_elem.get(&cur) {
1933 return self.browsing_context_doc(fe).map(|_| Some(cur));
1935 } else {
1936 return None;
1937 }
1938 }
1939 }
1940 }
1941 }
1942
1943 fn queue_post_connection(&mut self, parent: Option<usize>, roots: &[usize]) {
1947 if let Some(p) = parent {
1948 self.script_children_changed(p);
1949 }
1950 let mut stack: Vec<usize> = roots.iter().rev().copied().collect();
1951 let mut guard = 0usize;
1952 while let Some(i) = stack.pop() {
1953 guard += 1;
1954 if guard > self.nodes.len() + 64 {
1955 break;
1956 }
1957 let Some(n) = self.nodes.get(i) else { continue };
1958 if n.is_text {
1959 continue;
1960 }
1961 let is_script = n.tag == "script";
1962 let is_frame = matches!(n.tag.as_str(), "iframe" | "frame");
1963 if ((is_script && self.js_created_scripts.contains(&i)) || is_frame) && self.browsing_context_doc(i).is_some() {
1964 if is_frame {
1965 self.frames_pending_setup.insert(i);
1966 }
1967 self.pending_post_connection.push(i);
1968 }
1969 if self.js_created_links.contains(&i) && self.is_connected(i) {
1971 let is_css = self.get_attr(i, "rel").is_some_and(|r| r.to_ascii_lowercase().contains("stylesheet"));
1972 if is_css && self.get_attr(i, "href").is_some_and(|h| !h.is_empty()) {
1973 self.js_created_links.remove(&i);
1974 self.pending_dynamic_links.push(i);
1975 }
1976 }
1977 let kids: Vec<usize> = self.nodes.get(i).map(|n| n.children.clone()).unwrap_or_default();
1978 for &c in kids.iter().rev() {
1979 stack.push(c);
1980 }
1981 if let Some(r) = self.shadow_tree.get_by_host(i).map(|d| d.root_node_idx) {
1982 stack.push(r);
1983 }
1984 }
1985 }
1986
1987 pub fn script_children_changed(&mut self, idx: usize) {
1990 let target = match self.nodes.get(idx) {
1991 Some(n) if n.is_text => match n.parent {
1992 Some(p) => p,
1993 None => return,
1994 },
1995 Some(_) => idx,
1996 None => return,
1997 };
1998 if self.js_created_scripts.contains(&target) && self.browsing_context_doc(target).is_some() {
1999 self.pending_post_connection.push(target);
2000 }
2001 }
2002
2003 pub fn ensure_frame_doc(&mut self, idx: usize) -> bool {
2005 if self.iframe_docs.contains_key(&idx) || !self.is_frame_element(idx) {
2006 return false;
2007 }
2008 let doc_idx = self.create_document_node("text/html", true);
2009 if let Some(dn) = self.nodes.get_mut(doc_idx) {
2010 dn.attrs.insert(String::from("_url"), String::from("about:blank"));
2011 }
2012 let html = self.create_element("html");
2013 let head = self.create_element("head");
2014 let body = self.create_element("body");
2015 self.append_child(html, head);
2016 self.append_child(html, body);
2017 self.set_owner_subtree(html, Some(doc_idx));
2018 self.append_child(doc_idx, html);
2019 self.iframe_docs.insert(idx, doc_idx);
2020 self.iframe_doc_to_elem.insert(doc_idx, idx);
2021 self.frames_dirty = true;
2022 true
2023 }
2024
2025 pub fn prune_disconnected_frames(&mut self) -> bool {
2029 let mut any = false;
2030 loop {
2031 let gone: Vec<usize> = self
2032 .iframe_docs
2033 .keys()
2034 .copied()
2035 .filter(|&e| self.browsing_context_doc(e).is_none())
2036 .collect();
2037 if gone.is_empty() {
2038 break;
2039 }
2040 for e in gone {
2041 if let Some(d) = self.iframe_docs.remove(&e) {
2042 self.iframe_doc_to_elem.remove(&d);
2043 }
2044 self.iframe_content_windows.remove(&e);
2045 self.frames_pending_setup.remove(&e);
2046 if let Some(n) = self.nodes.get_mut(e) {
2047 n.attrs.remove("_iframe_loaded");
2048 }
2049 }
2050 any = true;
2051 }
2052 if any {
2053 self.frames_dirty = true;
2054 }
2055 any
2056 }
2057
2058 pub fn child_frames_of(&self, root: usize) -> Vec<usize> {
2060 let mut out = Vec::new();
2061 let mut stack: Vec<usize> = self.nodes.get(root).map(|n| n.children.iter().rev().copied().collect()).unwrap_or_default();
2062 let mut guard = 0usize;
2063 while let Some(i) = stack.pop() {
2064 guard += 1;
2065 if guard > self.nodes.len() + 64 {
2066 break;
2067 }
2068 let Some(n) = self.nodes.get(i) else { continue };
2069 if n.is_text {
2070 continue;
2071 }
2072 if matches!(n.tag.as_str(), "iframe" | "frame") && self.iframe_docs.contains_key(&i) {
2073 out.push(i);
2074 }
2075 stack.extend(n.children.iter().rev().copied());
2076 }
2077 out
2078 }
2079
2080 pub fn create_text_node(&mut self, text: &str) -> usize {
2082 self.new_text_node(text)
2083 }
2084
2085 pub fn create_comment(&mut self, text: &str) -> usize {
2087 let idx = self.nodes.len();
2088 self.nodes.push(DomNode {
2089 tag: String::from("#comment"),
2090 is_text: false,
2091 id: String::new(),
2092 classes: Vec::new(),
2093 style: BTreeMap::new(),
2094 attrs: BTreeMap::new(),
2095 text_override: Some(text.to_string()),
2096 initial_text: text.to_string(),
2097 parent: None,
2098 children: Vec::new(),
2099 classes_dirty: false,
2100 style_dirty: false,
2101 });
2102 idx
2103 }
2104
2105 pub fn create_doctype(&mut self, name: &str, public_id: &str, system_id: &str) -> usize {
2108 let idx = self.nodes.len();
2109 let mut attrs = BTreeMap::new();
2110 attrs.insert(String::from("_name"), name.to_string());
2111 attrs.insert(String::from("_publicId"), public_id.to_string());
2112 attrs.insert(String::from("_systemId"), system_id.to_string());
2113 self.nodes.push(DomNode {
2114 tag: String::from("#doctype"),
2115 is_text: false,
2116 id: String::new(),
2117 classes: Vec::new(),
2118 style: BTreeMap::new(),
2119 attrs,
2120 text_override: None,
2121 initial_text: String::new(),
2122 parent: None,
2123 children: Vec::new(),
2124 classes_dirty: false,
2125 style_dirty: false,
2126 });
2127 idx
2128 }
2129
2130 pub fn create_processing_instruction(&mut self, target: &str, data: &str) -> usize {
2133 let idx = self.nodes.len();
2134 let mut attrs = BTreeMap::new();
2135 attrs.insert(String::from("_target"), target.to_string());
2136 self.nodes.push(DomNode {
2137 tag: String::from("#pi"),
2138 is_text: false,
2139 id: String::new(),
2140 classes: Vec::new(),
2141 style: BTreeMap::new(),
2142 attrs,
2143 text_override: Some(data.to_string()),
2144 initial_text: data.to_string(),
2145 parent: None,
2146 children: Vec::new(),
2147 classes_dirty: false,
2148 style_dirty: false,
2149 });
2150 idx
2151 }
2152
2153 pub fn create_document_fragment(&mut self) -> usize {
2159 self.new_element_node("#fragment")
2160 }
2161
2162 pub fn attr_ns(&self, elem: usize, qname: &str) -> Option<String> {
2171 if let Some(ns) = self.ns_attrs.get(&elem).and_then(|list| {
2172 list.iter()
2173 .find(|(_, qn, _)| qn == qname)
2174 .map(|(ns, _, _)| ns.clone())
2175 }) {
2176 return Some(ns);
2177 }
2178 self.nodes.get(elem)?.attrs.get(&format!("_ans:{}", qname)).cloned()
2179 }
2180
2181 pub fn new_attr_node(&mut self, qname: &str, ns: Option<&str>, value: &str) -> usize {
2183 let idx = self.nodes.len();
2184 let mut attrs = BTreeMap::new();
2185 attrs.insert(String::from("_aname"), qname.to_string());
2186 attrs.insert(String::from("_aval"), value.to_string());
2187 if let Some(n) = ns {
2188 attrs.insert(String::from("_ans"), n.to_string());
2189 }
2190 self.nodes.push(DomNode {
2191 tag: String::from("#attr"),
2192 is_text: false,
2193 id: String::new(),
2194 classes: Vec::new(),
2195 style: BTreeMap::new(),
2196 attrs,
2197 text_override: None,
2198 initial_text: String::new(),
2199 parent: None,
2200 children: Vec::new(),
2201 classes_dirty: false,
2202 style_dirty: false,
2203 });
2204 self.has_attr_nodes = true;
2205 idx
2206 }
2207
2208 pub fn attr_node_for(&mut self, elem: usize, qname: &str) -> Option<usize> {
2210 if qname.starts_with('_') {
2211 return None;
2212 }
2213 for (ns, qn) in self.attr_entries(elem) {
2214 if qn == qname {
2215 return self.attr_node_for_ns(elem, ns.as_deref(), &qn);
2216 }
2217 }
2218 None
2219 }
2220
2221 pub fn attr_node_for_ns(&mut self, elem: usize, ns: Option<&str>, qname: &str) -> Option<usize> {
2223 if qname.starts_with('_') {
2224 return None;
2225 }
2226 let ns_clean = ns.filter(|s| !s.is_empty());
2227 let val = match ns_clean {
2228 None => {
2229 if !self.has_attr(elem, qname) {
2230 return None;
2231 }
2232 self.get_attr(elem, qname).unwrap_or_default()
2233 }
2234 Some(u) => {
2235 let local = qname.split_once(':').map(|(_, l)| l).unwrap_or(qname);
2236 self.get_attr_ns(elem, Some(u), local)?
2237 }
2238 };
2239 let key = match ns_clean {
2240 None => qname.to_string(),
2241 Some(u) => format!("{}\x01{}", u, qname),
2242 };
2243 if let Some(&i) = self.attr_nodes.get(&(elem, key.clone())) {
2244 return Some(i);
2245 }
2246 let i = self.new_attr_node(qname, ns_clean, &val);
2247 self.nodes[i].attrs.insert(String::from("_aowner"), elem.to_string());
2248 if let Some(own) = self.node_document(elem) {
2249 self.node_doc.insert(i, own);
2250 }
2251 self.attr_nodes.insert((elem, key), i);
2252 Some(i)
2253 }
2254
2255 pub fn detach_attr_node(&mut self, elem: usize, qname: &str, last_value: &str) {
2257 if let Some(i) = self.attr_nodes.remove(&(elem, qname.to_string())) {
2258 if let Some(n) = self.nodes.get_mut(i) {
2259 n.attrs.remove("_aowner");
2260 n.attrs.insert(String::from("_aval"), last_value.to_string());
2261 }
2262 }
2263 }
2264
2265 pub fn attr_value(&self, attr: usize) -> String {
2267 let Some(n) = self.nodes.get(attr) else { return String::new() };
2268 if let (Some(o), Some(name)) = (n.attrs.get("_aowner").and_then(|s| s.parse::<usize>().ok()), n.attrs.get("_aname")) {
2269 if let Some(ns) = n.attrs.get("_ans") {
2270 let local = name.split_once(':').map(|(_, l)| l).unwrap_or(name.as_str());
2271 return self.get_attr_ns(o, Some(ns), local).unwrap_or_default();
2272 }
2273 return self.get_attr(o, name).unwrap_or_default();
2274 }
2275 n.attrs.get("_aval").cloned().unwrap_or_default()
2276 }
2277
2278 pub fn set_attr_ns(&mut self, elem: usize, ns: Option<&str>, qname: &str, value: &str) {
2281 let Some(u) = ns.filter(|s| !s.is_empty()) else {
2282 self.set_attr(elem, qname, value);
2283 return;
2284 };
2285 self.has_attr_nodes = true;
2286 self.ensure_attr_ns_order(elem);
2287 let local = qname.split_once(':').map(|(_, l)| l).unwrap_or(qname);
2288 let list = self.ns_attrs.entry(elem).or_default();
2289 let old_val = if let Some(entry) = list.iter_mut().find(|(a_ns, a_qn, _)| {
2290 let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2291 a_ns == u && a_l == local
2292 }) {
2293 let old = entry.2.clone();
2294 entry.2 = value.to_string();
2295 Some(old)
2296 } else {
2297 list.push((u.to_string(), qname.to_string(), value.to_string()));
2298 if let Some(ord) = self.attr_ns_order.get_mut(&elem) {
2299 ord.push((Some(u.to_string()), qname.to_string()));
2300 }
2301 None
2302 };
2303 self.notify_attribute_ns(elem, local, Some(u), old_val.as_deref());
2304 }
2305
2306 pub fn find_attr_ns(&self, elem: usize, ns: Option<&str>, local: &str) -> Option<String> {
2308 match ns.filter(|s| !s.is_empty()) {
2309 None => {
2310 let n = self.nodes.get(elem)?;
2311 for name in self.attr_names_default(elem) {
2312 if name == local && !n.attrs.contains_key(&format!("_ans:{}", name)) {
2313 return Some(name);
2314 }
2315 }
2316 None
2317 }
2318 Some(u) => self.ns_attrs.get(&elem).and_then(|list| {
2319 list.iter().find_map(|(a_ns, a_qn, _)| {
2320 let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2321 if a_ns == u && a_l == local {
2322 Some(a_qn.clone())
2323 } else {
2324 None
2325 }
2326 })
2327 }),
2328 }
2329 }
2330
2331 pub fn get_attr_ns(&self, elem: usize, ns: Option<&str>, local: &str) -> Option<String> {
2333 match ns.filter(|s| !s.is_empty()) {
2334 None => self.get_attr(elem, local),
2335 Some(u) => self.ns_attrs.get(&elem).and_then(|list| {
2336 list.iter().find_map(|(a_ns, a_qn, v)| {
2337 let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2338 if a_ns == u && a_l == local {
2339 Some(v.clone())
2340 } else {
2341 None
2342 }
2343 })
2344 }),
2345 }
2346 }
2347
2348 pub fn remove_attr_ns(&mut self, elem: usize, ns: Option<&str>, local: &str) {
2350 let Some(u) = ns.filter(|s| !s.is_empty()) else {
2351 self.remove_attr(elem, local);
2352 return;
2353 };
2354 let removed = if let Some(list) = self.ns_attrs.get_mut(&elem) {
2355 if let Some(pos) = list.iter().position(|(a_ns, a_qn, _)| {
2356 let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2357 a_ns == u && a_l == local
2358 }) {
2359 let (_, qn, val) = list.remove(pos);
2360 Some((qn, val))
2361 } else {
2362 None
2363 }
2364 } else {
2365 None
2366 };
2367 if let Some((qn, old_val)) = removed {
2368 if let Some(ord) = self.attr_ns_order.get_mut(&elem) {
2369 ord.retain(|(a_ns, a_qn)| !(a_ns.as_deref() == Some(u) && a_qn == &qn));
2370 }
2371 self.remove_attr_ns_notify(elem, Some(u), local, &qn, &old_val);
2372 }
2373 }
2374
2375 pub fn remove_attr_ns_notify(
2376 &mut self,
2377 elem: usize,
2378 ns: Option<&str>,
2379 local: &str,
2380 qn: &str,
2381 old_val: &str,
2382 ) {
2383 if self.has_attr_nodes {
2384 let key = match ns {
2385 None => qn.to_string(),
2386 Some(u) => format!("{}\x01{}", u, qn),
2387 };
2388 self.detach_attr_node(elem, &key, old_val);
2389 }
2390 self.notify_attribute_ns(elem, local, ns, Some(old_val));
2391 }
2392
2393 fn range_inclusive_descendant(&self, mut n: usize, anc: usize) -> bool {
2398 let mut guard = 0usize;
2399 loop {
2400 if n == anc {
2401 return true;
2402 }
2403 match self.nodes.get(n).and_then(|x| x.parent) {
2404 Some(p) => n = p,
2405 None => return false,
2406 }
2407 guard += 1;
2408 if guard > self.nodes.len() + 8 {
2409 return false;
2410 }
2411 }
2412 }
2413
2414 pub fn ni_register(&mut self, obj: &crate::os_lib::ecma::value::ObjRef, root: usize) -> u32 {
2416 if self.node_iters.len() >= 64 && self.node_iters.len().is_power_of_two() {
2417 self.node_iters.retain(|_, r| r.obj.strong_count() > 0);
2418 }
2419 let id = self.next_ni_id;
2420 self.next_ni_id = self.next_ni_id.wrapping_add(1).max(1);
2421 self.node_iters.insert(
2422 id,
2423 NiRec {
2424 obj: alloc::rc::Rc::downgrade(obj),
2425 root,
2426 reference: root,
2427 before: true,
2428 in_flight: None,
2429 },
2430 );
2431 id
2432 }
2433
2434 pub fn remove_main_doc_child(&mut self, child: usize) {
2436 self.iters_pre_remove(child);
2437 if self.main_doctype == Some(child) {
2438 self.main_doctype = None;
2439 }
2440 if let Some(n) = self.nodes.get_mut(child) {
2441 n.parent = None;
2442 }
2443 }
2444
2445 fn ni_retarget_pos(&self, root: usize, node: usize, pos: usize, before_in: bool) -> (usize, bool) {
2446 if self.range_inclusive_descendant(root, node) || !self.range_inclusive_descendant(pos, node) {
2447 return (pos, before_in);
2448 }
2449 let mut before = before_in;
2450 if before {
2451 if self.main_doctype == Some(node) && root == MAIN_DOC && !self.nodes.is_empty() {
2452 return (0, true);
2453 }
2454 let mut cur = node;
2456 let mut next = None;
2457 while cur != root {
2458 let Some(p) = self.nodes.get(cur).and_then(|n| n.parent) else { break };
2459 let p_pos = self.nodes[p].children.iter().position(|&c| c == cur);
2460 if let Some(sib) = p_pos.and_then(|i| self.nodes[p].children.get(i + 1).copied()) {
2461 next = Some(sib);
2462 break;
2463 }
2464 cur = p;
2465 }
2466 if let Some(nx) = next {
2467 return (nx, true);
2468 }
2469 before = false;
2470 }
2471 if self.main_doctype == Some(node) {
2472 return (MAIN_DOC, before);
2473 }
2474 let new_ref = match self.nodes.get(node).and_then(|n| n.parent) {
2475 Some(p) => {
2476 let p_pos = self.nodes[p].children.iter().position(|&c| c == node).unwrap_or(0);
2477 if p_pos == 0 {
2478 p
2479 } else {
2480 let mut d = self.nodes[p].children[p_pos - 1];
2481 while let Some(&last) = self.nodes[d].children.last() {
2482 d = last;
2483 }
2484 d
2485 }
2486 }
2487 None => pos,
2488 };
2489 (new_ref, before)
2490 }
2491
2492 fn iters_pre_remove(&mut self, node: usize) {
2494 if self.node_iters.is_empty() {
2495 return;
2496 }
2497 self.node_iters.retain(|_, r| r.obj.strong_count() > 0);
2498 let keys: Vec<u32> = self.node_iters.keys().copied().collect();
2499 for k in keys {
2500 let Some(r) = self.node_iters.get(&k).cloned() else { continue };
2501 let (nr, nb) = self.ni_retarget_pos(r.root, node, r.reference, r.before);
2502 let nf = r.in_flight.map(|(fp, fb)| self.ni_retarget_pos(r.root, node, fp, fb));
2503 if let Some(m) = self.node_iters.get_mut(&k) {
2504 m.reference = nr;
2505 m.before = nb;
2506 m.in_flight = nf;
2507 }
2508 }
2509 }
2510
2511 fn range_prune(&mut self) {
2513 if self.ranges.len() >= 64 && self.ranges.len().is_power_of_two() {
2514 self.ranges.retain(|_, r| r.obj.strong_count() > 0);
2515 }
2516 }
2517
2518 #[inline]
2520 fn live_ranges(&mut self) -> bool {
2521 if self.ranges.is_empty() {
2522 return false;
2523 }
2524 self.ranges.retain(|_, r| r.obj.strong_count() > 0);
2525 !self.ranges.is_empty()
2526 }
2527
2528 pub fn ranges_node_removed(&mut self, node: usize, parent: usize, index: usize) {
2530 self.iters_pre_remove(node);
2531 if !self.live_ranges() {
2532 return;
2533 }
2534 let keys: Vec<u32> = self.ranges.keys().copied().collect();
2535 for k in keys {
2536 let Some(r) = self.ranges.get(&k).cloned() else { continue };
2537 let (mut sc, mut so, mut ec, mut eo) = (r.sc, r.so, r.ec, r.eo);
2538 if sc != MAIN_DOC && self.range_inclusive_descendant(sc, node) {
2539 sc = parent;
2540 so = index;
2541 } else if sc == parent && so > index {
2542 so -= 1;
2543 }
2544 if ec != MAIN_DOC && self.range_inclusive_descendant(ec, node) {
2545 ec = parent;
2546 eo = index;
2547 } else if ec == parent && eo > index {
2548 eo -= 1;
2549 }
2550 if let Some(m) = self.ranges.get_mut(&k) {
2551 m.sc = sc;
2552 m.so = so;
2553 m.ec = ec;
2554 m.eo = eo;
2555 }
2556 }
2557 }
2558
2559 pub fn ranges_children_cleared(&mut self, parent: usize, kids: &[usize]) {
2561 if !self.live_ranges() {
2562 if !self.node_iters.is_empty() {
2563 for &k in kids {
2564 self.iters_pre_remove(k);
2565 }
2566 }
2567 return;
2568 }
2569 for &k in kids {
2570 self.ranges_node_removed(k, parent, 0);
2571 }
2572 }
2573
2574 pub fn ranges_inserted(&mut self, parent: usize, index: usize, count: usize) {
2576 if !self.live_ranges() {
2577 return;
2578 }
2579 for r in self.ranges.values_mut() {
2580 if r.sc == parent && r.so > index {
2581 r.so += count;
2582 }
2583 if r.ec == parent && r.eo > index {
2584 r.eo += count;
2585 }
2586 }
2587 }
2588
2589 pub fn ranges_replace_data(&mut self, node: usize, offset: usize, count: usize, new_len: usize) {
2591 if !self.live_ranges() {
2592 return;
2593 }
2594 for r in self.ranges.values_mut() {
2595 if r.sc == node {
2596 if r.so > offset && r.so <= offset + count {
2597 r.so = offset;
2598 } else if r.so > offset + count {
2599 r.so = r.so + new_len - count;
2600 }
2601 }
2602 if r.ec == node {
2603 if r.eo > offset && r.eo <= offset + count {
2604 r.eo = offset;
2605 } else if r.eo > offset + count {
2606 r.eo = r.eo + new_len - count;
2607 }
2608 }
2609 }
2610 }
2611
2612 pub fn ranges_split(&mut self, node: usize, new_node: usize, parent: Option<usize>, offset: usize) {
2614 if parent.is_none() || !self.live_ranges() {
2615 return;
2616 }
2617 let index = parent.and_then(|p| self.nodes.get(p)).and_then(|p| p.children.iter().position(|&c| c == node));
2618 for r in self.ranges.values_mut() {
2619 if r.sc == node && r.so > offset {
2620 r.sc = new_node;
2621 r.so -= offset;
2622 } else if parent.is_some() && r.sc == parent.unwrap_or(0) && index.is_some_and(|i| r.so == i + 1) {
2623 r.so += 1;
2624 }
2625 if r.ec == node && r.eo > offset {
2626 r.ec = new_node;
2627 r.eo -= offset;
2628 } else if parent.is_some() && r.ec == parent.unwrap_or(0) && index.is_some_and(|i| r.eo == i + 1) {
2629 r.eo += 1;
2630 }
2631 }
2632 }
2633
2634 pub fn ranges_normalize_merge(&mut self, node: usize, cur: usize, parent: usize, index: usize, length: usize) {
2636 if !self.live_ranges() {
2637 return;
2638 }
2639 for r in self.ranges.values_mut() {
2640 if r.sc == cur {
2641 r.sc = node;
2642 r.so += length;
2643 } else if r.sc == parent && r.so == index {
2644 r.sc = node;
2645 r.so = length;
2646 }
2647 if r.ec == cur {
2648 r.ec = node;
2649 r.eo += length;
2650 } else if r.ec == parent && r.eo == index {
2651 r.ec = node;
2652 r.eo = length;
2653 }
2654 }
2655 }
2656
2657 pub fn set_main_doctype(&mut self, name: &str, public_id: &str, system_id: &str) {
2659 let d = self.create_doctype(name, public_id, system_id);
2660 self.main_doctype = Some(d);
2661 }
2662
2663 pub fn range_register(&mut self, obj: &crate::os_lib::ecma::value::ObjRef, node: usize) -> u32 {
2665 self.range_prune();
2666 let id = self.next_range_id;
2667 self.next_range_id = self.next_range_id.wrapping_add(1).max(1);
2668 self.ranges.insert(id, RangeRec { obj: alloc::rc::Rc::downgrade(obj), sc: node, so: 0, ec: node, eo: 0 });
2669 id
2670 }
2671
2672 pub fn replace_data(&mut self, idx: usize, offset: usize, count: usize, new_len: usize, new_text: &str) {
2674 self.suppress_range_hook = true;
2675 self.set_text_content(idx, new_text);
2676 self.suppress_range_hook = false;
2677 self.ranges_replace_data(idx, offset, count, new_len);
2678 }
2679
2680 pub fn create_document_node(&mut self, ctype: &str, html: bool) -> usize {
2689 let idx = self.nodes.len();
2690 let mut attrs = BTreeMap::new();
2691 attrs.insert(String::from("_ctype"), ctype.to_string());
2692 if html {
2693 attrs.insert(String::from("_html"), String::from("1"));
2694 }
2695 self.nodes.push(DomNode {
2696 tag: String::from("#document"),
2697 is_text: false,
2698 id: String::new(),
2699 classes: Vec::new(),
2700 style: BTreeMap::new(),
2701 attrs,
2702 text_override: None,
2703 initial_text: String::new(),
2704 parent: None,
2705 children: Vec::new(),
2706 classes_dirty: false,
2707 style_dirty: false,
2708 });
2709 self.extra_docs += 1;
2710 idx
2711 }
2712
2713 #[inline]
2715 pub fn is_doc_node(&self, idx: usize) -> bool {
2716 self.extra_docs > 0 && self.nodes.get(idx).is_some_and(|n| n.tag == "#document")
2717 }
2718
2719 pub fn doc_is_html(&self, doc: Option<usize>) -> bool {
2721 match doc {
2722 None => true,
2723 Some(d) => self.nodes.get(d).is_some_and(|n| n.attrs.contains_key("_html")),
2724 }
2725 }
2726
2727 #[inline]
2729 pub fn node_document(&self, idx: usize) -> Option<usize> {
2730 if self.extra_docs == 0 {
2731 return None;
2732 }
2733 if self.is_doc_node(idx) {
2734 return Some(idx);
2735 }
2736 self.node_doc.get(&idx).copied()
2737 }
2738
2739 pub fn root_of(&self, mut idx: usize) -> usize {
2741 let mut guard = 0;
2742 while let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
2743 idx = p;
2744 guard += 1;
2745 if guard > self.nodes.len() + 64 {
2746 break;
2747 }
2748 }
2749 idx
2750 }
2751
2752 pub fn set_owner_subtree(&mut self, idx: usize, doc: Option<usize>) {
2754 let html = self.doc_is_html(doc);
2755 let mut stack: Vec<usize> = alloc::vec![idx];
2756 let mut guard = 0usize;
2757 while let Some(i) = stack.pop() {
2758 guard += 1;
2759 if guard > self.nodes.len() + 8 {
2760 break;
2761 }
2762 match doc {
2763 Some(d) => {
2764 self.node_doc.insert(i, d);
2765 }
2766 None => {
2767 self.node_doc.remove(&i);
2768 }
2769 }
2770 let shadow = self.shadow_tree.get_by_host(i).map(|d| d.root_node_idx);
2771 let Some(n) = self.nodes.get_mut(i) else { continue };
2772 if !n.is_text && !n.tag.starts_with('#') {
2773 if html {
2774 n.attrs.remove("_xml");
2775 } else {
2776 n.attrs.insert(String::from("_xml"), String::from("1"));
2777 }
2778 }
2779 stack.extend(n.children.iter().copied());
2780 if let Some(f) = n.attrs.get("_content_frag").and_then(|s| s.parse::<usize>().ok()) {
2781 stack.push(f);
2782 }
2783 if let Some(r) = shadow {
2784 stack.push(r);
2785 }
2786 }
2787 }
2788
2789 #[inline]
2791 pub fn inherit_owner(&mut self, idx: usize, from: usize) {
2792 if self.extra_docs == 0 {
2793 return;
2794 }
2795 if let Some(d) = self.node_document(from) {
2796 self.set_owner_subtree(idx, Some(d));
2797 }
2798 }
2799
2800 fn sync_owner_on_insert(&mut self, parent: usize, kids: &[usize]) {
2802 let target = self.node_document(parent);
2803 for &k in kids {
2804 if self.node_document(k) != target {
2805 self.set_owner_subtree(k, target);
2806 }
2807 }
2808 }
2809
2810 pub fn attach_shadow(
2812 &mut self,
2813 host_idx: usize,
2814 mode: crate::os_lib::shadow_dom::ShadowRootMode,
2815 ) -> Result<usize, crate::os_lib::shadow_dom::AttachShadowError> {
2816 let tag = match self.nodes.get(host_idx) {
2817 Some(n) if !n.is_text => n.tag.clone(),
2818 _ => return Err(crate::os_lib::shadow_dom::AttachShadowError::DisallowedTag),
2819 };
2820 let root_idx = self.new_element_node("#shadow-root");
2822 self.shadow_tree.attach_shadow(host_idx, &tag, mode, root_idx)?;
2823 if self.extra_docs > 0 {
2824 if let Some(doc_idx) = self.node_document(host_idx) {
2825 self.set_owner_subtree(root_idx, Some(doc_idx));
2826 }
2827 }
2828 self.structural_dirty = true;
2829 Self::count_relayout_request();
2830 self.note_dirty_cause("attachShadow");
2831 self.dirty = true;
2832 Ok(root_idx)
2833 }
2834
2835 pub fn get_shadow_root(&self, host_idx: usize) -> Option<usize> {
2837 self.shadow_tree
2838 .get_by_host(host_idx)
2839 .filter(|d| d.is_accessible_via_element())
2840 .map(|d| d.root_node_idx)
2841 }
2842
2843 pub fn create_contextual_fragment(&mut self, context_node_idx: Option<usize>, html: &str) -> usize {
2845 let mut context_tag = alloc::string::String::from("div");
2846 if let Some(idx) = context_node_idx {
2847 if let Some(node) = self.nodes.get(idx) {
2848 if node.is_text {
2849 if let Some(p) = node.parent {
2850 if let Some(pn) = self.nodes.get(p) {
2851 if !pn.is_text && !pn.tag.starts_with('#') {
2852 context_tag = pn.tag.clone();
2853 }
2854 }
2855 }
2856 } else if !node.tag.starts_with('#') {
2857 context_tag = node.tag.clone();
2858 }
2859 }
2860 }
2861
2862 let (wrapped, depth) = crate::os_lib::dom_fragment::context_wrapper(&context_tag, html);
2863 let root = crate::os_lib::dom::parse_html_app_flat(&wrapped);
2864 let frag_idx = self.create_document_fragment();
2865 let children = crate::os_lib::dom_fragment::extract_fragment_children(&root, depth);
2866
2867 let mut imported_children = Vec::new();
2868 for child in children {
2869 let ci = self.import_node(child);
2870 self.nodes[ci].parent = Some(frag_idx);
2871 imported_children.push(ci);
2872 }
2873 self.nodes[frag_idx].children = imported_children;
2874 frag_idx
2875 }
2876
2877 pub fn template_content(&mut self, idx: usize) -> usize {
2886 if let Some(f) = self
2887 .get_attr(idx, "_content_frag")
2888 .or_else(|| self.get_attr(idx, "_template_content_idx"))
2889 .and_then(|s| s.parse::<usize>().ok())
2890 {
2891 let fs = f.to_string();
2892 self.set_attr(idx, "_content_frag", &fs);
2893 self.set_attr(idx, "_template_content_idx", &fs);
2894 return f;
2895 }
2896 let owner_doc = self.node_document(idx);
2897 let tmpl_doc = match self.template_owner_docs.get(&owner_doc).copied() {
2898 Some(d) => d,
2899 None => {
2900 let d = self.create_document_node("text/html", true);
2901 self.template_owner_docs.insert(owner_doc, d);
2902 d
2903 }
2904 };
2905 let f = self.create_document_fragment();
2906 let kids = core::mem::take(&mut self.nodes[idx].children);
2907 for &k in &kids {
2908 self.nodes[k].parent = Some(f);
2909 }
2910 self.nodes[f].children = kids;
2911 self.set_owner_subtree(f, Some(tmpl_doc));
2912 let fs = f.to_string();
2913 self.set_attr(idx, "_content_frag", &fs);
2914 self.set_attr(idx, "_template_content_idx", &fs);
2915 f
2916 }
2917
2918 fn expand_fragment(&mut self, child: usize) -> Vec<usize> {
2922 if self.nodes.get(child).map(|n| matches!(n.tag.as_str(), "#fragment" | "#document-fragment" | "#shadow-root")).unwrap_or(false) {
2923 let kids = core::mem::take(&mut self.nodes[child].children);
2924 if !self.ranges.is_empty() {
2925 for &k in &kids {
2927 self.nodes[k].parent = Some(child);
2928 }
2929 self.ranges_children_cleared(child, &kids);
2930 }
2931 for &k in &kids {
2932 self.nodes[k].parent = None;
2933 }
2934 kids
2935 } else {
2936 alloc::vec![child]
2937 }
2938 }
2939
2940 pub fn append_child(&mut self, parent: usize, child: usize) {
2943 if parent >= self.nodes.len() || child >= self.nodes.len() || parent == child {
2944 return;
2945 }
2946 let kids = self.expand_fragment(child);
2947 if kids.is_empty() {
2948 return;
2949 }
2950 let any_kid_was_attached = kids.iter().any(|&k| self.is_attached(k));
2951 for &k in &kids {
2952 self.detach_with_notify(k);
2953 }
2954 let prev_sib = self.nodes[parent].children.last().copied();
2955 for &k in &kids {
2956 self.nodes[k].parent = Some(parent);
2957 self.nodes[parent].children.push(k);
2958 }
2959 if self.extra_docs > 0 {
2960 self.sync_owner_on_insert(parent, &kids);
2961 }
2962 if self.is_attached(parent) || any_kid_was_attached {
2963 self.mark_structural_dirty_for("appendChild");
2964 }
2965 self.queue_post_connection(Some(parent), &kids);
2966 self.notify_child_list_sib(parent, kids, Vec::new(), prev_sib, None);
2967 }
2968
2969 pub fn replace_children(&mut self, parent: usize, new_child: Option<usize>) {
2971 if parent >= self.nodes.len() {
2972 return;
2973 }
2974 let kids = match new_child {
2975 Some(c) if c < self.nodes.len() && c != parent => self.expand_fragment(c),
2976 _ => Vec::new(),
2977 };
2978 for &k in &kids {
2979 if self.nodes.get(k).and_then(|n| n.parent) != Some(parent) {
2980 self.detach_with_notify(k);
2981 }
2982 }
2983 let old: Vec<usize> = core::mem::take(&mut self.nodes[parent].children);
2984 if !old.is_empty() {
2985 self.ranges_children_cleared(parent, &old);
2986 for &c in &old {
2987 self.nodes[c].parent = None;
2988 }
2989 }
2990 for &k in &kids {
2991 self.nodes[k].parent = Some(parent);
2992 self.nodes[parent].children.push(k);
2993 }
2994 if self.extra_docs > 0 && !kids.is_empty() {
2995 self.sync_owner_on_insert(parent, &kids);
2996 }
2997 if !kids.is_empty() {
2998 self.ranges_inserted(parent, 0, kids.len());
2999 }
3000 if !old.is_empty() || !kids.is_empty() {
3001 self.queue_post_connection(Some(parent), &kids);
3002 self.notify_child_list(parent, kids, old);
3003 if self.is_attached(parent) {
3004 self.mark_structural_dirty_for("replaceChildren");
3005 }
3006 }
3007 }
3008
3009 pub fn remove_child(&mut self, parent: usize, child: usize) {
3011 let p = if parent < self.nodes.len() { Some(parent) } else { self.nodes.get(child).and_then(|n| n.parent) };
3012 let sibs = p.map(|pi| self.siblings_of_child(pi, child)).unwrap_or((None, None));
3013 let was_attached = self.is_attached(child) && self.nodes.get(child).and_then(|n| n.parent).is_some();
3014 self.detach(child);
3015 if was_attached {
3016 self.mark_structural_dirty_for("removeChild");
3017 }
3018 if let Some(p) = p {
3019 self.notify_child_list_sib(p, Vec::new(), alloc::vec![child], sibs.0, sibs.1);
3020 }
3021 }
3022 pub fn remove_node(&mut self, idx: usize) {
3023 let p = self.nodes.get(idx).and_then(|n| n.parent);
3024 let sibs = p.map(|pi| self.siblings_of_child(pi, idx)).unwrap_or((None, None));
3025 let was_attached = p.is_some() && self.is_attached(idx);
3026 self.detach(idx);
3027 if was_attached {
3028 self.mark_structural_dirty_for("remove");
3029 }
3030 if let Some(p) = p {
3031 self.notify_child_list_sib(p, Vec::new(), alloc::vec![idx], sibs.0, sibs.1);
3032 }
3033 }
3034
3035 pub fn insert_before(&mut self, parent: usize, new_child: usize, ref_child: Option<usize>) {
3040 if parent >= self.nodes.len() || new_child >= self.nodes.len() || parent == new_child {
3041 return;
3042 }
3043 let mut ref_child = ref_child;
3044 if ref_child == Some(new_child) {
3045 let sib = self.nodes[parent].children.iter().position(|&c| c == new_child).and_then(|i| self.nodes[parent].children.get(i + 1).copied());
3046 ref_child = sib;
3047 }
3048 let kids = self.expand_fragment(new_child);
3049 if kids.is_empty() {
3050 return;
3051 }
3052 let any_kid_was_attached = kids.iter().any(|&k| self.is_attached(k));
3053 for &k in &kids {
3054 self.detach_with_notify(k);
3055 }
3056 let pos = ref_child.and_then(|r| self.nodes[parent].children.iter().position(|&c| c == r));
3057 let (prev_sib, next_sib) = match pos {
3058 Some(p) => (
3059 if p > 0 { self.nodes[parent].children.get(p - 1).copied() } else { None },
3060 self.nodes[parent].children.get(p).copied(),
3061 ),
3062 None => (self.nodes[parent].children.last().copied(), None),
3063 };
3064 if let Some(p) = pos {
3065 self.ranges_inserted(parent, p, kids.len());
3066 }
3067 for (i, &k) in kids.iter().enumerate() {
3068 self.nodes[k].parent = Some(parent);
3069 match pos {
3070 Some(p) => self.nodes[parent].children.insert(p + i, k),
3071 None => self.nodes[parent].children.push(k),
3072 }
3073 }
3074 if self.extra_docs > 0 {
3075 self.sync_owner_on_insert(parent, &kids);
3076 }
3077 if self.is_attached(parent) || any_kid_was_attached {
3078 self.mark_structural_dirty_for("insertBefore");
3079 }
3080 self.queue_post_connection(Some(parent), &kids);
3081 self.notify_child_list_sib(parent, kids, Vec::new(), prev_sib, next_sib);
3082 }
3083
3084 pub fn replace_child(&mut self, parent: usize, new_child: usize, old_child: usize) {
3086 if parent >= self.nodes.len() || new_child >= self.nodes.len() || old_child >= self.nodes.len() {
3087 return;
3088 }
3089 if !self.nodes[parent].children.contains(&old_child) {
3090 return;
3091 }
3092 if new_child == old_child {
3093 if let Some(p) = self.nodes[parent].children.iter().position(|&c| c == old_child) {
3094 let prev_sib = if p > 0 { self.nodes[parent].children.get(p - 1).copied() } else { None };
3095 let next_sib = self.nodes[parent].children.get(p + 1).copied();
3096 self.ranges_node_removed(old_child, parent, p);
3097 self.ranges_inserted(parent, p, 1);
3098 self.notify_child_list_sib(
3099 parent,
3100 Vec::new(),
3101 alloc::vec![old_child],
3102 prev_sib,
3103 next_sib,
3104 );
3105 self.notify_child_list_sib(
3106 parent,
3107 alloc::vec![old_child],
3108 Vec::new(),
3109 prev_sib,
3110 next_sib,
3111 );
3112 }
3113 return;
3114 }
3115 let kids = self.expand_fragment(new_child);
3116 let new_was_attached = kids.iter().any(|&k| self.is_attached(k));
3117 for &k in &kids {
3118 self.detach_with_notify(k); }
3120 if let Some(p) = self.nodes[parent].children.iter().position(|&c| c == old_child) {
3121 let prev_sib = if p > 0 { self.nodes[parent].children.get(p - 1).copied() } else { None };
3122 let next_sib = self.nodes[parent].children.get(p + 1).copied();
3123 self.ranges_node_removed(old_child, parent, p);
3124 if p + 1 < self.nodes[parent].children.len() {
3125 self.ranges_inserted(parent, p, kids.len());
3126 }
3127 self.nodes[old_child].parent = None;
3128 for &k in &kids {
3129 self.nodes[k].parent = Some(parent);
3130 }
3131 self.nodes[parent].children.splice(p..p + 1, kids.iter().copied());
3132 if self.extra_docs > 0 {
3133 self.sync_owner_on_insert(parent, &kids);
3134 }
3135 if self.is_attached(parent) || new_was_attached {
3136 self.mark_structural_dirty_for("replaceChild");
3137 }
3138 self.queue_post_connection(Some(parent), &kids);
3139 self.notify_child_list_sib(parent, kids, alloc::vec![old_child], prev_sib, next_sib);
3140 }
3141 }
3142
3143 pub fn clone_node(&mut self, idx: usize, deep: bool) -> usize {
3145 let c = self.clone_node_inner(idx, deep);
3146 if c != idx {
3147 self.inherit_owner(c, idx);
3148 }
3149 if c != idx && !self.custom_elements.is_empty() {
3150 self.ce_queue.push(CeEvent::Created(c));
3151 }
3152 c
3153 }
3154
3155 fn clone_node_inner(&mut self, idx: usize, deep: bool) -> usize {
3156 if idx >= self.nodes.len() {
3157 return idx;
3158 }
3159 let (is_text, tag, id, classes, style, attrs, text_override, initial_text, children) = {
3160 let n = &self.nodes[idx];
3161 (
3162 n.is_text,
3163 n.tag.clone(),
3164 n.id.clone(),
3165 n.classes.clone(),
3166 n.style.clone(),
3167 n.attrs.clone(),
3168 n.text_override.clone(),
3169 n.initial_text.clone(),
3170 n.children.clone(),
3171 )
3172 };
3173 let new_idx = self.nodes.len();
3174 if !self.attr_order.is_empty() {
3175 if let Some(o) = self.attr_order.get(&idx).cloned() {
3176 self.attr_order.insert(new_idx, o);
3177 }
3178 }
3179 if !self.ns_attrs.is_empty() {
3180 if let Some(ns) = self.ns_attrs.get(&idx).cloned() {
3181 self.ns_attrs.insert(new_idx, ns);
3182 }
3183 }
3184 if !self.attr_ns_order.is_empty() {
3185 if let Some(ord) = self.attr_ns_order.get(&idx).cloned() {
3186 self.attr_ns_order.insert(new_idx, ord);
3187 }
3188 }
3189 self.nodes.push(DomNode {
3190 tag,
3191 is_text,
3192 id,
3193 classes,
3194 style,
3195 attrs,
3196 text_override,
3197 initial_text,
3198 parent: None,
3199 children: Vec::new(),
3200 classes_dirty: false,
3201 style_dirty: false,
3202 });
3203 if deep && !is_text {
3204 for c in children {
3205 let cc = self.clone_node_inner(c, true);
3206 self.nodes[cc].parent = Some(new_idx);
3207 self.nodes[new_idx].children.push(cc);
3208 }
3209 }
3210 let frag_attr = self.nodes[new_idx]
3220 .attrs
3221 .get("_template_content_idx")
3222 .or_else(|| self.nodes[new_idx].attrs.get("_content_frag"))
3223 .cloned();
3224 if let Some(frag_idx) = frag_attr.and_then(|s| s.parse::<usize>().ok()) {
3225 let new_frag = self.clone_node_inner(frag_idx, true);
3226 let new_frag_str = new_frag.to_string();
3227 self.nodes[new_idx]
3228 .attrs
3229 .insert("_template_content_idx".to_string(), new_frag_str.clone());
3230 self.nodes[new_idx]
3231 .attrs
3232 .insert("_content_frag".to_string(), new_frag_str);
3233 }
3234 new_idx
3236 }
3237
3238 fn subtree_contains(&self, root: usize, target: usize) -> bool {
3240 let mut cur = Some(target);
3241 let mut guard = 0;
3242 while let Some(c) = cur {
3243 if c == root {
3244 return true;
3245 }
3246 guard += 1;
3247 if guard > self.nodes.len() + 1 {
3248 break;
3249 }
3250 cur = self.nodes.get(c).and_then(|n| n.parent);
3251 }
3252 false
3253 }
3254
3255 fn detach(&mut self, idx: usize) {
3256 if idx >= self.nodes.len() {
3257 return;
3258 }
3259 if self.focused_idx.is_some_and(|f| self.subtree_contains(idx, f)) {
3260 self.focused_idx = None;
3261 }
3262 if let Some(p) = self.nodes[idx].parent {
3263 if let Some(pos) = self.nodes[p].children.iter().position(|&c| c == idx) {
3264 self.ranges_node_removed(idx, p, pos);
3265 self.nodes[p].children.remove(pos);
3266 }
3267 }
3268 self.nodes[idx].parent = None;
3269 }
3270
3271 pub fn move_before(&mut self, parent: usize, new_child: usize, ref_child: Option<usize>) {
3272 let saved_focus = self.focused_idx;
3273 let queued = self.pending_post_connection.len();
3274 self.insert_before(parent, new_child, ref_child);
3275 self.focused_idx = saved_focus;
3276 for i in self.pending_post_connection.split_off(queued) {
3278 self.frames_pending_setup.remove(&i);
3279 }
3280 }
3281
3282 pub fn insert_adjacent_node(&mut self, idx: usize, position: &str, node: usize) {
3284 match position {
3285 "beforeend" => self.append_child(idx, node),
3286 "afterbegin" => {
3287 let first = self
3288 .nodes
3289 .get(idx)
3290 .and_then(|n| n.children.first().copied());
3291 self.insert_before(idx, node, first);
3292 }
3293 "beforebegin" => {
3294 if let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
3295 self.insert_before(p, node, Some(idx));
3296 }
3297 }
3298 "afterend" => {
3299 if let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
3300 let next = self.nodes.get(p).and_then(|n| {
3301 n.children
3302 .iter()
3303 .position(|&c| c == idx)
3304 .and_then(|i| n.children.get(i + 1).copied())
3305 });
3306 self.insert_before(p, node, next);
3307 }
3308 }
3309 _ => {}
3310 }
3311 }
3312
3313 pub fn insert_adjacent_html(&mut self, idx: usize, position: &str, html: &str) {
3315 let root = crate::os_lib::dom::parse_html_app_flat(html);
3316 let imported: Vec<usize> = root.children.iter().map(|c| self.import_node(c)).collect();
3317 if position == "afterbegin" {
3318 let first = self
3320 .nodes
3321 .get(idx)
3322 .and_then(|n| n.children.first().copied());
3323 for node in imported {
3324 self.insert_before(idx, node, first);
3325 }
3326 } else {
3327 for node in imported {
3328 self.insert_adjacent_node(idx, position, node);
3329 }
3330 }
3331 self.mark_structural_dirty_for("insertAdjacentHTML");
3332 }
3333
3334 pub fn attr_affects_layout(&self, idx: usize, name: &str) -> bool {
3336 let lower = name.to_ascii_lowercase();
3337 let is_intrinsic = matches!(
3339 lower.as_str(),
3340 "id"
3341 | "class"
3342 | "style"
3343 | "hidden"
3344 | "open"
3345 | "src"
3346 | "srcset"
3347 | "href"
3348 | "rel"
3349 | "type"
3350 | "value"
3351 | "checked"
3352 | "selected"
3353 | "disabled"
3354 | "placeholder"
3355 | "width"
3356 | "height"
3357 | "cols"
3358 | "rows"
3359 | "size"
3360 | "colspan"
3361 | "rowspan"
3362 | "span"
3363 | "dir"
3364 | "lang"
3365 | "poster"
3366 | "controls"
3367 | "Reversed"
3368 | "reversed"
3369 | "start"
3370 | "align"
3371 | "valign"
3372 | "bgcolor"
3373 | "color"
3374 | "border"
3375 | "cellpadding"
3376 | "cellspacing"
3377 | "viewbox"
3378 | "d"
3379 | "fill"
3380 | "stroke"
3381 | "stroke-width"
3382 | "points"
3383 | "x"
3384 | "y"
3385 | "x1"
3386 | "y1"
3387 | "x2"
3388 | "y2"
3389 | "cx"
3390 | "cy"
3391 | "r"
3392 | "rx"
3393 | "ry"
3394 | "transform"
3395 );
3396 let in_css = match &self.css_referenced_attrs {
3398 Some(set) => set.contains(&lower),
3399 None => true,
3400 };
3401 if !is_intrinsic && !in_css {
3402 return false;
3403 }
3404 if !self.is_attached(idx) {
3411 return false;
3412 }
3413 if let Some(parent) = self.nodes.get(idx).and_then(|n| n.parent) {
3414 if self.is_in_display_none_subtree(parent) && !matches!(lower.as_str(), "id" | "class" | "style" | "hidden" | "open") && !in_css {
3415 return false;
3416 }
3417 }
3418 true
3419 }
3420
3421 pub fn set_inner_html(&mut self, idx: usize, html: &str) {
3427 if idx >= self.nodes.len() || self.nodes[idx].is_text {
3428 return;
3429 }
3430 if self.nodes[idx].children.is_empty() && html.is_empty() {
3431 return;
3432 }
3433 let frag_children = if html.contains("<?") {
3434 let context = self.nodes[idx].tag.clone();
3435 crate::os_lib::dom::parse_html_fragment(&context, html)
3436 } else {
3437 crate::os_lib::dom::parse_html_app_flat(html).children
3438 };
3439 let old: Vec<usize> = self.nodes[idx].children.clone();
3441 self.ranges_children_cleared(idx, &old);
3442 for &c in &old {
3443 self.nodes[c].parent = None;
3444 }
3445 self.nodes[idx].children.clear();
3446 let mut new_children = Vec::new();
3448 for child in &frag_children {
3449 let ci = self.import_node(child);
3450 self.nodes[ci].parent = Some(idx);
3451 new_children.push(ci);
3452 }
3453 self.nodes[idx].children = new_children.clone();
3454 if self.extra_docs > 0 {
3455 for &c in &new_children {
3456 self.inherit_owner(c, idx);
3457 }
3458 }
3459 if self.is_attached(idx) {
3460 self.mark_structural_dirty_for("innerHTML");
3461 }
3462 self.queue_post_connection(Some(idx), &new_children);
3464 self.notify_child_list(idx, new_children, old);
3465 }
3466
3467 pub fn set_outer_html(&mut self, idx: usize, html: &str) {
3469 if idx >= self.nodes.len() {
3470 return;
3471 }
3472 let parent = match self.nodes[idx].parent {
3473 Some(p) => p,
3474 None => return,
3475 };
3476 let pos = match self.nodes[parent].children.iter().position(|&c| c == idx) {
3477 Some(p) => p,
3478 None => return,
3479 };
3480 let root = crate::os_lib::dom::parse_html_app_flat(html);
3481 let mut new_inserted = Vec::new();
3482 for child in &root.children {
3483 let ci = self.import_node(child);
3484 self.nodes[ci].parent = Some(parent);
3485 new_inserted.push(ci);
3486 }
3487 self.nodes[idx].parent = None;
3488 self.nodes[parent].children.remove(pos);
3489 for (i, &ci) in new_inserted.iter().enumerate() {
3490 self.nodes[parent].children.insert(pos + i, ci);
3491 }
3492 if self.is_attached(parent) {
3493 self.mark_structural_dirty_for("outerHTML");
3494 }
3495 self.queue_post_connection(None, &new_inserted);
3496 self.notify_child_list(parent, new_inserted, alloc::vec![idx]);
3497 }
3498
3499 pub fn import_node(&mut self, node: &Node) -> usize {
3501 match &node.node_type {
3502 NodeType::Text(t) => self.new_text_node(t),
3503 NodeType::Element {
3504 tag_name,
3505 attributes,
3506 classes,
3507 id,
3508 } => {
3509 let idx = self.new_element_node(tag_name);
3510 {
3511 let style = parse_inline_style(
3512 attributes.get("style").map(|s| s.as_str()).unwrap_or(""),
3513 );
3514 let (attrs, text) = Self::special_node_parts(tag_name, attributes);
3515 let n = &mut self.nodes[idx];
3516 n.tag = tag_name.clone();
3517 n.id = id.clone().unwrap_or_default();
3518 n.classes = classes.clone();
3519 n.style = style;
3520 n.attrs = attrs;
3521 if let Some(t) = text {
3522 n.initial_text = t.clone();
3523 n.text_override = Some(t);
3524 }
3525 }
3526 let mut kids = Vec::new();
3527 for c in &node.children {
3528 let ci = self.import_node(c);
3529 self.nodes[ci].parent = Some(idx);
3530 kids.push(ci);
3531 }
3532 self.nodes[idx].children = kids;
3533 self.normalize_foreign_attrs(idx);
3534 idx
3535 }
3536 }
3537 }
3538
3539 pub fn normalize_foreign_attrs(&mut self, idx: usize) {
3541 let (is_foreign, is_xml) = match self.nodes.get(idx) {
3542 Some(n) if !n.is_text && !n.tag.starts_with('#') => (
3543 matches!(n.attrs.get("#ns").map(|s| s.as_str()), Some("svg") | Some("math")),
3544 n.attrs.contains_key("_xml"),
3545 ),
3546 _ => return,
3547 };
3548 if !is_foreign && !is_xml {
3549 return;
3550 }
3551 let keys: Vec<String> = self.nodes[idx].attrs.keys().cloned().collect();
3552 let mut moved: Vec<(String, String, String, String)> = Vec::new();
3553 for k in keys {
3554 if k.starts_with('_') || k.starts_with('#') {
3555 continue;
3556 }
3557 let mapped: Option<(&str, String)> = if let Some(l) = k.strip_prefix("xlink ") {
3558 Some(("http://www.w3.org/1999/xlink", format!("xlink:{}", l)))
3559 } else if let Some(l) = k.strip_prefix("xml ") {
3560 Some(("http://www.w3.org/XML/1998/namespace", format!("xml:{}", l)))
3561 } else if let Some(l) = k.strip_prefix("xmlns ") {
3562 Some(("http://www.w3.org/2000/xmlns/", format!("xmlns:{}", l)))
3563 } else if k == "xmlns" {
3564 Some(("http://www.w3.org/2000/xmlns/", String::from("xmlns")))
3565 } else if let Some(l) = k.strip_prefix("xmlns:") {
3566 Some(("http://www.w3.org/2000/xmlns/", format!("xmlns:{}", l)))
3567 } else if let Some(l) = k.strip_prefix("xlink:") {
3568 Some(("http://www.w3.org/1999/xlink", format!("xlink:{}", l)))
3569 } else if let Some(l) = k.strip_prefix("xml:") {
3570 Some(("http://www.w3.org/XML/1998/namespace", format!("xml:{}", l)))
3571 } else {
3572 None
3573 };
3574 if let Some((ns, qn)) = mapped {
3575 if let Some(val) = self.nodes[idx].attrs.get(&k).cloned() {
3576 moved.push((k, ns.to_string(), qn, val));
3577 }
3578 }
3579 }
3580 if moved.is_empty() {
3581 return;
3582 }
3583 self.has_attr_nodes = true;
3584 for (old_k, ns, qn, val) in moved {
3585 self.nodes[idx].attrs.remove(&old_k);
3586 let list = self.ns_attrs.entry(idx).or_default();
3587 if !list.iter().any(|(a_ns, a_qn, _)| a_ns == &ns && a_qn == &qn) {
3588 list.push((ns, qn, val));
3589 }
3590 }
3591 }
3592
3593 pub fn unmark_subtree_xml(&mut self, idx: usize) {
3596 if let Some(n) = self.nodes.get_mut(idx) {
3597 n.attrs.remove("_xml");
3598 let kids = n.children.clone();
3599 for k in kids {
3600 self.unmark_subtree_xml(k);
3601 }
3602 }
3603 }
3604
3605 pub fn mark_subtree_xml(&mut self, idx: usize) {
3606 if let Some(n) = self.nodes.get_mut(idx) {
3607 n.attrs.insert("_xml".into(), "1".into());
3608 let kids = n.children.clone();
3609 self.normalize_foreign_attrs(idx);
3610 for k in kids {
3611 self.mark_subtree_xml(k);
3612 }
3613 }
3614 }
3615
3616 pub fn to_dom_node(&self) -> Node {
3619 if self.nodes.is_empty() {
3620 return Node::new_text(String::new());
3621 }
3622 self.build_node(0)
3623 }
3624
3625 pub fn tree_order(&self) -> Vec<usize> {
3629 let mut out = Vec::with_capacity(self.nodes.len());
3630 if !self.nodes.is_empty() {
3631 self.tree_order_into(0, &mut out);
3632 }
3633 out
3634 }
3635
3636 fn tree_order_into(&self, idx: usize, out: &mut Vec<usize>) {
3637 out.push(idx);
3638 if self.has_shells {
3639 let mut v = Vec::new();
3640 self.flat_kids(idx, &mut v);
3641 for c in v {
3642 self.tree_order_into(c, out);
3643 }
3644 return;
3645 }
3646 for &c in &self.nodes[idx].children {
3647 self.tree_order_into(c, out);
3648 }
3649 }
3650
3651 fn build_node(&self, idx: usize) -> Node {
3652 let n = &self.nodes[idx];
3653 if n.is_text {
3654 let mut node = Node::new_text(
3655 n.text_override
3656 .clone()
3657 .unwrap_or_else(|| n.initial_text.clone()),
3658 );
3659 node.node_idx = Some(idx);
3660 return node;
3661 }
3662 let mut attrs = n.attrs.clone();
3663 attrs.remove("_ns");
3666 attrs.remove("_qname");
3667 attrs.remove("_prefix");
3668 let id = if n.id.is_empty() {
3669 let gen_id = alloc::format!("_node_idx_{}", idx);
3670 attrs.insert("id".to_string(), gen_id.clone());
3671 Some(gen_id)
3672 } else {
3673 attrs.insert("id".to_string(), n.id.clone());
3674 Some(n.id.clone())
3675 };
3676 if n.classes.is_empty() {
3677 attrs.remove("class");
3678 } else {
3679 attrs.insert("class".to_string(), n.classes.join(" "));
3680 }
3681 if n.style.is_empty() {
3682 attrs.remove("style");
3683 } else {
3684 attrs.insert("style".to_string(), serialize_inline_style(&n.style));
3685 }
3686 let mut node = Node::new_element_direct(n.tag.clone(), attrs, id, n.classes.clone());
3687 node.node_idx = Some(idx);
3688 node.children.reserve(n.children.len());
3689 let flat: Vec<usize>;
3690 let kids: &[usize] = if self.has_shells {
3691 let mut v = Vec::new();
3692 self.flat_kids(idx, &mut v);
3693 flat = v;
3694 &flat
3695 } else {
3696 &n.children
3697 };
3698 for &c in kids {
3699 if bridge_poll() {
3702 break;
3703 }
3704 node.children.push(self.build_node(c));
3705 }
3706 node.update_dependent_hashes();
3707 node
3708 }
3709
3710 pub fn get_text_content(&self, idx: usize) -> String {
3712 if idx >= self.nodes.len() {
3713 return String::new();
3714 }
3715 self.collect_text(idx)
3716 }
3717
3718 fn descendant_text_nodes(&self, idx: usize) -> Vec<usize> {
3719 let mut out = Vec::new();
3720 self.descendant_text_into(idx, &mut out);
3721 out
3722 }
3723 fn descendant_text_into(&self, idx: usize, out: &mut Vec<usize>) {
3724 let node = &self.nodes[idx];
3725 if node.is_text {
3726 out.push(idx);
3727 return;
3728 }
3729 for &c in &node.children {
3730 self.descendant_text_into(c, out);
3731 }
3732 }
3733
3734 pub fn set_style(&mut self, idx: usize, prop: &str, val: &str) {
3739 let key = css_prop_from_camel(prop);
3740 let (old_value, changed, had_attr) = {
3741 let Some(n) = self.nodes.get_mut(idx) else {
3742 return;
3743 };
3744 let old_value = serialize_inline_style(&n.style);
3745 let changed = if val.is_empty() {
3746 n.style.remove(&key).is_some()
3747 } else {
3748 n.style.insert(key.clone(), val.to_string()).as_deref() != Some(val)
3749 };
3750 let style_str = serialize_inline_style(&n.style);
3751 let had_attr = n.attrs.contains_key("style");
3752 n.attrs.insert(String::from("style"), style_str);
3753 if changed {
3754 n.style_dirty = true;
3755 }
3756 (old_value, changed, had_attr)
3757 };
3758 if !had_attr {
3759 self.attr_order_push(idx, "style");
3760 }
3761 if changed && self.is_attached(idx) && !(key != "display" && self.is_in_display_none_subtree(idx)) {
3768 self.dirty = true;
3769 Self::count_relayout_request();
3770 if let Some(pos) = self.pending_style_updates.iter().position(|(i, k, _)| *i == idx && k == &key) {
3771 self.pending_style_updates[pos].2 = val.to_string();
3772 } else {
3773 let cause = alloc::format!("style:{}", key);
3774 self.note_dirty_cause(&cause);
3775 self.pending_style_updates.push((idx, key, val.to_string()));
3776 }
3777 }
3778 self.notify_attribute(idx, "style", Some(&old_value));
3779 }
3780
3781 pub fn get_style(&self, idx: usize, prop: &str) -> String {
3782 let raw = self
3783 .nodes
3784 .get(idx)
3785 .and_then(|n| n.style.get(&css_prop_from_camel(prop)).cloned())
3786 .unwrap_or_default();
3787 strip_style_priority(&raw).0.to_string()
3788 }
3789
3790 pub fn get_style_priority(&self, idx: usize, prop: &str) -> String {
3795 let raw = self
3796 .nodes
3797 .get(idx)
3798 .and_then(|n| n.style.get(&css_prop_from_camel(prop)).cloned())
3799 .unwrap_or_default();
3800 if strip_style_priority(&raw).1 {
3801 "important".to_string()
3802 } else {
3803 String::new()
3804 }
3805 }
3806
3807 pub fn get_css_text(&self, idx: usize) -> String {
3812 self.nodes
3813 .get(idx)
3814 .map(|n| serialize_inline_style(&n.style))
3815 .unwrap_or_default()
3816 }
3817 pub fn set_css_text(&mut self, idx: usize, text: &str) {
3821 let (old_value, changed, had_attr) = {
3822 let Some(n) = self.nodes.get_mut(idx) else {
3823 return;
3824 };
3825 let old_value = serialize_inline_style(&n.style);
3826 n.style = parse_inline_style(text);
3827 let new_value = serialize_inline_style(&n.style);
3828 let changed = new_value != old_value;
3829 let had_attr = n.attrs.contains_key("style");
3830 n.attrs.insert(String::from("style"), new_value);
3831 if changed {
3832 n.style_dirty = true;
3833 }
3834 (old_value, changed, had_attr)
3835 };
3836 if !had_attr {
3837 self.attr_order_push(idx, "style");
3838 }
3839 if changed && self.is_attached(idx) {
3840 self.mark_structural_dirty_for("cssText");
3841 }
3842 self.notify_attribute(idx, "style", Some(&old_value));
3843 }
3844
3845 pub fn outline(&self, max: usize) -> Vec<String> {
3848 let mut out = Vec::new();
3849 let mut stack: Vec<(usize, usize)> = self
3850 .nodes
3851 .iter()
3852 .enumerate()
3853 .filter(|(_, n)| n.parent.is_none() && !n.is_text)
3854 .map(|(i, _)| (i, 0))
3855 .rev()
3856 .collect();
3857 while let Some((idx, depth)) = stack.pop() {
3858 if out.len() >= max {
3859 break;
3860 }
3861 let Some(n) = self.nodes.get(idx) else { continue };
3862 if n.is_text {
3863 continue;
3864 }
3865 let mut line = String::new();
3866 for _ in 0..depth.min(30) {
3867 line.push(' ');
3868 }
3869 line.push_str(&n.tag);
3870 if !n.id.is_empty() {
3871 line.push('#');
3872 line.push_str(&n.id);
3873 }
3874 for c in n.classes.iter().take(3) {
3875 line.push('.');
3876 line.push_str(c);
3877 }
3878 if !n.style.is_empty() {
3879 line.push_str(" [");
3880 for (k, v) in n.style.iter().take(4) {
3881 line.push_str(k);
3882 line.push(':');
3883 line.extend(v.chars().take(70));
3884 line.push(';');
3885 }
3886 line.push(']');
3887 }
3888 if let Some(src) = n.attrs.get("src") {
3889 line.push_str(" src=");
3890 line.extend(src.chars().take(60));
3891 }
3892 let text: String = n
3894 .children
3895 .iter()
3896 .filter_map(|&c| self.nodes.get(c))
3897 .filter(|c| c.is_text)
3898 .map(|c| c.text_override.as_deref().unwrap_or(&c.initial_text))
3899 .collect::<Vec<_>>()
3900 .join("");
3901 let text = n.text_override.as_deref().filter(|t| !t.is_empty()).unwrap_or(text.as_str()).trim();
3902 if !text.is_empty() && n.tag != "script" && n.tag != "style" {
3903 line.push_str(" \"");
3904 line.extend(text.chars().take(80));
3905 line.push('"');
3906 }
3907 out.push(line);
3908 for &c in n.children.iter().rev() {
3909 stack.push((c, depth + 1));
3910 }
3911 }
3912 out
3913 }
3914
3915 pub fn get_outer_html(&self, idx: usize) -> String {
3919 let mut out = String::new();
3920 self.serialize_node_html(idx, &mut out);
3921 out
3922 }
3923 pub fn get_inner_html(&self, idx: usize) -> String {
3928 let mut out = String::new();
3929 if let Some(n) = self.nodes.get(idx) {
3930 for &c in &n.children {
3931 self.serialize_node_html(c, &mut out);
3932 }
3933 }
3934 out
3935 }
3936 fn serialize_node_html(&self, idx: usize, out: &mut String) {
3937 let Some(n) = self.nodes.get(idx) else { return };
3938 if n.is_text {
3939 let text = n.text_override.as_deref().unwrap_or(&n.initial_text);
3940 let raw_parent = n
3943 .parent
3944 .and_then(|p| self.nodes.get(p))
3945 .is_some_and(|p| crate::os_lib::dom::serializer::is_raw_text_element(p.tag.as_str(), true));
3946 if raw_parent {
3947 out.push_str(text);
3948 } else {
3949 crate::os_lib::dom::serializer::escape_text(text, out);
3950 }
3951 return;
3952 }
3953 if n.tag == "#doctype" {
3954 out.push_str("<!DOCTYPE ");
3955 out.push_str(n.attrs.get("_name").map(|s| s.as_str()).unwrap_or(""));
3956 out.push('>');
3957 return;
3958 }
3959 if n.tag == "#pi" {
3960 out.push_str("<?");
3961 out.push_str(n.attrs.get("_target").map(|s| s.as_str()).unwrap_or(""));
3962 out.push(' ');
3963 out.push_str(n.text_override.as_deref().unwrap_or(&n.initial_text));
3964 out.push('>');
3965 return;
3966 }
3967 if n.tag == "#comment" {
3968 out.push_str("<!--");
3969 out.push_str(n.text_override.as_deref().unwrap_or(&n.initial_text));
3970 out.push_str("-->");
3971 return;
3972 }
3973 if n.tag == "#document" {
3974 for &c in &n.children {
3975 self.serialize_node_html(c, out);
3976 }
3977 return;
3978 }
3979 out.push('<');
3980 out.push_str(&n.tag);
3981 if !n.id.is_empty() {
3982 out.push_str(&format!(" id=\"{}\"", html_escape_attr(&n.id)));
3983 }
3984 if !n.classes.is_empty() {
3985 out.push_str(&format!(" class=\"{}\"", html_escape_attr(&n.classes.join(" "))));
3986 }
3987 if !n.style.is_empty() {
3988 out.push_str(&format!(
3989 " style=\"{}\"",
3990 html_escape_attr(&serialize_inline_style(&n.style))
3991 ));
3992 }
3993 for (k, v) in &n.attrs {
4001 if k == "id" || k == "class" || k == "style" || k.starts_with('_') {
4002 continue;
4003 }
4004 out.push(' ');
4005 out.push_str(k);
4006 out.push_str("=\"");
4007 out.push_str(&html_escape_attr(v));
4008 out.push('"');
4009 }
4010 out.push('>');
4011 if crate::os_lib::dom::serializer::is_void_element(n.tag.as_str()) {
4013 return;
4014 }
4015 for &c in &n.children {
4016 self.serialize_node_html(c, out);
4017 }
4018 out.push_str("</");
4019 out.push_str(&n.tag);
4020 out.push('>');
4021 }
4022
4023 pub fn class_add(&mut self, idx: usize, cls: &str) {
4028 if self.nodes.get(idx).is_some_and(|n| !n.attrs.contains_key("class") && !n.classes.iter().any(|c| c == cls)) {
4029 self.attr_order_push(idx, "class");
4030 }
4031 let old_value = {
4032 let Some(n) = self.nodes.get_mut(idx) else {
4033 return;
4034 };
4035 if n.classes.iter().any(|c| c == cls) {
4036 return;
4037 };
4038 let old_value = if n.classes.is_empty() && !n.attrs.contains_key("class") { None } else { Some(n.classes.join(" ")) };
4040 n.classes.push(cls.to_string());
4041 n.classes_dirty = true;
4042 n.attrs.insert(String::from("class"), n.classes.join(" "));
4043 old_value
4044 };
4045 if self.is_attached(idx) {
4046 self.mark_structural_dirty_for("class");
4047 }
4048 self.notify_attribute(idx, "class", old_value.as_deref());
4049 }
4050 pub fn class_remove(&mut self, idx: usize, cls: &str) {
4051 let old_value = {
4052 let Some(n) = self.nodes.get_mut(idx) else {
4053 return;
4054 };
4055 let before = n.classes.len();
4056 let old_value = if n.classes.is_empty() && !n.attrs.contains_key("class") { None } else { Some(n.classes.join(" ")) };
4058 n.classes.retain(|c| c != cls);
4059 if n.classes.len() == before {
4060 return;
4061 }
4062 n.classes_dirty = true;
4063 n.attrs.insert(String::from("class"), n.classes.join(" "));
4064 old_value
4065 };
4066 if self.is_attached(idx) {
4067 self.mark_structural_dirty_for("class");
4068 }
4069 self.notify_attribute(idx, "class", old_value.as_deref());
4070 }
4071 pub fn class_toggle(&mut self, idx: usize, cls: &str) -> bool {
4072 if self.class_contains(idx, cls) {
4073 self.class_remove(idx, cls);
4074 false
4075 } else {
4076 self.class_add(idx, cls);
4077 true
4078 }
4079 }
4080 pub fn class_contains(&self, idx: usize, cls: &str) -> bool {
4081 self.nodes
4082 .get(idx)
4083 .map(|n| n.classes.iter().any(|c| c == cls))
4084 .unwrap_or(false)
4085 }
4086
4087 fn collect_descendant_options(&self, idx: usize, out: &mut Vec<usize>) {
4097 let Some(n) = self.nodes.get(idx) else { return };
4098 for &c in &n.children {
4099 let Some(cn) = self.nodes.get(c) else { continue };
4100 if cn.tag == "option" {
4101 out.push(c);
4102 } else {
4103 self.collect_descendant_options(c, out);
4104 }
4105 }
4106 }
4107 pub fn select_options(&self, idx: usize) -> Vec<usize> {
4111 let mut out = Vec::new();
4112 self.collect_descendant_options(idx, &mut out);
4113 out
4114 }
4115 fn option_value(&self, opt_idx: usize) -> String {
4118 self.get_attr(opt_idx, "value").unwrap_or_else(|| {
4119 self.nodes
4120 .get(opt_idx)
4121 .map(|n| n.text_override.clone().unwrap_or_else(|| n.initial_text.clone()))
4122 .unwrap_or_default()
4123 })
4124 }
4125 pub fn selected_option_indices(&self, idx: usize) -> Vec<usize> {
4130 let options = self.select_options(idx);
4131 let selected: Vec<usize> = options.iter().copied().filter(|&o| self.has_attr(o, "selected")).collect();
4132 if !selected.is_empty() {
4133 selected
4134 } else {
4135 options.first().copied().into_iter().collect()
4136 }
4137 }
4138 pub fn select_effective_value(&self, idx: usize) -> String {
4143 let options = self.select_options(idx);
4144 let target = options
4145 .iter()
4146 .copied()
4147 .find(|&o| self.has_attr(o, "selected"))
4148 .or_else(|| options.first().copied());
4149 match target {
4150 Some(o) => self.option_value(o),
4151 None => String::new(),
4152 }
4153 }
4154 pub fn effective_form_value(&self, idx: usize) -> String {
4163 let tag = self.nodes.get(idx).map(|n| n.tag.as_str()).unwrap_or("");
4164 if tag == "select" {
4165 self.select_effective_value(idx)
4166 } else if tag == "textarea" {
4167 self.get_attr(idx, "_live_value").or_else(|| self.get_attr(idx, "value")).unwrap_or_else(|| {
4168 self.nodes
4169 .get(idx)
4170 .map(|n| n.initial_text.clone())
4171 .unwrap_or_default()
4172 })
4173 } else if tag == "input" {
4174 self.input_value(idx)
4175 } else {
4176 self.get_attr(idx, "value").unwrap_or_default()
4177 }
4178 }
4179 pub fn set_select_value(&mut self, idx: usize, val: &str) {
4182 let options = self.select_options(idx);
4183 for &o in &options {
4184 if self.option_value(o) == val {
4185 self.set_attr(o, "selected", "selected");
4186 } else {
4187 self.remove_attr(o, "selected");
4188 }
4189 }
4190 self.mark_structural_dirty_for("select");
4191 }
4192 pub fn select_selected_index(&self, idx: usize) -> i32 {
4195 let options = self.select_options(idx);
4196 match options.iter().position(|&o| self.has_attr(o, "selected")) {
4197 Some(p) => p as i32,
4198 None if !options.is_empty()
4199 && !self.nodes.get(idx).is_some_and(|n| n.attrs.contains_key("_sel_none")) => 0,
4200 None => -1,
4201 }
4202 }
4203 pub fn set_select_selected_index(&mut self, idx: usize, n: i32) {
4205 let options = self.select_options(idx);
4206 if n < 0 || (n as usize) >= options.len() {
4207 if let Some(node) = self.nodes.get_mut(idx) {
4208 node.attrs.insert(String::from("_sel_none"), String::from("1"));
4209 }
4210 } else if let Some(node) = self.nodes.get_mut(idx) {
4211 node.attrs.remove("_sel_none");
4212 }
4213 for (i, &o) in options.iter().enumerate() {
4214 if i as i32 == n {
4215 self.set_attr(o, "selected", "selected");
4216 } else {
4217 self.remove_attr(o, "selected");
4218 }
4219 }
4220 self.mark_structural_dirty_for("select");
4221 }
4222 pub fn set_select_length(&mut self, idx: usize, n: usize) {
4227 let options = self.select_options(idx);
4228 if n < options.len() {
4229 for &o in &options[n..] {
4230 if let Some(parent) = self.nodes.get(o).and_then(|node| node.parent) {
4231 self.remove_child(parent, o);
4232 }
4233 }
4234 } else {
4235 for _ in options.len()..n {
4236 let opt = self.create_element("option");
4237 self.append_child(idx, opt);
4238 }
4239 }
4240 self.mark_structural_dirty_for("select");
4241 }
4242 pub fn option_index(&self, idx: usize) -> i32 {
4248 match self.closest_tag(idx, "select") {
4249 Some(sel) => self
4250 .select_options(sel)
4251 .iter()
4252 .position(|&o| o == idx)
4253 .map(|p| p as i32)
4254 .unwrap_or(0),
4255 None => 0,
4256 }
4257 }
4258
4259 pub fn get_attr(&self, idx: usize, name: &str) -> Option<String> {
4260 let n = self.nodes.get(idx)?;
4261 match name {
4262 "id" => match n.attrs.get("id") {
4265 Some(v) => Some(v.clone()),
4266 None if !n.id.is_empty() => Some(n.id.clone()),
4267 None => None,
4268 },
4269 "class" => match n.attrs.get("class") {
4270 Some(v) => Some(v.clone()),
4271 None if !n.classes.is_empty() => Some(n.classes.join(" ")),
4272 None => None,
4273 },
4274 _ => n.attrs.get(name).cloned(),
4275 }
4276 }
4277 pub fn set_attr(&mut self, idx: usize, name: &str, val: &str) {
4278 let old_value = self.get_attr(idx, name);
4279 let unchanged = old_value.as_deref() == Some(val) && (name != "id" || !val.is_empty());
4283 if unchanged || name.starts_with('_') {
4284 if let Some(n) = self.nodes.get_mut(idx) {
4285 match name {
4286 "id" => {
4287 n.id = val.to_string();
4288 n.attrs.insert(name.to_string(), val.to_string());
4289 self.id_dirty = true;
4290 }
4291 "class" => {
4292 n.attrs.insert(name.to_string(), val.to_string());
4293 }
4294 _ => {
4295 n.attrs.insert(name.to_string(), val.to_string());
4296 }
4297 }
4298 }
4299 self.notify_attribute(idx, name, old_value.as_deref());
4300 return;
4301 }
4302 if old_value.is_none() {
4303 self.attr_order_push(idx, name);
4304 if let Some(ord) = self.attr_ns_order.get_mut(&idx) {
4305 if !ord.iter().any(|(ns, qn)| ns.is_none() && qn == name) {
4306 ord.push((None, name.to_string()));
4307 }
4308 }
4309 }
4310 let affects_layout = self.attr_affects_layout(idx, name);
4311 let clear_sel_none = name == "selected" && self.nodes.get(idx).is_some_and(|n| !n.is_text && n.tag == "option");
4312 if let Some(n) = self.nodes.get_mut(idx) {
4313 match name {
4314 "id" => {
4315 n.id = val.to_string();
4316 n.attrs.insert(name.to_string(), val.to_string());
4317 self.id_dirty = true;
4318 }
4319 "class" => {
4320 n.classes = split_ascii_ws(val);
4321 n.classes_dirty = true;
4322 n.attrs.insert(name.to_string(), val.to_string());
4323 }
4324 _ => {
4325 n.attrs.insert(name.to_string(), val.to_string());
4326 }
4327 }
4328 if affects_layout {
4329 self.mark_structural_dirty_attr(name);
4330 }
4331 }
4332 if clear_sel_none {
4333 let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
4334 while let Some(p) = cur {
4335 if self.nodes.get(p).is_some_and(|n| !n.is_text && n.tag == "select") {
4336 if let Some(sn) = self.nodes.get_mut(p) {
4337 sn.attrs.remove("_sel_none");
4338 }
4339 break;
4340 }
4341 cur = self.nodes.get(p).and_then(|n| n.parent);
4342 }
4343 }
4344 if name == "type" && self.nodes.get(idx).is_some_and(|n| n.tag == "input") {
4345 self.input_type_changed(idx, old_value.as_deref());
4346 }
4347 self.notify_attribute(idx, name, old_value.as_deref());
4348 }
4349
4350 pub fn has_attr(&self, idx: usize, name: &str) -> bool {
4352 match self.nodes.get(idx) {
4353 Some(n) => match name {
4354 "id" => !n.id.is_empty() || n.attrs.contains_key("id"),
4355 "class" => !n.classes.is_empty() || n.attrs.contains_key("class"),
4356 _ => n.attrs.contains_key(name),
4357 },
4358 None => false,
4359 }
4360 }
4361
4362 pub fn remove_attr(&mut self, idx: usize, name: &str) {
4364 let old_value = self.get_attr(idx, name);
4368 if self.has_attr_nodes && !name.starts_with('_') {
4369 self.detach_attr_node(idx, name, old_value.as_deref().unwrap_or(""));
4370 if let Some(n) = self.nodes.get_mut(idx) {
4371 n.attrs.remove(&format!("_ans:{}", name));
4372 }
4373 }
4374 if name.starts_with('_') {
4376 if let Some(n) = self.nodes.get_mut(idx) {
4377 n.attrs.remove(name);
4378 }
4379 return;
4380 }
4381 if !self.has_attr(idx, name) {
4382 let found_ns = self.ns_attrs.get_mut(&idx).and_then(|list| {
4383 list.iter()
4384 .position(|(_, qn, _)| qn == name)
4385 .map(|pos| list.remove(pos))
4386 });
4387 if let Some((u, qn, old_val)) = found_ns {
4388 if self.ns_attrs.get(&idx).is_some_and(|l| l.is_empty()) {
4389 self.ns_attrs.remove(&idx);
4390 }
4391 let local = qn.split_once(':').map(|(_, l)| l).unwrap_or(&qn);
4392 self.remove_attr_ns_notify(idx, Some(&u), local, &qn, &old_val);
4393 }
4394 return;
4395 }
4396 if !self.attr_order.is_empty() {
4397 if let Some(o) = self.attr_order.get_mut(&idx) {
4398 o.retain(|k| k != name);
4399 }
4400 }
4401 if let Some(ord) = self.attr_ns_order.get_mut(&idx) {
4402 ord.retain(|(ns, qn)| !(ns.is_none() && qn == name));
4403 }
4404 let affects_layout = self.attr_affects_layout(idx, name);
4405 if let Some(n) = self.nodes.get_mut(idx) {
4406 match name {
4407 "id" => {
4408 n.id = String::new();
4409 n.attrs.remove("id");
4410 self.id_dirty = true;
4411 }
4412 "class" => {
4413 n.classes.clear();
4414 n.classes_dirty = true;
4415 n.attrs.remove("class");
4416 }
4417 "style" => {
4418 n.style.clear();
4419 n.style_dirty = true;
4420 n.attrs.remove("style");
4421 }
4422 _ => {
4423 n.attrs.remove(name);
4424 }
4425 }
4426 if affects_layout {
4427 self.mark_structural_dirty_attr(name);
4428 }
4429 }
4430 if name == "type" && self.nodes.get(idx).is_some_and(|n| n.tag == "input") {
4431 self.input_type_changed(idx, old_value.as_deref());
4432 }
4433 self.notify_attribute(idx, name, old_value.as_deref());
4434 }
4435
4436 pub fn get_dataset(&self, idx: usize) -> BTreeMap<String, String> {
4438 match self.nodes.get(idx) {
4439 Some(n) => crate::os_lib::dom_dataset::extract_dataset(&n.attrs),
4440 None => BTreeMap::new(),
4441 }
4442 }
4443
4444 pub fn close_details_group_siblings(&mut self, idx: usize) -> alloc::vec::Vec<usize> {
4456 let name = match self.nodes.get(idx).and_then(|n| n.attrs.get("name")) {
4457 Some(n) if !n.is_empty() => n.clone(),
4458 _ => return alloc::vec::Vec::new(),
4459 };
4460 let siblings: alloc::vec::Vec<usize> = self
4461 .nodes
4462 .iter()
4463 .enumerate()
4464 .filter(|(i, n)| {
4465 *i != idx
4466 && n.tag == "details"
4467 && n.attrs.get("name").map(|s| s.as_str()) == Some(name.as_str())
4468 && n.attrs.contains_key("open")
4469 })
4470 .map(|(i, _)| i)
4471 .collect();
4472 for &i in &siblings {
4473 self.remove_attr(i, "open");
4474 }
4475 siblings
4476 }
4477
4478 fn node_tree_root(&self, idx: usize) -> usize {
4479 let mut cur = idx;
4480 for _ in 0..=self.nodes.len() {
4481 match self.nodes.get(cur).and_then(|n| n.parent) {
4482 Some(p) => cur = p,
4483 None => break,
4484 }
4485 }
4486 cur
4487 }
4488
4489 fn radio_form_owner(&self, idx: usize, root: usize) -> Option<usize> {
4490 if let Some(fid) = self.nodes.get(idx).and_then(|n| n.attrs.get("form")).filter(|s| !s.is_empty()) {
4491 let mut stack = alloc::vec![root];
4492 while let Some(c) = stack.pop() {
4493 if let Some(n) = self.nodes.get(c) {
4494 if !n.is_text && n.tag == "form" && n.id == *fid {
4495 return Some(c);
4496 }
4497 stack.extend(n.children.iter().rev().copied());
4498 }
4499 }
4500 }
4501 let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
4502 for _ in 0..=self.nodes.len() {
4503 let Some(p) = cur else { break };
4504 if self.nodes.get(p).is_some_and(|n| !n.is_text && n.tag == "form") {
4505 return Some(p);
4506 }
4507 cur = self.nodes.get(p).and_then(|n| n.parent);
4508 }
4509 None
4510 }
4511
4512 pub fn same_radio_group(&self, a: usize, b: usize) -> bool {
4513 let Some(na) = self.nodes.get(a) else { return false };
4514 let Some(nb) = self.nodes.get(b) else { return false };
4515 if na.is_text || nb.is_text || na.tag != "input" || nb.tag != "input" {
4516 return false;
4517 }
4518 let is_radio = |n: &DomNode| n.attrs.get("type").is_some_and(|t| t.eq_ignore_ascii_case("radio"));
4519 if !is_radio(na) || !is_radio(nb) {
4520 return false;
4521 }
4522 let name_a = na.attrs.get("name").map(|s| s.as_str()).unwrap_or("");
4523 let name_b = nb.attrs.get("name").map(|s| s.as_str()).unwrap_or("");
4524 if name_a.is_empty() || name_a != name_b {
4525 return false;
4526 }
4527 let ra = self.node_tree_root(a);
4528 let rb = self.node_tree_root(b);
4529 let fa = self.radio_form_owner(a, ra);
4530 let fb = self.radio_form_owner(b, rb);
4531 match (fa, fb) {
4532 (Some(x), Some(y)) => x == y,
4533 (None, None) => ra == rb,
4534 _ => false,
4535 }
4536 }
4537
4538 pub fn uncheck_radio_group_siblings(&mut self, idx: usize) {
4539 let siblings: Vec<usize> = (0..self.nodes.len())
4540 .filter(|&i| i != idx && self.same_radio_group(idx, i))
4541 .collect();
4542 for i in siblings {
4543 self.remove_attr(i, "checked");
4544 self.set_attr(i, "_live_checked", "false");
4545 }
4546 }
4547
4548 pub fn assigned_slot_for(&self, idx: usize) -> Option<usize> {
4549 let p = self.nodes.get(idx)?.parent?;
4550 let d = self.shadow_tree.get_by_host(p)?;
4551 if !d.is_accessible_via_element() {
4552 return None;
4553 }
4554 let slot_name = self.get_attr(idx, "slot").unwrap_or_default();
4555 self.descendants_by_tag_name(d.root_node_idx, "slot")
4556 .into_iter()
4557 .find(|&s| self.get_attr(s, "name").unwrap_or_default() == slot_name)
4558 }
4559
4560 pub fn slot_assigned_nodes(&self, slot_idx: usize, elem_only: bool) -> Vec<usize> {
4561 let mut cur = self.nodes.get(slot_idx).and_then(|n| n.parent);
4562 let mut root = slot_idx;
4563 while let Some(p) = cur {
4564 root = p;
4565 cur = self.nodes.get(p).and_then(|n| n.parent);
4566 }
4567 let Some(host) = self.shadow_tree.get_host_by_root(root) else {
4568 return Vec::new();
4569 };
4570 let slot_name = self.get_attr(slot_idx, "name").unwrap_or_default();
4571 let Some(hn) = self.nodes.get(host) else {
4572 return Vec::new();
4573 };
4574 hn.children
4575 .iter()
4576 .copied()
4577 .filter(|&c| {
4578 let Some(cn) = self.nodes.get(c) else { return false };
4579 if cn.is_text {
4580 !elem_only && slot_name.is_empty()
4581 } else {
4582 !cn.tag.starts_with('#') && self.get_attr(c, "slot").unwrap_or_default() == slot_name
4583 }
4584 })
4585 .collect()
4586 }
4587
4588 pub fn node_matches(&self, idx: usize, selector: &str) -> bool {
4596 self.node_matches_scoped(idx, selector, None)
4597 }
4598
4599 pub fn node_matches_scoped(&self, idx: usize, selector: &str, scope_root: Option<usize>) -> bool {
4605 if self.nodes.get(idx).map(|n| n.is_text).unwrap_or(true) {
4606 return false;
4607 }
4608 self.node_matches_parsed(idx, &parse_selector_groups(selector), scope_root)
4609 }
4610
4611 pub fn node_matches_parsed(&self, idx: usize, groups: &[Vec<SelStep>], scope_root: Option<usize>) -> bool {
4613 self.node_matches_parsed_with_anchor(idx, groups, scope_root, None)
4614 }
4615
4616 fn node_matches_parsed_with_anchor(
4617 &self,
4618 idx: usize,
4619 groups: &[Vec<SelStep>],
4620 scope_root: Option<usize>,
4621 has_anchor: Option<usize>,
4622 ) -> bool {
4623 if self.nodes.get(idx).map(|n| n.is_text || n.tag.starts_with('#')).unwrap_or(true) {
4624 return false;
4625 }
4626 for steps in groups {
4627 let last = steps.len() - 1;
4628 if self.compound_matches_with_anchor(idx, &steps[last].compound, scope_root, has_anchor)
4629 && self.match_selector_chain_with_anchor(idx, steps, last, scope_root, has_anchor)
4630 {
4631 return true;
4632 }
4633 }
4634 false
4635 }
4636
4637 fn compound_matches(&self, idx: usize, c: &CompoundSel, scope_root: Option<usize>) -> bool {
4639 self.compound_matches_with_anchor(idx, c, scope_root, None)
4640 }
4641
4642 fn compound_matches_with_anchor(
4643 &self,
4644 idx: usize,
4645 c: &CompoundSel,
4646 scope_root: Option<usize>,
4647 has_anchor: Option<usize>,
4648 ) -> bool {
4649 if c.is_has_anchor && Some(idx) != has_anchor {
4650 return false;
4651 }
4652 if c.is_scope && Some(idx) != scope_root {
4653 return false;
4654 }
4655 let n = match self.nodes.get(idx) {
4656 Some(n) if !n.is_text && !n.tag.starts_with('#') => n,
4657 _ => return false,
4658 };
4659 let ns_uri = node_namespace(n);
4660 if c.no_namespace && ns_uri.is_some() {
4661 return false;
4662 }
4663 let html_el_in_html_doc = !n.attrs.contains_key("_xml")
4664 && ns_uri.as_deref() == Some(HTML_NS_URI)
4665 && self.doc_is_html(self.node_document(idx));
4666 if !type_selector_matches(c, &node_local_name(n), html_el_in_html_doc) {
4667 return false;
4668 }
4669 if let Some(id) = &c.id {
4670 if &n.id != id {
4671 return false;
4672 }
4673 }
4674 if !c.classes.iter().all(|cls| n.classes.iter().any(|nc| nc == cls)) {
4675 return false;
4676 }
4677 for (k, attr) in c.attrs.iter().enumerate() {
4678 let ext = c.attr_ext.get(k).copied().unwrap_or_default();
4679 let ok = if ext.any_ns {
4680 let in_plain = n.attrs.iter().any(|(qn, val)| {
4681 !qn.starts_with('_')
4682 && !qn.starts_with('#')
4683 && attr_qname_has_local_name(qn, &attr.name)
4684 && attr_value_matches(
4685 attr.op,
4686 &attr.value,
4687 val,
4688 ext,
4689 html_el_in_html_doc && html_attr_value_is_case_insensitive(qn),
4690 )
4691 });
4692 let in_ns = !in_plain
4693 && self.ns_attrs.get(&idx).is_some_and(|list| {
4694 list.iter().any(|(_, qn, val)| {
4695 attr_qname_has_local_name(qn, &attr.name)
4696 && attr_value_matches(
4697 attr.op,
4698 &attr.value,
4699 val,
4700 ext,
4701 html_el_in_html_doc && html_attr_value_is_case_insensitive(qn),
4702 )
4703 })
4704 });
4705 in_plain || in_ns
4706 } else {
4707 let lookup = attr_lookup_name(&attr.name, html_el_in_html_doc);
4708 let val_opt = if lookup.starts_with('_') {
4709 None
4710 } else {
4711 n.attrs.get(&lookup).map(|s| s.as_str()).or_else(|| {
4712 self.ns_attrs.get(&idx).and_then(|list| {
4713 list.iter()
4714 .find(|(_, qn, _)| qn == &lookup)
4715 .map(|(_, _, v)| v.as_str())
4716 })
4717 })
4718 };
4719 match val_opt {
4720 Some(actual) => attr_value_matches(
4721 attr.op,
4722 &attr.value,
4723 actual,
4724 ext,
4725 html_el_in_html_doc && html_attr_value_is_case_insensitive(&lookup),
4726 ),
4727 None => false,
4728 }
4729 };
4730 if !ok {
4731 return false;
4732 }
4733 }
4734 for not_sel in &c.not {
4735 if self.compound_matches_with_anchor(idx, not_sel, scope_root, has_anchor) {
4736 return false;
4737 }
4738 }
4739 for not_steps in &c.not_complex {
4740 if self.node_matches_parsed_with_anchor(
4741 idx,
4742 core::slice::from_ref(not_steps),
4743 scope_root,
4744 has_anchor,
4745 ) {
4746 return false;
4747 }
4748 }
4749 if !c.is_list.is_empty() || !c.is_complex.is_empty() {
4750 let ok = c
4751 .is_list
4752 .iter()
4753 .any(|s| self.compound_matches_with_anchor(idx, s, scope_root, has_anchor))
4754 || c.is_complex.iter().any(|g| {
4755 self.node_matches_parsed_with_anchor(
4756 idx,
4757 core::slice::from_ref(g),
4758 scope_root,
4759 has_anchor,
4760 )
4761 });
4762 if !ok {
4763 return false;
4764 }
4765 }
4766 for rel in &c.has {
4767 let candidates: Vec<usize> = match rel.combinator {
4768 Combinator::Child | Combinator::Descendant => walk_elements(self, idx, false),
4769 Combinator::Adjacent | Combinator::General => self.following_sibling_elements_and_descendants(idx),
4770 };
4771 let anchored = core::slice::from_ref(&rel.anchored);
4772 if !candidates
4773 .into_iter()
4774 .any(|cand| self.node_matches_parsed_with_anchor(cand, anchored, scope_root, Some(idx)))
4775 {
4776 return false;
4777 }
4778 }
4779 if !c.pos.is_empty() {
4780 let (position, count) = self.element_sibling_position(idx);
4781 for p in &c.pos {
4782 let ok = match p {
4783 PosPseudo::First => position == 1,
4784 PosPseudo::Last => position == count,
4785 PosPseudo::Only => position == 1 && count == 1,
4786 PosPseudo::Nth(f) => nth_formula_matches(*f, position),
4787 PosPseudo::NthLast(f) => nth_formula_matches(*f, count - position + 1),
4788 };
4789 if !ok {
4790 return false;
4791 }
4792 }
4793 }
4794 if !c.pos_of_type.is_empty() {
4795 let (position, count) = self.element_type_sibling_position(idx);
4796 for p in &c.pos_of_type {
4797 let ok = match p {
4798 PosPseudo::First => position == 1,
4799 PosPseudo::Last => position == count,
4800 PosPseudo::Only => position == 1 && count == 1,
4801 PosPseudo::Nth(f) => nth_formula_matches(*f, position),
4802 PosPseudo::NthLast(f) => nth_formula_matches(*f, count - position + 1),
4803 };
4804 if !ok {
4805 return false;
4806 }
4807 }
4808 }
4809 if c.is_root {
4810 let is_root_elem = n.tag == "html" || n.parent.is_none();
4812 if !is_root_elem {
4813 return false;
4814 }
4815 }
4816 if c.is_empty {
4817 let has_content = n.children.iter().any(|&cid| {
4819 if let Some(child) = self.nodes.get(cid) {
4820 !child.is_text || !child.text_override.as_deref().unwrap_or(&child.initial_text).is_empty()
4821 } else {
4822 false
4823 }
4824 });
4825 if has_content {
4826 return false;
4827 }
4828 }
4829 if c.is_checked {
4830 let checked = if let Some(lc) = n.attrs.get("_live_checked") {
4831 lc == "true"
4832 } else {
4833 n.attrs.contains_key("checked")
4834 };
4835 if !checked {
4836 return false;
4837 }
4838 }
4839 if c.is_disabled && !self.is_disabled(idx) {
4840 return false;
4841 }
4842 if c.is_enabled {
4843 let can_disable = matches!(
4844 n.tag.as_str(),
4845 "button" | "input" | "select" | "textarea" | "optgroup" | "option" | "fieldset"
4846 );
4847 if !can_disable || self.is_disabled(idx) {
4848 return false;
4849 }
4850 }
4851 if c.is_valid || c.is_invalid {
4852 let is_ctrl_cand = !n.is_text && !self.barred_from_validation(idx);
4853 let valid_opt = if is_ctrl_cand {
4854 Some(self.validity_flags(idx, "").valid())
4855 } else if !n.is_text && n.tag == "form" {
4856 let controls = self.form_associated_controls(idx, &["button", "input", "select", "textarea"]);
4857 let any_invalid =
4858 controls.iter().any(|&ci| !self.barred_from_validation(ci) && !self.validity_flags(ci, "").valid());
4859 Some(!any_invalid)
4860 } else if !n.is_text && n.tag == "fieldset" {
4861 let first_legend = n.children.iter().copied().find(|&ch| {
4862 self.nodes.get(ch).is_some_and(|cn| !cn.is_text && cn.tag == "legend")
4863 });
4864 let mut stack: Vec<usize> = n.children.iter().copied().filter(|&ch| Some(ch) != first_legend).collect();
4865 let mut any_invalid = false;
4866 while let Some(ci) = stack.pop() {
4867 if let Some(cn) = self.nodes.get(ci) {
4868 if !cn.is_text {
4869 if matches!(cn.tag.as_str(), "button" | "input" | "select" | "textarea")
4870 && !self.barred_from_validation(ci)
4871 && !self.validity_flags(ci, "").valid()
4872 {
4873 any_invalid = true;
4874 break;
4875 }
4876 stack.extend(cn.children.iter().copied());
4877 }
4878 }
4879 }
4880 Some(!any_invalid)
4881 } else {
4882 None
4883 };
4884 match valid_opt {
4885 Some(valid) => {
4886 if (c.is_valid && !valid) || (c.is_invalid && valid) {
4887 return false;
4888 }
4889 }
4890 None => return false,
4891 }
4892 }
4893 true
4894 }
4895
4896 fn element_sibling_position(&self, idx: usize) -> (usize, usize) {
4899 let parent = match self.nodes.get(idx).and_then(|n| n.parent) {
4900 Some(p) => p,
4901 None => return (1, 1),
4902 };
4903 let siblings = match self.nodes.get(parent) {
4904 Some(n) => &n.children,
4905 None => return (1, 1),
4906 };
4907 let elements: Vec<usize> = siblings
4908 .iter()
4909 .filter(|&&c| self.nodes.get(c).is_some_and(|n| !n.is_text && !n.tag.starts_with('#')))
4910 .copied()
4911 .collect();
4912 let count = elements.len();
4913 let position = elements.iter().position(|&c| c == idx).map(|p| p + 1).unwrap_or(0);
4914 (position, count)
4915 }
4916
4917 fn following_sibling_elements_and_descendants(&self, idx: usize) -> Vec<usize> {
4918 let Some(parent) = self.nodes.get(idx).and_then(|n| n.parent) else {
4919 return Vec::new();
4920 };
4921 let Some(siblings) = self.nodes.get(parent).map(|n| &n.children) else {
4922 return Vec::new();
4923 };
4924 let Some(pos) = siblings.iter().position(|&c| c == idx) else {
4925 return Vec::new();
4926 };
4927 let mut out = Vec::new();
4928 for &sib in &siblings[pos + 1..] {
4929 out.extend(walk_elements(self, sib, true));
4930 }
4931 out
4932 }
4933
4934 fn element_type_sibling_position(&self, idx: usize) -> (usize, usize) {
4937 let tag = match self.nodes.get(idx) {
4938 Some(n) => n.tag.clone(),
4939 None => return (1, 1),
4940 };
4941 let parent = match self.nodes.get(idx).and_then(|n| n.parent) {
4942 Some(p) => p,
4943 None => return (1, 1),
4944 };
4945 let siblings = match self.nodes.get(parent) {
4946 Some(n) => &n.children,
4947 None => return (1, 1),
4948 };
4949 let same_type: Vec<usize> = siblings
4950 .iter()
4951 .filter(|&&c| self.nodes.get(c).map(|n| !n.is_text && n.tag == tag).unwrap_or(false))
4952 .copied()
4953 .collect();
4954 let count = same_type.len();
4955 let position = same_type.iter().position(|&c| c == idx).map(|p| p + 1).unwrap_or(0);
4956 (position, count)
4957 }
4958
4959 fn match_selector_chain(
4962 &self,
4963 idx: usize,
4964 steps: &[SelStep],
4965 step_i: usize,
4966 scope_root: Option<usize>,
4967 ) -> bool {
4968 self.match_selector_chain_with_anchor(idx, steps, step_i, scope_root, None)
4969 }
4970
4971 fn match_selector_chain_with_anchor(
4972 &self,
4973 idx: usize,
4974 steps: &[SelStep],
4975 step_i: usize,
4976 scope_root: Option<usize>,
4977 has_anchor: Option<usize>,
4978 ) -> bool {
4979 if step_i == 0 {
4980 return true;
4981 }
4982 let combinator = match steps[step_i].combinator {
4983 Some(c) => c,
4984 None => return true,
4985 };
4986 match combinator {
4987 Combinator::Descendant => {
4988 let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
4989 let mut guard = 0;
4990 while let Some(p) = cur {
4991 if self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
4992 && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
4993 {
4994 return true;
4995 }
4996 cur = self.nodes.get(p).and_then(|n| n.parent);
4997 guard += 1;
4998 if guard > self.nodes.len() {
4999 break;
5000 }
5001 }
5002 false
5003 }
5004 Combinator::Child => match self.nodes.get(idx).and_then(|n| n.parent) {
5005 Some(p) => {
5006 self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
5007 && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
5008 }
5009 None => false,
5010 },
5011 Combinator::Adjacent => match self.prev_element_sibling(idx) {
5012 Some(p) => {
5013 self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
5014 && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
5015 }
5016 None => false,
5017 },
5018 Combinator::General => {
5019 for p in self.preceding_element_siblings(idx) {
5020 if self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
5021 && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
5022 {
5023 return true;
5024 }
5025 }
5026 false
5027 }
5028 }
5029 }
5030
5031 fn prev_element_sibling(&self, idx: usize) -> Option<usize> {
5033 let parent = self.nodes.get(idx)?.parent?;
5034 let siblings = &self.nodes.get(parent)?.children;
5035 let pos = siblings.iter().position(|&c| c == idx)?;
5036 siblings[..pos]
5037 .iter()
5038 .rev()
5039 .find(|&&c| self.nodes.get(c).is_some_and(|n| !n.is_text && !n.tag.starts_with('#')))
5040 .copied()
5041 }
5042
5043 fn preceding_element_siblings(&self, idx: usize) -> Vec<usize> {
5045 let parent = match self.nodes.get(idx).and_then(|n| n.parent) {
5046 Some(p) => p,
5047 None => return Vec::new(),
5048 };
5049 let siblings = match self.nodes.get(parent) {
5050 Some(n) => &n.children,
5051 None => return Vec::new(),
5052 };
5053 let pos = match siblings.iter().position(|&c| c == idx) {
5054 Some(p) => p,
5055 None => return Vec::new(),
5056 };
5057 siblings[..pos]
5058 .iter()
5059 .filter(|&&c| self.nodes.get(c).is_some_and(|n| !n.is_text && !n.tag.starts_with('#')))
5060 .copied()
5061 .collect()
5062 }
5063
5064 pub fn is_ancestor_of(&self, anc: usize, idx: usize) -> bool {
5066 let mut cur = idx;
5067 let mut guard = 0;
5068 while let Some(p) = self.nodes.get(cur).and_then(|n| n.parent) {
5069 if p == anc {
5070 return true;
5071 }
5072 cur = p;
5073 guard += 1;
5074 if guard > self.nodes.len() {
5075 break;
5076 }
5077 }
5078 false
5079 }
5080
5081 pub fn document_position(&self, this_idx: usize, other_idx: usize) -> u32 {
5089 const DISCONNECTED: u32 = 0x01;
5090 const PRECEDING: u32 = 0x02;
5091 const FOLLOWING: u32 = 0x04;
5092 const CONTAINS: u32 = 0x08;
5093 const CONTAINED_BY: u32 = 0x10;
5094 const IMPLEMENTATION_SPECIFIC: u32 = 0x20;
5095
5096 if this_idx == other_idx {
5097 return 0;
5098 }
5099 if self.is_ancestor_of(other_idx, this_idx) {
5100 return CONTAINS | PRECEDING;
5102 }
5103 if self.is_ancestor_of(this_idx, other_idx) {
5104 return CONTAINED_BY | FOLLOWING;
5106 }
5107 let chain_of = |start: usize| -> Vec<usize> {
5108 let mut chain = alloc::vec![start];
5109 let mut cur = start;
5110 let mut guard = 0;
5111 while let Some(p) = self.nodes.get(cur).and_then(|n| n.parent) {
5112 chain.push(p);
5113 cur = p;
5114 guard += 1;
5115 if guard > self.nodes.len() {
5116 break;
5117 }
5118 }
5119 chain.reverse(); chain
5121 };
5122 let chain_a = chain_of(this_idx);
5123 let chain_b = chain_of(other_idx);
5124 if chain_a.first() != chain_b.first() {
5125 let order = if this_idx < other_idx { FOLLOWING } else { PRECEDING };
5127 return DISCONNECTED | IMPLEMENTATION_SPECIFIC | order;
5128 }
5129 let mut i = 0;
5130 while i < chain_a.len() && i < chain_b.len() && chain_a[i] == chain_b[i] {
5131 i += 1;
5132 }
5133 if i == 0 || i >= chain_a.len() || i >= chain_b.len() {
5134 return DISCONNECTED | IMPLEMENTATION_SPECIFIC;
5136 }
5137 let lca = chain_a[i - 1];
5138 let child_a = chain_a[i];
5139 let child_b = chain_b[i];
5140 let siblings = match self.nodes.get(lca) {
5141 Some(n) => &n.children,
5142 None => return DISCONNECTED | IMPLEMENTATION_SPECIFIC,
5143 };
5144 let pos_a = siblings.iter().position(|&c| c == child_a);
5145 let pos_b = siblings.iter().position(|&c| c == child_b);
5146 match (pos_a, pos_b) {
5147 (Some(pa), Some(pb)) if pa < pb => FOLLOWING,
5148 (Some(pa), Some(pb)) if pa > pb => PRECEDING,
5149 _ => DISCONNECTED | IMPLEMENTATION_SPECIFIC,
5150 }
5151 }
5152
5153 pub fn offset_parent(&self, idx: usize) -> Option<usize> {
5158 let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
5159 let mut body_idx = None;
5160 let mut guard = 0;
5161 while let Some(c) = cur {
5162 if self.nodes.get(c).map(|n| !n.is_text && n.tag == "body").unwrap_or(false) {
5163 body_idx = Some(c);
5164 }
5165 let pos = self.get_computed(c, "position");
5166 if pos == "absolute" || pos == "relative" || pos == "fixed" || pos == "sticky" {
5167 return Some(c);
5168 }
5169 cur = self.nodes.get(c).and_then(|n| n.parent);
5170 guard += 1;
5171 if guard > self.nodes.len() {
5172 break;
5173 }
5174 }
5175 body_idx
5176 }
5177
5178 pub fn closest_tag(&self, idx: usize, tag: &str) -> Option<usize> {
5179 let mut cur = Some(idx);
5180 let mut guard = 0;
5181 while let Some(c) = cur {
5182 if self
5183 .nodes
5184 .get(c)
5185 .map(|n| !n.is_text && n.tag == tag)
5186 .unwrap_or(false)
5187 {
5188 return Some(c);
5189 }
5190 cur = self.nodes.get(c).and_then(|n| n.parent);
5191 guard += 1;
5192 if guard > self.nodes.len() {
5193 break;
5194 }
5195 }
5196 None
5197 }
5198
5199 pub fn associated_form(&self, idx: usize) -> Option<usize> {
5208 if let Some(form_id) = self.get_attr(idx, "form") {
5211 if form_id.is_empty() {
5212 return None;
5213 }
5214 let found = if self.is_attached(idx) {
5215 self.get_element_by_id(&form_id)
5216 } else {
5217 let mut root = idx;
5218 while let Some(p) = self.nodes.get(root).and_then(|n| n.parent) {
5219 root = p;
5220 }
5221 if self.nodes.get(root).is_some_and(|n| !n.is_text && n.id == form_id) {
5222 Some(root)
5223 } else {
5224 self.descendants_by_tag_name(root, "*")
5225 .into_iter()
5226 .find(|&d| self.nodes.get(d).is_some_and(|n| !n.is_text && n.id == form_id))
5227 }
5228 };
5229 return found.filter(|&fi| self.nodes.get(fi).map(|n| n.tag == "form").unwrap_or(false));
5230 }
5231 self.closest_tag(idx, "form")
5232 }
5233
5234 pub fn form_associated_controls(&self, form_idx: usize, tags: &[&str]) -> Vec<usize> {
5241 let mut out: Vec<usize> = self
5242 .descendants_by_tags(form_idx, tags)
5243 .into_iter()
5244 .filter(|&c| !self.has_attr(c, "form") || self.associated_form(c) == Some(form_idx))
5245 .collect();
5246 let form_attached = self.is_attached(form_idx);
5247 if let Some(form_id) = self.get_attr(form_idx, "id") {
5248 if !form_id.is_empty() {
5249 for (i, n) in self.nodes.iter().enumerate() {
5250 if n.is_text || out.contains(&i) {
5251 continue;
5252 }
5253 if form_attached && !self.is_attached(i) {
5254 continue;
5255 }
5256 if !tags.contains(&n.tag.as_str()) {
5257 continue;
5258 }
5259 if n.attrs.get("form").map(|v| v == &form_id).unwrap_or(false) && self.associated_form(i) == Some(form_idx) {
5260 out.push(i);
5261 }
5262 }
5263 }
5264 }
5265 out
5266 }
5267
5268 pub fn first_by_tag(&self, tag: &str) -> Option<usize> {
5270 (0..self.nodes.len())
5271 .find(|&i| !self.nodes[i].is_text && self.nodes[i].tag == tag && self.is_attached(i))
5272 }
5273
5274 pub fn element_children(&self, idx: usize) -> Vec<usize> {
5276 self.nodes
5277 .get(idx)
5278 .map(|n| {
5279 n.children
5280 .iter()
5281 .copied()
5282 .filter(|c| self.nodes.get(*c).map(|cn| !cn.is_text && !cn.tag.starts_with('#')).unwrap_or(false))
5283 .collect()
5284 })
5285 .unwrap_or_default()
5286 }
5287
5288 pub fn descendants_by_tag_name(&self, root: usize, tag: &str) -> Vec<usize> {
5309 let want_all = tag == "*";
5310 let lower = tag.to_ascii_lowercase();
5311 let mut out = Vec::new();
5312 let mut stack: Vec<usize> = self.element_children(root).into_iter().rev().collect();
5313 while let Some(idx) = stack.pop() {
5314 if let Some(n) = self.nodes.get(idx) {
5315 let matched = match n.attrs.get("_qname") {
5318 Some(q) => {
5319 if n.attrs.get("_ns").is_none_or(|v| v == "http://www.w3.org/1999/xhtml") {
5320 *q == lower
5321 } else {
5322 q == tag
5323 }
5324 }
5325 None => n.tag.eq_ignore_ascii_case(&lower),
5326 };
5327 if !n.is_text && (want_all || matched) {
5328 out.push(idx);
5329 }
5330 for &c in n.children.iter().rev() {
5331 if self.nodes.get(c).map(|cn| !cn.is_text).unwrap_or(false) {
5332 stack.push(c);
5333 }
5334 }
5335 }
5336 }
5337 out
5338 }
5339
5340 pub fn descendants_by_tags(&self, root: usize, tags: &[&str]) -> Vec<usize> {
5341 let mut out = Vec::new();
5342 let mut stack: Vec<usize> = self.element_children(root).into_iter().rev().collect();
5343 while let Some(idx) = stack.pop() {
5344 if let Some(n) = self.nodes.get(idx) {
5345 if !n.is_text && tags.iter().any(|t| n.tag == *t) {
5346 out.push(idx);
5347 }
5348 for &c in n.children.iter().rev() {
5349 if self.nodes.get(c).map(|cn| !cn.is_text).unwrap_or(false) {
5350 stack.push(c);
5351 }
5352 }
5353 }
5354 }
5355 out
5356 }
5357
5358 pub fn is_disabled(&self, idx: usize) -> bool {
5367 let n = match self.nodes.get(idx) {
5368 Some(n) => n,
5369 None => return false,
5370 };
5371 if n.attrs.contains_key("disabled") {
5372 return true;
5373 }
5374 let mut cur = n.parent;
5375 while let Some(i) = cur {
5376 let anc = match self.nodes.get(i) {
5377 Some(a) => a,
5378 None => break,
5379 };
5380 if anc.tag == "fieldset" && anc.attrs.contains_key("disabled") {
5381 return true;
5382 }
5383 cur = anc.parent;
5384 }
5385 false
5386 }
5387
5388 pub fn input_kind(&self, idx: usize) -> crate::os_lib::web_apis::form_value::Kind {
5392 crate::os_lib::web_apis::form_value::kind_of(
5393 self.nodes.get(idx).and_then(|n| n.attrs.get("type")).map(|s| s.as_str()),
5394 )
5395 }
5396
5397 pub fn input_value(&self, idx: usize) -> String {
5401 use crate::os_lib::web_apis::form_value::{mode_of, sanitize, Attrs, Mode};
5402 let Some(n) = self.nodes.get(idx) else { return String::new() };
5403 let k = self.input_kind(idx);
5404 match mode_of(k) {
5405 Mode::Value => {
5406 let raw = n
5407 .attrs
5408 .get("_live_value")
5409 .or_else(|| n.attrs.get("value"))
5410 .map(|s| s.as_str())
5411 .unwrap_or("");
5412 let at = Attrs {
5413 min: n.attrs.get("min").map(|s| s.as_str()),
5414 max: n.attrs.get("max").map(|s| s.as_str()),
5415 step: n.attrs.get("step").map(|s| s.as_str()),
5416 multiple: n.attrs.contains_key("multiple"),
5417 };
5418 sanitize(k, raw, &at)
5419 }
5420 Mode::Default => n.attrs.get("value").cloned().unwrap_or_default(),
5421 Mode::DefaultOn => n.attrs.get("value").cloned().unwrap_or_else(|| String::from("on")),
5422 Mode::Filename => String::new(),
5423 }
5424 }
5425
5426 pub fn set_input_value(&mut self, idx: usize, v: &str) {
5429 use crate::os_lib::web_apis::form_value::{mode_of, sanitize, Attrs, Mode};
5430 let k = self.input_kind(idx);
5431 match mode_of(k) {
5432 Mode::Value => {
5433 let s = {
5434 let Some(n) = self.nodes.get(idx) else { return };
5435 let at = Attrs {
5436 min: n.attrs.get("min").map(|s| s.as_str()),
5437 max: n.attrs.get("max").map(|s| s.as_str()),
5438 step: n.attrs.get("step").map(|s| s.as_str()),
5439 multiple: n.attrs.contains_key("multiple"),
5440 };
5441 sanitize(k, v, &at)
5442 };
5443 self.set_attr(idx, "_live_value", &s);
5444 }
5445 Mode::Default | Mode::DefaultOn => self.set_attr(idx, "value", v),
5446 Mode::Filename => {}
5447 }
5448 }
5449
5450 pub fn input_type_changed(&mut self, idx: usize, old: Option<&str>) {
5453 use crate::os_lib::web_apis::form_value::{kind_of, mode_of, Mode};
5454 let ok = kind_of(old);
5455 let nk = self.input_kind(idx);
5456 if ok == nk {
5457 return;
5458 }
5459 let (om, nm) = (mode_of(ok), mode_of(nk));
5460 match (om, nm) {
5461 (Mode::Value, Mode::Default) | (Mode::Value, Mode::DefaultOn) => {
5462 let n = match self.nodes.get_mut(idx) {
5464 Some(n) => n,
5465 None => return,
5466 };
5467 let live = n.attrs.get("_live_value").cloned();
5468 if let Some(v) = live {
5469 let cur_type = n.attrs.get("type").cloned();
5471 match old {
5472 Some(o) => {
5473 n.attrs.insert(String::from("type"), o.to_string());
5474 }
5475 None => {
5476 n.attrs.remove("type");
5477 }
5478 }
5479 let _ = v;
5480 let val = self.input_value(idx);
5481 if let Some(n) = self.nodes.get_mut(idx) {
5482 match cur_type {
5483 Some(c) => {
5484 n.attrs.insert(String::from("type"), c);
5485 }
5486 None => {
5487 n.attrs.remove("type");
5488 }
5489 }
5490 if !val.is_empty() {
5492 n.attrs.insert(String::from("value"), val);
5493 }
5494 n.attrs.remove("_live_value");
5495 }
5496 }
5497 }
5498 (Mode::Default, Mode::Value) | (Mode::DefaultOn, Mode::Value) => {
5499 if let Some(n) = self.nodes.get_mut(idx) {
5501 let v = n.attrs.get("value").cloned().unwrap_or_default();
5502 n.attrs.insert(String::from("_live_value"), v);
5503 }
5504 }
5505 (Mode::Filename, Mode::Value) => {
5506 if let Some(n) = self.nodes.get_mut(idx) {
5507 n.attrs.insert(String::from("_live_value"), String::new());
5508 }
5509 }
5510 (Mode::Value, Mode::Filename) => {
5511 if let Some(n) = self.nodes.get_mut(idx) {
5512 n.attrs.remove("_live_value");
5513 }
5514 }
5515 (Mode::Value, Mode::Value) => {
5516 if self.nodes.get(idx).is_some_and(|n| n.attrs.contains_key("_live_value")) {
5518 let cur_type = self.nodes.get(idx).and_then(|n| n.attrs.get("type").cloned());
5519 if let Some(n) = self.nodes.get_mut(idx) {
5520 match old {
5521 Some(o) => {
5522 n.attrs.insert(String::from("type"), o.to_string());
5523 }
5524 None => {
5525 n.attrs.remove("type");
5526 }
5527 }
5528 }
5529 let val = self.input_value(idx);
5530 if let Some(n) = self.nodes.get_mut(idx) {
5531 match cur_type {
5532 Some(c) => {
5533 n.attrs.insert(String::from("type"), c);
5534 }
5535 None => {
5536 n.attrs.remove("type");
5537 }
5538 }
5539 n.attrs.insert(String::from("_live_value"), val);
5540 }
5541 }
5542 }
5543 _ => {}
5544 }
5545 }
5546
5547 pub fn barred_from_validation(&self, idx: usize) -> bool {
5552 use crate::os_lib::web_apis::form_value::Kind;
5553 let Some(n) = self.nodes.get(idx) else { return true };
5554 if n.is_text {
5555 return true;
5556 }
5557 match n.tag.as_str() {
5558 "input" => {
5559 let k = self.input_kind(idx);
5560 if matches!(k, Kind::Hidden | Kind::Reset | Kind::Button) || n.attrs.contains_key("readonly") {
5562 return true;
5563 }
5564 }
5565 "button" => {
5566 if let Some(t) = n.attrs.get("type") {
5567 if t.eq_ignore_ascii_case("reset") || t.eq_ignore_ascii_case("button") {
5568 return true;
5569 }
5570 }
5571 }
5572 "textarea" => {
5573 if n.attrs.contains_key("readonly") {
5574 return true;
5575 }
5576 }
5577 "select" => {}
5578 _ => return true,
5579 }
5580 if self.is_disabled(idx) {
5581 return true;
5582 }
5583 let mut cur = n.parent;
5584 while let Some(i) = cur {
5585 match self.nodes.get(i) {
5586 Some(a) => {
5587 if a.tag == "datalist" {
5588 return true;
5589 }
5590 cur = a.parent;
5591 }
5592 None => break,
5593 }
5594 }
5595 false
5596 }
5597
5598 pub fn validity_flags(&self, idx: usize, _value: &str) -> ValidityFlags {
5602 use crate::os_lib::web_apis::form_value as fv;
5603 use crate::os_lib::web_apis::form_value::Kind;
5604 let mut f = ValidityFlags::default();
5605 let n = match self.nodes.get(idx) {
5606 Some(n) if !n.is_text && matches!(n.tag.as_str(), "button" | "input" | "select" | "textarea") => n,
5607 _ => return f,
5608 };
5609 f.custom_error = n.attrs.get("_custom_validity").map(|s| !s.is_empty()).unwrap_or(false);
5610 let required = n.attrs.contains_key("required");
5611 let readonly = n.attrs.contains_key("readonly");
5612 let disabled = self.is_disabled(idx);
5613 match n.tag.as_str() {
5614 "button" => {}
5615 "select" => {
5616 if required {
5617 f.value_missing = self.select_effective_value(idx).is_empty();
5618 }
5619 }
5620 "textarea" => {
5621 let v = self.effective_form_value(idx);
5622 f.value_missing = required && !readonly && !disabled && v.is_empty();
5623 if !v.is_empty() && !n.attrs.contains_key("_live_value") {
5625 let len = v.chars().count();
5626 if let Some(ml) = n.attrs.get("minlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5627 f.too_short = len < ml;
5628 }
5629 if let Some(ml) = n.attrs.get("maxlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5630 f.too_long = len > ml;
5631 }
5632 }
5633 }
5634 _ => {
5635 let k = self.input_kind(idx);
5636 let v = self.input_value(idx);
5637 let mutable = !disabled && !(readonly && fv::readonly_applies(k));
5638 if required && fv::required_applies(k) {
5639 f.value_missing = match k {
5640 Kind::Checkbox => !self.is_checked_node(idx),
5641 Kind::Radio => {
5642 let group: alloc::vec::Vec<usize> = if n.attrs.get("name").map(|s| s.is_empty()).unwrap_or(true) {
5644 alloc::vec![idx]
5645 } else {
5646 (0..self.nodes.len()).filter(|&i| self.same_radio_group(idx, i)).collect()
5647 };
5648 let any_required = group.iter().any(|&i| self.nodes[i].attrs.contains_key("required"));
5649 any_required && !group.iter().any(|&i| self.is_checked_node(i))
5650 }
5651 Kind::File => true,
5652 _ => mutable && v.is_empty(),
5653 };
5654 }
5655 if !v.is_empty() {
5656 if fv::text_constraints_apply(k) {
5657 if !n.attrs.contains_key("_live_value") {
5658 let len = v.chars().count();
5659 if let Some(ml) = n.attrs.get("minlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5660 f.too_short = len < ml;
5661 }
5662 if let Some(ml) = n.attrs.get("maxlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5663 f.too_long = len > ml;
5664 }
5665 }
5666 match k {
5667 Kind::Email => {
5668 f.type_mismatch = if n.attrs.contains_key("multiple") {
5669 !v.split(',').all(|p| fv::is_valid_email(p.trim()))
5670 } else {
5671 !fv::is_valid_email(&v)
5672 };
5673 }
5674 Kind::Url => f.type_mismatch = !fv::looks_like_absolute_url(&v),
5675 _ => {}
5676 }
5677 if let Some(pat) = n.attrs.get("pattern") {
5678 if !pat.is_empty() {
5679 f.pattern_mismatch = if k == Kind::Email && n.attrs.contains_key("multiple") {
5680 !v.split(',').all(|p| Self::pattern_matches(pat, p.trim()))
5681 } else {
5682 !Self::pattern_matches(pat, &v)
5683 };
5684 }
5685 }
5686 }
5687 if fv::has_number_semantics(k) {
5688 if let Some(num) = fv::string_to_number(k, &v) {
5689 let min = n.attrs.get("min").and_then(|m| fv::string_to_number(k, m));
5690 let max = n.attrs.get("max").and_then(|m| fv::string_to_number(k, m));
5691 let reversed = k == Kind::Time && matches!((min, max), (Some(a), Some(b)) if b < a);
5692 if reversed {
5693 if let (Some(a), Some(b)) = (min, max) {
5694 if num > b && num < a {
5695 f.range_underflow = true;
5696 f.range_overflow = true;
5697 }
5698 }
5699 } else {
5700 if let Some(a) = min {
5701 f.range_underflow = num < a;
5702 }
5703 if let Some(b) = max {
5704 f.range_overflow = num > b;
5705 }
5706 }
5707 let at = fv::Attrs {
5708 min: n.attrs.get("min").map(|s| s.as_str()),
5709 max: n.attrs.get("max").map(|s| s.as_str()),
5710 step: n.attrs.get("step").map(|s| s.as_str()),
5711 multiple: false,
5712 };
5713 f.step_mismatch = fv::step_mismatch(k, num, &at, n.attrs.get("value").map(|s| s.as_str()));
5714 }
5715 }
5716 }
5717 }
5718 }
5719 f
5720 }
5721
5722 fn is_checked_node(&self, idx: usize) -> bool {
5724 match self.nodes.get(idx) {
5725 Some(node) => match node.attrs.get("_live_checked") {
5726 Some(lc) => lc == "true",
5727 None => node.attrs.contains_key("checked"),
5728 },
5729 None => false,
5730 }
5731 }
5732
5733 pub fn validate_field(&self, idx: usize, _value: &str) -> Option<String> {
5735 if self.barred_from_validation(idx) {
5736 return None;
5737 }
5738 let n = self.nodes.get(idx)?;
5739 let f = self.validity_flags(idx, "");
5740 if f.custom_error {
5741 return n.attrs.get("_custom_validity").cloned();
5742 }
5743 let ty = if n.tag == "input" { crate::os_lib::web_apis::form_value::kind_name(self.input_kind(idx)) } else { "" };
5744 if f.value_missing {
5745 return Some(String::from(match ty {
5746 "checkbox" => "このフィールドをオンにしてください。",
5747 "radio" => "いずれかを選択してください。",
5748 _ => "このフィールドを入力してください。",
5749 }));
5750 }
5751 if f.too_short {
5752 let min = n.attrs.get("minlength").cloned().unwrap_or_default();
5753 let len = self.effective_form_value(idx).chars().count();
5754 return Some(alloc::format!("{}文字以上で入力してください(現在{}文字)。", min.trim(), len));
5755 }
5756 if f.too_long {
5757 let max = n.attrs.get("maxlength").cloned().unwrap_or_default();
5758 let len = self.effective_form_value(idx).chars().count();
5759 return Some(alloc::format!("{}文字以下で入力してください(現在{}文字)。", max.trim(), len));
5760 }
5761 if f.type_mismatch {
5762 return Some(String::from(match ty {
5763 "email" => "メールアドレスを入力してください。",
5764 _ => "URL を入力してください。",
5765 }));
5766 }
5767 if f.range_underflow {
5768 return Some(alloc::format!("{}以上の値を入力してください。", n.attrs.get("min").cloned().unwrap_or_default()));
5769 }
5770 if f.range_overflow {
5771 return Some(alloc::format!("{}以下の値を入力してください。", n.attrs.get("max").cloned().unwrap_or_default()));
5772 }
5773 if f.step_mismatch {
5774 return Some(String::from("有効な値を入力してください。"));
5775 }
5776 if f.bad_input {
5777 return Some(String::from("数値を入力してください。"));
5778 }
5779 if f.pattern_mismatch {
5780 return Some(String::from("要求された形式で入力してください。"));
5781 }
5782 None
5783 }
5784
5785 fn pattern_matches(pat: &str, val: &str) -> bool {
5792 if crate::os_lib::ecma::regex_syntax::pattern_error(pat, "v").is_some() {
5794 return true;
5795 }
5796 let anchored = format!("^(?:{})$", pat);
5797 let re = crate::os_lib::ecma::regex::Regex::new(&anchored, "v");
5798 let chars: alloc::vec::Vec<char> = val.chars().collect();
5799 re.find_at(&chars, 0).is_some()
5800 }
5801
5802 fn attr_names_default(&self, idx: usize) -> Vec<String> {
5804 let mut out = Vec::new();
5805 if let Some(n) = self.nodes.get(idx) {
5806 if !n.id.is_empty() || n.attrs.contains_key("id") {
5807 out.push(String::from("id"));
5808 }
5809 if !n.classes.is_empty() || n.attrs.contains_key("class") {
5810 out.push(String::from("class"));
5811 }
5812 for k in n.attrs.keys() {
5817 if k != "id" && k != "class" && !k.starts_with('_') && !k.starts_with('#') {
5818 out.push(k.clone());
5819 }
5820 }
5821 }
5822 out
5823 }
5824
5825 pub fn attr_names(&self, idx: usize) -> Vec<String> {
5827 if let Some(ord) = self.attr_ns_order.get(&idx) {
5828 return ord.iter().map(|(_, qn)| qn.clone()).collect();
5829 }
5830 let mut out = self.attr_names_default(idx);
5831 if !self.attr_order.is_empty() {
5832 if let Some(order) = self.attr_order.get(&idx) {
5833 let mut ordered: Vec<String> = Vec::with_capacity(out.len());
5834 for k in order {
5835 if let Some(p) = out.iter().position(|x| x == k) {
5836 ordered.push(out.remove(p));
5837 }
5838 }
5839 ordered.extend(out);
5840 out = ordered;
5841 }
5842 }
5843 if let Some(ns_list) = self.ns_attrs.get(&idx) {
5844 for (_, qn, _) in ns_list {
5845 out.push(qn.clone());
5846 }
5847 }
5848 out
5849 }
5850
5851 pub fn attr_entries(&self, idx: usize) -> Vec<(Option<String>, String)> {
5853 if let Some(ord) = self.attr_ns_order.get(&idx) {
5854 return ord.clone();
5855 }
5856 let mut out: Vec<(Option<String>, String)> = self
5857 .attr_names_ordered_plain(idx)
5858 .into_iter()
5859 .map(|q| (None, q))
5860 .collect();
5861 if let Some(ns_list) = self.ns_attrs.get(&idx) {
5862 for (ns, qn, _) in ns_list {
5863 out.push((Some(ns.clone()), qn.clone()));
5864 }
5865 }
5866 out
5867 }
5868
5869 fn attr_names_ordered_plain(&self, idx: usize) -> Vec<String> {
5870 let mut out = self.attr_names_default(idx);
5871 if !self.attr_order.is_empty() {
5872 if let Some(order) = self.attr_order.get(&idx) {
5873 let mut ordered: Vec<String> = Vec::with_capacity(out.len());
5874 for k in order {
5875 if let Some(p) = out.iter().position(|x| x == k) {
5876 ordered.push(out.remove(p));
5877 }
5878 }
5879 ordered.extend(out);
5880 out = ordered;
5881 }
5882 }
5883 out
5884 }
5885
5886 fn ensure_attr_ns_order(&mut self, idx: usize) {
5887 if self.attr_ns_order.contains_key(&idx) {
5888 return;
5889 }
5890 let mut entries: Vec<(Option<String>, String)> = self
5891 .attr_names_ordered_plain(idx)
5892 .into_iter()
5893 .map(|q| (None, q))
5894 .collect();
5895 if let Some(ns_list) = self.ns_attrs.get(&idx) {
5896 for (ns, qn, _) in ns_list {
5897 entries.push((Some(ns.clone()), qn.clone()));
5898 }
5899 }
5900 self.attr_ns_order.insert(idx, entries);
5901 }
5902
5903 pub fn attr_node_at(&mut self, elem: usize, pos: usize) -> Option<usize> {
5905 let (ns, qn) = self.attr_entries(elem).get(pos)?.clone();
5906 self.attr_node_for_ns(elem, ns.as_deref(), &qn)
5907 }
5908
5909 pub fn attr_order_replace(&mut self, idx: usize, before: Vec<String>, old: &str, new: &str) {
5911 let mut want: Vec<String> = Vec::with_capacity(before.len());
5912 for k in before {
5913 if k == old {
5914 want.push(new.to_string());
5915 } else if k != new {
5916 want.push(k);
5917 }
5918 }
5919 if self.attr_names(idx) != want {
5920 self.attr_order.insert(idx, want);
5921 }
5922 }
5923
5924 pub fn attr_ns_order_replace(
5926 &mut self,
5927 idx: usize,
5928 before: Vec<(Option<String>, String)>,
5929 old_ns: Option<&str>,
5930 old_q: &str,
5931 new_ns: Option<&str>,
5932 new_q: &str,
5933 ) {
5934 if self.attr_ns_order.contains_key(&idx)
5935 || old_ns.is_some()
5936 || new_ns.is_some()
5937 || before.iter().any(|(ns, _)| ns.is_some())
5938 {
5939 let mut want: Vec<(Option<String>, String)> = Vec::with_capacity(before.len());
5940 for (ns, q) in before {
5941 if ns.as_deref() == old_ns && q == old_q {
5942 want.push((new_ns.map(String::from), String::from(new_q)));
5943 } else if !(ns.as_deref() == new_ns && q == new_q) {
5944 want.push((ns, q));
5945 }
5946 }
5947 self.attr_ns_order.insert(idx, want);
5948 return;
5949 }
5950 let plain_before: Vec<String> = before.into_iter().map(|(_, q)| q).collect();
5951 self.attr_order_replace(idx, plain_before, old_q, new_q);
5952 }
5953
5954 fn attr_order_push(&mut self, idx: usize, name: &str) {
5956 if name.starts_with('_') {
5957 return;
5958 }
5959 if let Some(o) = self.attr_order.get_mut(&idx) {
5960 o.retain(|k| k != name);
5961 o.push(name.to_string());
5962 return;
5963 }
5964 let base = self.attr_names_default(idx);
5965 let rank = |k: &str| -> (u8, String) {
5966 match k {
5967 "id" => (0, String::new()),
5968 "class" => (1, String::new()),
5969 _ => (2, k.to_string()),
5970 }
5971 };
5972 if let Some(last) = base.last() {
5973 if rank(name) < rank(last) {
5974 let mut o = base;
5975 o.push(name.to_string());
5976 self.attr_order.insert(idx, o);
5977 }
5978 }
5979 }
5980
5981 pub fn add_listener(&mut self, node: usize, event: &str, func: Value) {
5982 self.add_listener_opts(node, event, func, false, false);
5983 }
5984
5985 pub fn add_listener_opts(
5988 &mut self,
5989 node: usize,
5990 event: &str,
5991 func: Value,
5992 capture: bool,
5993 once: bool,
5994 ) -> u64 {
5995 self.add_listener_opts_signal(node, event, func, capture, once, None)
5996 }
5997
5998 pub fn add_listener_opts_signal(
6001 &mut self,
6002 node: usize,
6003 event: &str,
6004 func: Value,
6005 capture: bool,
6006 once: bool,
6007 signal: Option<Value>,
6008 ) -> u64 {
6009 self.add_listener_full(node, event, func, capture, once, false, signal)
6010 }
6011
6012 #[allow(clippy::too_many_arguments)]
6014 pub fn add_listener_full(
6015 &mut self,
6016 node: usize,
6017 event: &str,
6018 func: Value,
6019 capture: bool,
6020 once: bool,
6021 passive: bool,
6022 signal: Option<Value>,
6023 ) -> u64 {
6024 if signal.as_ref().is_some_and(is_signal_aborted) {
6025 return 0;
6026 }
6027 if self.listeners.iter().any(|l| {
6029 l.node == node && l.event == event && l.capture == capture && l.func.same_ref(&func)
6030 }) {
6031 return 0;
6032 }
6033 let id = self.next_listener_id;
6034 self.next_listener_id += 1;
6035 self.listeners.push(Listener {
6036 node,
6037 event: event.to_string(),
6038 func,
6039 capture,
6040 once,
6041 passive,
6042 id,
6043 signal,
6044 });
6045 id
6046 }
6047
6048 pub fn remove_listener(&mut self, node: usize, event: &str, func: &Value, capture: bool) {
6050 self.listeners.retain(|l| {
6051 !(l.node == node && l.event == event && l.capture == capture && l.func.same_ref(func))
6052 });
6053 }
6054
6055 pub fn remove_listener_by_id(&mut self, id: u64) {
6057 self.listeners.retain(|l| l.id != id);
6058 }
6059
6060 pub fn has_listener_by_id(&self, id: u64) -> bool {
6061 self.listeners.iter().any(|l| l.id == id)
6062 }
6063
6064 pub fn has_listener(&self, event: &str) -> bool {
6066 self.listeners.iter().any(|l| l.event == event)
6067 }
6068
6069 pub fn listeners_for(&self, node: usize, event: &str) -> Vec<Value> {
6073 self.listeners
6074 .iter()
6075 .filter(|l| l.node == node && l.event == event && !l.capture && !is_listener_aborted(l))
6076 .map(|l| l.func.clone())
6077 .collect()
6078 }
6079
6080 pub fn listeners_phase(
6084 &self,
6085 node: usize,
6086 event: &str,
6087 want_capture: bool,
6088 ) -> Vec<(Value, bool, bool, u64, Option<Value>)> {
6089 self.listeners
6090 .iter()
6091 .filter(|l| l.node == node && l.event == event && l.capture == want_capture && !is_listener_aborted(l))
6092 .map(|l| (l.func.clone(), l.once, l.passive, l.id, l.signal.clone()))
6093 .collect()
6094 }
6095
6096 pub fn has_listener_on(&self, node: usize, event: &str) -> bool {
6098 self.listeners
6099 .iter()
6100 .any(|l| l.node == node && l.event == event)
6101 }
6102
6103 pub fn apply_overrides(&self, root: &mut Node) {
6105 let mut counter = 0usize;
6106 self.apply_node(root, &mut counter);
6107 }
6108 fn apply_node(&self, node: &mut Node, counter: &mut usize) {
6109 let idx = *counter;
6110 *counter += 1;
6111 if let Some(dn) = self.nodes.get(idx) {
6112 match &mut node.node_type {
6113 NodeType::Text(t) => {
6114 if let Some(ov) = &dn.text_override {
6115 *t = ov.clone();
6116 }
6117 }
6118 NodeType::Element {
6119 attributes,
6120 classes,
6121 ..
6122 } => {
6123 if dn.classes_dirty {
6124 *classes = dn.classes.clone();
6125 attributes.insert("class".to_string(), dn.classes.join(" "));
6126 }
6127 if dn.style_dirty {
6128 attributes.insert("style".to_string(), serialize_inline_style(&dn.style));
6129 }
6130 }
6131 }
6132 }
6133 for c in &mut node.children {
6134 self.apply_node(c, counter);
6135 }
6136 }
6137}
6138
6139fn html_escape_attr(s: &str) -> String {
6141 let mut o = String::new();
6142 crate::os_lib::dom::serializer::escape_attr_value(s, Some('"'), &mut o);
6143 o
6144}
6145
6146fn strip_style_priority(raw: &str) -> (&str, bool) {
6152 let trimmed = raw.trim_end();
6153 if let Some(pos) = trimmed.to_ascii_lowercase().rfind("!important") {
6154 if trimmed.get(pos..).unwrap_or("").eq_ignore_ascii_case("!important") {
6155 let before = trimmed.get(..pos).unwrap_or("").trim_end();
6156 return (before, true);
6157 }
6158 }
6159 (raw, false)
6160}
6161
6162pub(crate) fn parse_inline_style(s: &str) -> BTreeMap<String, String> {
6164 let mut m = BTreeMap::new();
6165 for decl in s.split(';') {
6166 let decl = decl.trim();
6167 if decl.is_empty() {
6168 continue;
6169 }
6170 if let Some(colon) = decl.find(':') {
6171 let k = decl.get(..colon).unwrap_or("").trim().to_lowercase();
6172 let v = decl.get(colon + 1..).unwrap_or("").trim().to_string();
6173 if !k.is_empty() && (!v.is_empty() || k.starts_with("--")) {
6175 m.insert(k, v);
6176 }
6177 }
6178 }
6179 m
6180}
6181
6182fn serialize_inline_style(m: &BTreeMap<String, String>) -> String {
6183 let mut parts = Vec::new();
6184 for (k, v) in m {
6185 parts.push(format!("{}: {}", k, v));
6186 }
6187 parts.join("; ")
6188}
6189
6190fn css_prop_from_camel(prop: &str) -> String {
6192 if prop.contains('-') || !prop.chars().any(|c| c.is_ascii_uppercase()) {
6193 return prop.to_lowercase();
6194 }
6195 let mut out = String::new();
6196 for c in prop.chars() {
6197 if c.is_ascii_uppercase() {
6198 out.push('-');
6199 out.push(c.to_ascii_lowercase());
6200 } else {
6201 out.push(c);
6202 }
6203 }
6204 out
6205}
6206
6207#[derive(Debug, Clone, PartialEq)]
6209pub enum CeEvent {
6210 Attr(usize, String, Option<String>, Option<String>),
6212 Inserted(usize),
6214 Removed(usize),
6216 Created(usize),
6218}
6219
6220impl DomBridge {
6221 pub fn subtree_elements(&self, root: usize) -> Vec<usize> {
6223 let mut out = Vec::new();
6224 let mut stack = alloc::vec![root];
6225 while let Some(i) = stack.pop() {
6226 let Some(n) = self.nodes.get(i) else { continue };
6227 if n.is_text {
6228 continue;
6229 }
6230 out.push(i);
6231 if let Some(shadow_desc) = self.shadow_tree.get_by_host(i) {
6233 stack.push(shadow_desc.root_node_idx);
6234 }
6235 for &c in n.children.iter().rev() {
6236 stack.push(c);
6237 }
6238 }
6239 out
6240 }
6241
6242 pub fn clean_unreachable_nodes<F>(&mut self, is_node_referenced: F) -> usize
6250 where
6251 F: Fn(usize) -> bool,
6252 {
6253 if self.nodes.is_empty() {
6254 return 0;
6255 }
6256
6257 let total_nodes = self.nodes.len();
6258 let get_parent = |i: usize| -> Option<usize> {
6259 self.nodes.get(i).and_then(|n| n.parent)
6260 };
6261 let get_children = |i: usize| -> Vec<usize> {
6266 let Some(n) = self.nodes.get(i) else { return Vec::new() };
6267 crate::os_lib::ecma::gc_policy::children_with_links(
6268 &n.children,
6269 self.shadow_tree.get_by_host(i).map(|d| d.root_node_idx),
6270 crate::os_lib::ecma::gc_policy::parse_content_frag(n.attrs.get("_content_frag").map(|s| s.as_str())),
6271 )
6272 };
6273
6274 let mut reachable = crate::os_lib::ecma::gc_policy::find_reachable_dom_nodes(total_nodes, get_parent, get_children, is_node_referenced);
6275
6276 loop {
6281 let mut add: Vec<usize> = Vec::new();
6282 for (&i, m) in self.expandos.iter() {
6283 if reachable.contains(&i) {
6284 continue;
6285 }
6286 if let Some(Value::Object(o)) = m.get("host") {
6287 if let Ok(b) = o.try_borrow() {
6288 if let Some(h) = b.kind.dom_node() {
6289 if reachable.contains(&h) {
6290 add.push(i);
6291 }
6292 }
6293 }
6294 }
6295 if let Some(Value::Object(sh)) = m.get("__shady") {
6300 if let Ok(sb) = sh.try_borrow() {
6301 if let Some(Value::Object(po)) = sb.props.get("parentNode") {
6302 if let Ok(pb) = po.try_borrow() {
6303 if let Some(h) = pb.kind.dom_node() {
6304 if reachable.contains(&h) {
6305 add.push(i);
6306 }
6307 }
6308 }
6309 }
6310 }
6311 }
6312 }
6313 if add.is_empty() {
6314 break;
6315 }
6316 let mut stack = add;
6318 while let Some(i) = stack.pop() {
6319 if !reachable.insert(i) {
6320 continue;
6321 }
6322 if let Some(n) = self.nodes.get(i) {
6323 for &c in n.children.iter() {
6324 if c < total_nodes && !reachable.contains(&c) {
6325 stack.push(c);
6326 }
6327 }
6328 if let Some(f) = crate::os_lib::ecma::gc_policy::parse_content_frag(n.attrs.get("_content_frag").map(|s| s.as_str())) {
6330 if f < total_nodes && !reachable.contains(&f) {
6331 stack.push(f);
6332 }
6333 }
6334 }
6335 }
6336 }
6337
6338 let mut cleaned_nodes = 0;
6340 for i in 1..total_nodes {
6341 if reachable.contains(&i) {
6342 continue;
6343 }
6344 let had_expando = self.expandos.remove(&i).is_some();
6345 let had_accessor = self.node_accessors.remove(&i).is_some();
6346 let had_proto = self.node_protos.remove(&i).is_some();
6347 let had_rect = self.rects.remove(&i).is_some();
6348 let had_measured = self.measured.remove(&i).is_some();
6349 let had_border = self.border_widths.remove(&i).is_some();
6350 let had_style = self.computed_styles.remove(&i).is_some();
6351 let had_scroll = self.scroll_tops.remove(&i).is_some()
6352 || self.scroll_lefts.remove(&i).is_some()
6353 || self.scroll_heights.remove(&i).is_some()
6354 || self.scroll_widths.remove(&i).is_some();
6355
6356 if had_expando || had_accessor || had_proto || had_rect || had_measured || had_border || had_style || had_scroll {
6357 cleaned_nodes += 1;
6358 }
6359 }
6360
6361 let prev_listeners_len = self.listeners.len();
6363 self.listeners.retain(|l| reachable.contains(&l.node));
6364 let cleaned_listeners = prev_listeners_len.saturating_sub(self.listeners.len());
6365
6366 cleaned_nodes + cleaned_listeners
6367 }
6368}
6369
6370#[inline]
6374fn bridge_poll() -> bool {
6375 #[cfg(target_os = "none")]
6376 return crate::os_lib::platform::layout_poll();
6377 #[cfg(not(target_os = "none"))]
6378 false
6379}
6380
6381#[inline]
6383fn bridge_aborting() -> bool {
6384 #[cfg(target_os = "none")]
6385 return crate::os_lib::platform::layout_aborting();
6386 #[cfg(not(target_os = "none"))]
6387 false
6388}
6389
6390pub const HOST_DOM_ELEMENT: u8 = HOST_CLASS_BY_ID;
6395pub const HOST_DOCUMENT: u8 = 1;
6397pub const HOST_STYLE: u8 = 2 | HOST_CLASS_BY_ID;
6399pub const HOST_CLASSLIST: u8 = 3 | HOST_CLASS_BY_ID;
6401pub const HOST_DATASET: u8 = 4 | HOST_CLASS_BY_ID;
6403pub const HOST_COMPUTED: u8 = 5;
6405pub const HOST_STYLESHEET: u8 = 6;
6407pub const HOST_STORAGE: u8 = 7;
6409pub const HOST_CSSRULE: u8 = 8;
6411pub const HOST_ATTRS: u8 = 9 | HOST_CLASS_BY_ID;
6413pub const HOST_TOKENLIST_RELLIST: u8 = 10 | HOST_CLASS_BY_ID;
6415pub const HOST_TOKENLIST_SANDBOX: u8 = 11 | HOST_CLASS_BY_ID;
6417pub const HOST_TOKENLIST_HTMLFOR: u8 = 12 | HOST_CLASS_BY_ID;
6419pub const HOST_TOKENLIST_SIZES: u8 = 13 | HOST_CLASS_BY_ID;
6421pub const HOST_TOKENLIST_BLOCKING: u8 = 14 | HOST_CLASS_BY_ID;
6423pub const HOST_TOKENLIST_PART: u8 = 15 | HOST_CLASS_BY_ID;
6425pub const HOST_HTMLCOLLECTION: u8 = 16;
6427pub const HOST_NODELIST: u8 = 17 | HOST_CLASS_BY_ID;
6429pub const HOST_STATIC_NODELIST: u8 = 18;
6431
6432#[derive(Clone)]
6434pub enum HtmlCollectionKind {
6435 ByTagName { root: Option<usize>, include_root: bool, qname: String },
6436 ByTagNameNS { root: Option<usize>, include_root: bool, ns: Option<String>, local: String },
6437 ByClassName { root: Option<usize>, class_names: String },
6438 Children { root: Option<usize> },
6439}
6440
6441impl DomBridge {
6442 pub fn new_html_collection(&mut self, kind: HtmlCollectionKind) -> usize {
6444 let id = self.html_collections.len();
6445 self.html_collections.push(kind);
6446 id
6447 }
6448
6449 pub fn html_collection_items(&self, col_id: usize) -> Vec<usize> {
6451 let Some(kind) = self.html_collections.get(col_id) else {
6452 return Vec::new();
6453 };
6454 match kind {
6455 HtmlCollectionKind::ByTagName { root, include_root, qname } => {
6456 let r = match root {
6457 Some(i) => *i,
6458 None => {
6459 if self.nodes.is_empty() {
6460 return Vec::new();
6461 }
6462 0
6463 }
6464 };
6465 walk_elements(self, r, *include_root)
6466 .into_iter()
6467 .filter(|&i| {
6468 self.nodes
6469 .get(i)
6470 .is_some_and(|n| matches_qualified_name(n, qname))
6471 })
6472 .collect()
6473 }
6474 HtmlCollectionKind::ByTagNameNS { root, include_root, ns, local } => {
6475 let r = match root {
6476 Some(i) => *i,
6477 None => {
6478 if self.nodes.is_empty() {
6479 return Vec::new();
6480 }
6481 0
6482 }
6483 };
6484 walk_elements(self, r, *include_root)
6485 .into_iter()
6486 .filter(|&i| {
6487 self.nodes
6488 .get(i)
6489 .is_some_and(|n| matches_ns_local(n, ns.as_deref(), local))
6490 })
6491 .collect()
6492 }
6493 HtmlCollectionKind::ByClassName { root, class_names } => {
6494 self.get_elements_by_class_name(*root, class_names)
6495 }
6496 HtmlCollectionKind::Children { root } => match root {
6497 Some(idx) => {
6498 if self.nodes.get(*idx).is_some_and(|n| n.tag == "template") {
6499 Vec::new()
6500 } else {
6501 self.element_children(*idx)
6502 }
6503 }
6504 None => self.query("html").into_iter().collect(),
6505 },
6506 }
6507 }
6508
6509 pub fn html_collection_named_item(&self, col_id: usize, name: &str) -> Option<usize> {
6511 if name.is_empty() {
6512 return None;
6513 }
6514 for idx in self.html_collection_items(col_id) {
6515 if self.get_attr(idx, "id").as_deref() == Some(name) {
6516 return Some(idx);
6517 }
6518 let is_html = self
6519 .nodes
6520 .get(idx)
6521 .and_then(node_namespace)
6522 .as_deref()
6523 == Some(HTML_NS_URI);
6524 if is_html && self.get_attr(idx, "name").as_deref() == Some(name) {
6525 return Some(idx);
6526 }
6527 }
6528 None
6529 }
6530
6531 pub fn html_collection_supported_names(&self, col_id: usize) -> Vec<String> {
6533 let mut out = Vec::new();
6534 let mut seen = BTreeSet::new();
6535 for idx in self.html_collection_items(col_id) {
6536 if let Some(id) = self.get_attr(idx, "id").filter(|s| !s.is_empty()) {
6537 if seen.insert(id.clone()) {
6538 out.push(id);
6539 }
6540 }
6541 let is_html = self
6542 .nodes
6543 .get(idx)
6544 .and_then(node_namespace)
6545 .as_deref()
6546 == Some(HTML_NS_URI);
6547 if is_html {
6548 if let Some(nm) = self.get_attr(idx, "name").filter(|s| !s.is_empty()) {
6549 if seen.insert(nm.clone()) {
6550 out.push(nm);
6551 }
6552 }
6553 }
6554 }
6555 out
6556 }
6557
6558 pub fn html_collection_entries(&self, col_id: usize) -> Vec<(String, String)> {
6560 let items = self.html_collection_items(col_id);
6561 let mut out = Vec::with_capacity(items.len());
6562 let mut seen = BTreeSet::new();
6563 for i in 0..items.len() {
6564 let k = i.to_string();
6565 seen.insert(k.clone());
6566 out.push((k, String::new()));
6567 }
6568 for name in self.html_collection_supported_names(col_id) {
6569 if seen.insert(name.clone()) {
6570 out.push((name, String::new()));
6571 }
6572 }
6573 if let Some(exp) = self.html_collection_expandos.get(&col_id) {
6574 for k in exp.keys() {
6575 if seen.insert(k.clone()) {
6576 out.push((k.clone(), String::new()));
6577 }
6578 }
6579 }
6580 out
6581 }
6582
6583 pub fn attrs_map_entries(&self, elem_idx: usize) -> Vec<(String, String)> {
6585 let entries = self.attr_entries(elem_idx);
6586 let mut out = Vec::with_capacity(entries.len() * 2);
6587 let mut seen = BTreeSet::new();
6588 for i in 0..entries.len() {
6589 let k = i.to_string();
6590 seen.insert(k.clone());
6591 out.push((k, String::new()));
6592 }
6593 let html_elem_in_html_doc = self.nodes.get(elem_idx).is_some_and(|n| {
6594 !n.attrs.contains_key("_xml")
6595 && node_namespace(n).as_deref() == Some(HTML_NS_URI)
6596 && self.doc_is_html(self.node_document(elem_idx))
6597 });
6598 for (_, name) in entries {
6599 if html_elem_in_html_doc && name.bytes().any(|b| b.is_ascii_uppercase()) {
6600 continue;
6601 }
6602 if seen.insert(name.clone()) {
6603 out.push((name, String::new()));
6604 }
6605 }
6606 out
6607 }
6608
6609 pub fn node_list_items(&self, id: usize) -> Vec<usize> {
6611 if id == usize::MAX - 1 {
6612 let mut v: Vec<usize> = self.main_doctype.into_iter().collect();
6613 if !self.nodes.is_empty() {
6614 v.push(0);
6615 }
6616 return v;
6617 }
6618 match self.nodes.get(id) {
6619 Some(n) if n.tag != "template" => n.children.clone(),
6620 _ => Vec::new(),
6621 }
6622 }
6623
6624 pub fn node_list_entries(&self, id: usize) -> Vec<(String, String)> {
6626 let len = self.node_list_items(id).len();
6627 (0..len).map(|i| (i.to_string(), String::new())).collect()
6628 }
6629
6630 pub fn new_static_node_list(&mut self, items: Vec<usize>) -> usize {
6632 let id = self.static_node_lists.len();
6633 self.static_node_lists.push(items);
6634 id
6635 }
6636
6637 pub fn static_node_list_items(&self, id: usize) -> &[usize] {
6639 self.static_node_lists.get(id).map(|v| v.as_slice()).unwrap_or(&[])
6640 }
6641
6642 pub fn static_node_list_entries(&self, id: usize) -> Vec<(String, String)> {
6644 let len = self.static_node_list_items(id).len();
6645 (0..len).map(|i| (i.to_string(), String::new())).collect()
6646 }
6647}
6648
6649#[inline]
6651pub const fn is_token_list_host(class: u8) -> bool {
6652 matches!(
6653 class,
6654 HOST_CLASSLIST
6655 | HOST_TOKENLIST_RELLIST
6656 | HOST_TOKENLIST_SANDBOX
6657 | HOST_TOKENLIST_HTMLFOR
6658 | HOST_TOKENLIST_SIZES
6659 | HOST_TOKENLIST_BLOCKING
6660 | HOST_TOKENLIST_PART
6661 )
6662}
6663
6664#[inline]
6666pub const fn token_list_attr(class: u8) -> Option<&'static str> {
6667 match class {
6668 HOST_CLASSLIST => Some("class"),
6669 HOST_TOKENLIST_RELLIST => Some("rel"),
6670 HOST_TOKENLIST_SANDBOX => Some("sandbox"),
6671 HOST_TOKENLIST_HTMLFOR => Some("for"),
6672 HOST_TOKENLIST_SIZES => Some("sizes"),
6673 HOST_TOKENLIST_BLOCKING => Some("blocking"),
6674 HOST_TOKENLIST_PART => Some("part"),
6675 _ => None,
6676 }
6677}
6678pub const STORAGE_LOCAL: usize = 0;
6680pub const STORAGE_SESSION: usize = 1;
6681
6682impl ObjKind {
6683 #[inline]
6685 pub fn dom_node(&self) -> Option<usize> {
6686 match self {
6687 ObjKind::HostRef(h) if h.class == HOST_DOM_ELEMENT => Some(h.id),
6688 _ => None,
6689 }
6690 }
6691}
6692
6693impl Obj {
6694 pub fn dom(node_idx: usize) -> ObjRef {
6696 Obj::host_ref(HostRef { class: HOST_DOM_ELEMENT, id: node_idx })
6697 }
6698 pub fn dom_host(class: u8, id: usize) -> ObjRef {
6700 Obj::host_ref(HostRef { class, id })
6701 }
6702}
6703
6704pub(crate) fn split_ascii_ws(s: &str) -> Vec<String> {
6706 s.split([' ', '\t', '\n', '\x0c', '\r'])
6707 .filter(|t| !t.is_empty())
6708 .map(String::from)
6709 .collect()
6710}
6711
6712const HTML_NS_URI: &str = "http://www.w3.org/1999/xhtml";
6713const SVG_NS_URI: &str = "http://www.w3.org/2000/svg";
6714const MATHML_NS_URI: &str = "http://www.w3.org/1998/Math/MathML";
6715
6716pub(crate) fn node_namespace(n: &DomNode) -> Option<String> {
6718 if let Some(v) = n.attrs.get("_ns") {
6719 return if v.is_empty() { None } else { Some(v.clone()) };
6720 }
6721 match n.attrs.get("#ns").map(|s| s.as_str()) {
6722 Some("svg") => Some(String::from(SVG_NS_URI)),
6723 Some("math") => Some(String::from(MATHML_NS_URI)),
6724 _ => Some(String::from(HTML_NS_URI)),
6725 }
6726}
6727
6728pub(crate) fn node_local_name(n: &DomNode) -> String {
6730 match n.attrs.get("_qname") {
6731 Some(q) => match q.split_once(':') {
6732 Some((_, l)) if n.attrs.contains_key("_prefix") => String::from(l),
6733 _ => q.clone(),
6734 },
6735 None => n.tag.clone(),
6736 }
6737}
6738
6739pub(crate) fn walk_elements(dom: &DomBridge, root: usize, include_root: bool) -> Vec<usize> {
6741 let mut out = Vec::new();
6742 let mut stack: Vec<usize> = alloc::vec![root];
6743 while let Some(i) = stack.pop() {
6744 let Some(n) = dom.nodes.get(i) else { continue };
6745 if n.is_text {
6746 continue;
6747 }
6748 if (i != root || include_root) && !n.tag.starts_with('#') {
6749 out.push(i);
6750 }
6751 for &c in n.children.iter().rev() {
6752 stack.push(c);
6753 }
6754 }
6755 out
6756}
6757
6758pub(crate) fn matches_qualified_name(n: &DomNode, name: &str) -> bool {
6760 if name == "*" {
6761 return true;
6762 }
6763 let qname = n.attrs.get("_qname").cloned().unwrap_or_else(|| n.tag.clone());
6764 if node_namespace(n).as_deref() == Some(HTML_NS_URI) && !n.attrs.contains_key("_xml") {
6765 qname == name.to_ascii_lowercase()
6766 } else {
6767 qname == name
6768 }
6769}
6770
6771pub(crate) fn matches_ns_local(n: &DomNode, ns: Option<&str>, local: &str) -> bool {
6773 let ns_ok = match ns {
6774 Some("*") => true,
6775 other => node_namespace(n).as_deref() == other.filter(|s| !s.is_empty()),
6776 };
6777 ns_ok && (local == "*" || node_local_name(n) == local)
6778}