Skip to main content

strata/runtime/
dom_hydration.rs

1//! Live Client-Side DOM Mutation and Dynamic Hydration Engine.
2//!
3//! Synchronizes in-memory ECMAScript `DomNode` mutations from `strata_js`
4//! into the live `AppRuntime` presentation and layout tree without page reloads.
5
6use std::sync::mpsc::{channel, Sender};
7use strata_dom::{Attribute, ClassList, EntityId, NodeBlueprint, Tag};
8use strata_js::{DomMutationRecord, DomMutationType, DomNode, DomNodeType};
9use strata_layout::LayoutNode;
10
11use super::AppRuntime;
12
13/// Maps a tag string to a strongly-typed Strata DOM `Tag`.
14pub fn parse_dom_tag(tag: &str) -> Tag {
15    match tag.to_ascii_lowercase().as_str() {
16        "div" | "html" | "body" => Tag::Div,
17        "span" => Tag::Span,
18        "p" => Tag::P,
19        "h1" => Tag::H1,
20        "h2" => Tag::H2,
21        "h3" => Tag::H3,
22        "h4" => Tag::H4,
23        "h5" => Tag::H5,
24        "h6" => Tag::H6,
25        "button" => Tag::Button,
26        "input" => Tag::Input,
27        "select" => Tag::Select,
28        "option" => Tag::Option,
29        "textarea" => Tag::Textarea,
30        "label" => Tag::Label,
31        "form" => Tag::Form,
32        "header" => Tag::Header,
33        "nav" => Tag::Nav,
34        "main" => Tag::Main,
35        "section" => Tag::Section,
36        "aside" => Tag::Aside,
37        "footer" => Tag::Footer,
38        "ul" => Tag::Ul,
39        "ol" => Tag::Ol,
40        "li" => Tag::Li,
41        "a" => Tag::A,
42        "img" => Tag::Img,
43        "svg" => Tag::Svg,
44        "path" => Tag::Path,
45        "canvas" => Tag::Canvas,
46        "table" => Tag::Table,
47        "thead" => Tag::Thead,
48        "tbody" => Tag::Tbody,
49        "tr" => Tag::Tr,
50        "th" => Tag::Th,
51        "td" => Tag::Td,
52        "hr" => Tag::Hr,
53        "br" => Tag::Br,
54        _ => Tag::Div,
55    }
56}
57
58/// Recursively converts a `strata_js::DomNode` into a native Strata `NodeBlueprint`
59/// assigning valid EntityIds and retaining DOM node UIDs.
60pub fn dom_node_to_blueprint(node: &DomNode) -> NodeBlueprint {
61    let inner = node.inner.borrow();
62    match &inner.node_type {
63        DomNodeType::Text(text) => NodeBlueprint::Text(text.clone()),
64        DomNodeType::Comment(_) => NodeBlueprint::Empty,
65        DomNodeType::Element {
66            tag,
67            attributes,
68            style,
69        } => {
70            let entity_id = EntityId::next();
71            let mut attrs: Vec<Attribute> = Vec::with_capacity(attributes.len() + 3);
72            attrs.push(Attribute::Entity(entity_id));
73            attrs.push(Attribute::property(
74                "data-strata-node-uid",
75                node.uid().to_string(),
76            ));
77
78            let mut class_str = String::new();
79            for (k, v) in attributes {
80                if k == "class" {
81                    class_str = v.clone();
82                } else if k != "data-strata-node-uid" {
83                    attrs.push(Attribute::property(k.clone(), v.clone()));
84                }
85            }
86
87            if !style.is_empty() {
88                let formatted_style = style
89                    .iter()
90                    .map(|(k, v)| format!("{k}: {v};"))
91                    .collect::<Vec<_>>()
92                    .join(" ");
93                attrs.push(Attribute::property("style", formatted_style));
94            }
95
96            let children: Vec<NodeBlueprint> =
97                inner.children.iter().map(dom_node_to_blueprint).collect();
98
99            let classes = if class_str.is_empty() {
100                ClassList::empty()
101            } else {
102                ClassList::from(
103                    class_str
104                        .split_whitespace()
105                        .map(|s| s.to_string())
106                        .collect::<Vec<_>>(),
107                )
108            };
109
110            NodeBlueprint::Element {
111                tag: parse_dom_tag(tag.as_str()),
112                classes,
113                attributes: attrs,
114                children,
115            }
116        }
117    }
118}
119
120/// Recursively resolves a mutable reference to a blueprint node along an index path.
121pub(crate) fn find_blueprint_node_mut<'a>(
122    root: &'a mut NodeBlueprint,
123    path: &[usize],
124) -> Option<&'a mut NodeBlueprint> {
125    let mut curr = root;
126    for &idx in path {
127        match curr {
128            NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
129                if idx >= children.len() {
130                    return None;
131                }
132                curr = &mut children[idx];
133            }
134            _ => return None,
135        }
136    }
137    Some(curr)
138}
139
140impl AppRuntime {
141    /// Registers a background channel receiver for DOM mutations and returns the transmitting sender.
142    pub fn register_dom_mutation_channel(&mut self) -> Sender<DomMutationRecord> {
143        let (tx, rx) = channel();
144        self.dom_mutation_receiver = Some(rx);
145        tx
146    }
147
148    /// Polls pending DOM mutations from the registered channel and hydrates them into the presentation tree.
149    /// Returns `true` if any mutations were processed and a frame redraw is required.
150    pub fn poll_dom_mutations(&mut self, document: Option<&strata_js::Document>) -> bool {
151        let records = if let Some(ref rx) = self.dom_mutation_receiver {
152            let mut list = Vec::new();
153            while let Ok(rec) = rx.try_recv() {
154                list.push(rec);
155            }
156            list
157        } else {
158            Vec::new()
159        };
160
161        if records.is_empty() {
162            false
163        } else {
164            self.hydrate_dom_mutations(&records, document)
165        }
166    }
167
168    /// Hydrates a sequence of fine-grained DOM mutation records directly into the live layout tree.
169    pub fn hydrate_dom_mutations(
170        &mut self,
171        records: &[DomMutationRecord],
172        document: Option<&strata_js::Document>,
173    ) -> bool {
174        let mut any_hydrated = false;
175        for record in records {
176            if self.hydrate_dom_mutation(record, document) {
177                any_hydrated = true;
178            }
179        }
180        any_hydrated
181    }
182
183    /// Hydrates an individual DOM mutation record in-place without triggering a full page transpile.
184    pub fn hydrate_dom_mutation(
185        &mut self,
186        record: &DomMutationRecord,
187        document: Option<&strata_js::Document>,
188    ) -> bool {
189        match &record.mutation {
190            DomMutationType::TextContentChanged { node_uid, new_text } => {
191                let path = match self.root_blueprint.find_path_by_dom_uid(*node_uid) {
192                    Some(p) => p,
193                    None => return false,
194                };
195
196                // 1. Update blueprint tree node
197                if let Some(bp) = find_blueprint_node_mut(&mut self.root_blueprint, &path) {
198                    if let NodeBlueprint::Element {
199                        ref mut children, ..
200                    } = bp
201                    {
202                        children.clear();
203                        children.push(NodeBlueprint::Text(new_text.clone()));
204                    }
205                }
206
207                // 2. Update layout tree node and measure text bounds
208                if let Some(node) = Self::find_layout_node_mut(&mut self.layout_root, &path) {
209                    node.text = Some(new_text.clone());
210                    node.children.clear();
211                    let is_mono = strata_layout::is_monospace_family(node.style.font_family);
212                    let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
213                        new_text,
214                        node.style.font_size,
215                        node.style.line_height,
216                        None,
217                        is_mono,
218                        node.style.font_family,
219                        node.style.font_weight,
220                        node.style.font_style,
221                    );
222                    node.style.width = strata_style::types::Dimension::Px(w);
223                    node.style.height = strata_style::types::Dimension::Px(h);
224                    node.geometry.content_box.width = w;
225                    node.geometry.content_box.height = h;
226                    node.geometry.padding_box.width = w;
227                    node.geometry.padding_box.height = h;
228                    node.geometry.border_box.width = w;
229                    node.geometry.border_box.height = h;
230                }
231
232                // 3. Mark layout cache invalid along path and perform incremental relayout
233                self.incremental_relayout(&path)
234            }
235
236            DomMutationType::AttributeSet {
237                node_uid,
238                name,
239                value,
240            } => {
241                let path = match self.root_blueprint.find_path_by_dom_uid(*node_uid) {
242                    Some(p) => p,
243                    None => return false,
244                };
245
246                if let Some(bp) = find_blueprint_node_mut(&mut self.root_blueprint, &path) {
247                    if let NodeBlueprint::Element {
248                        ref mut attributes,
249                        ref mut classes,
250                        ..
251                    } = bp
252                    {
253                        if name == "class" {
254                            let class_list = if value.is_empty() {
255                                ClassList::empty()
256                            } else {
257                                ClassList::from(
258                                    value
259                                        .split_whitespace()
260                                        .map(|s| s.to_string())
261                                        .collect::<Vec<_>>(),
262                                )
263                            };
264                            *classes = class_list;
265                        } else if let Some(pos) = attributes.iter().position(|a| match a {
266                            Attribute::Property { key, .. } => key == name,
267                            _ => false,
268                        }) {
269                            attributes[pos] = Attribute::property(name.clone(), value.clone());
270                        } else {
271                            attributes.push(Attribute::property(name.clone(), value.clone()));
272                        }
273                    }
274                }
275
276                if let Some(bp) = self.root_blueprint.find_by_dom_uid(*node_uid).cloned() {
277                    let ctx = self.interaction_context();
278                    let rebuilt = Self::build_layout_tree_with_interaction(&bp, &ctx);
279                    if let Some(target) = Self::find_layout_node_mut(&mut self.layout_root, &path) {
280                        target.style = rebuilt.style.clone();
281                    }
282                }
283
284                self.incremental_relayout(&path)
285            }
286
287            DomMutationType::AttributeRemoved { node_uid, name } => {
288                let path = match self.root_blueprint.find_path_by_dom_uid(*node_uid) {
289                    Some(p) => p,
290                    None => return false,
291                };
292
293                if let Some(bp) = find_blueprint_node_mut(&mut self.root_blueprint, &path) {
294                    if let NodeBlueprint::Element {
295                        ref mut attributes,
296                        ref mut classes,
297                        ..
298                    } = bp
299                    {
300                        if name == "class" {
301                            *classes = ClassList::empty();
302                        } else {
303                            attributes.retain(|a| match a {
304                                Attribute::Property { key, .. } => key != name,
305                                _ => true,
306                            });
307                        }
308                    }
309                }
310
311                if let Some(bp) = self.root_blueprint.find_by_dom_uid(*node_uid).cloned() {
312                    let ctx = self.interaction_context();
313                    let rebuilt = Self::build_layout_tree_with_interaction(&bp, &ctx);
314                    if let Some(target) = Self::find_layout_node_mut(&mut self.layout_root, &path) {
315                        target.style = rebuilt.style.clone();
316                    }
317                }
318
319                self.incremental_relayout(&path)
320            }
321
322            DomMutationType::StyleChanged {
323                node_uid,
324                property: _,
325                value: _,
326            } => {
327                let path = match self.root_blueprint.find_path_by_dom_uid(*node_uid) {
328                    Some(p) => p,
329                    None => return false,
330                };
331
332                if let Some(doc) = document {
333                    if let Some(dom_node) = doc.get_element_by_uid(*node_uid) {
334                        let new_bp = dom_node_to_blueprint(&dom_node);
335                        let ctx = self.interaction_context();
336                        let rebuilt = Self::build_layout_tree_with_interaction(&new_bp, &ctx);
337                        if let Some(target) =
338                            Self::find_layout_node_mut(&mut self.layout_root, &path)
339                        {
340                            target.style = rebuilt.style.clone();
341                        }
342                    }
343                }
344
345                self.incremental_relayout(&path)
346            }
347
348            DomMutationType::ChildAppended {
349                parent_uid,
350                child_uid,
351            } => {
352                let parent_path = match self.root_blueprint.find_path_by_dom_uid(*parent_uid) {
353                    Some(p) => p,
354                    None => return false,
355                };
356
357                let child_bp = if let Some(doc) = document {
358                    if let Some(child_dom) = doc.get_element_by_uid(*child_uid) {
359                        dom_node_to_blueprint(&child_dom)
360                    } else {
361                        return false;
362                    }
363                } else {
364                    return false;
365                };
366
367                // Append to blueprint
368                if let Some(parent_bp) =
369                    find_blueprint_node_mut(&mut self.root_blueprint, &parent_path)
370                {
371                    if let NodeBlueprint::Element {
372                        ref mut children, ..
373                    } = parent_bp
374                    {
375                        children.push(child_bp.clone());
376                    }
377                }
378
379                // Append to layout tree
380                let parent_style = Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
381                    .map(|n| n.style.clone());
382                let child_layout =
383                    Self::build_layout_tree_with_parent(&child_bp, parent_style.as_ref());
384                if let Some(parent_layout) =
385                    Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
386                {
387                    parent_layout.children.push(child_layout);
388                }
389
390                self.incremental_relayout(&parent_path)
391            }
392
393            DomMutationType::ChildPrepended {
394                parent_uid,
395                child_uid,
396            } => {
397                let parent_path = match self.root_blueprint.find_path_by_dom_uid(*parent_uid) {
398                    Some(p) => p,
399                    None => return false,
400                };
401
402                let child_bp = if let Some(doc) = document {
403                    if let Some(child_dom) = doc.get_element_by_uid(*child_uid) {
404                        dom_node_to_blueprint(&child_dom)
405                    } else {
406                        return false;
407                    }
408                } else {
409                    return false;
410                };
411
412                // Prepend to blueprint
413                if let Some(parent_bp) =
414                    find_blueprint_node_mut(&mut self.root_blueprint, &parent_path)
415                {
416                    if let NodeBlueprint::Element {
417                        ref mut children, ..
418                    } = parent_bp
419                    {
420                        children.insert(0, child_bp.clone());
421                    }
422                }
423
424                // Prepend to layout tree
425                let parent_style = Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
426                    .map(|n| n.style.clone());
427                let child_layout =
428                    Self::build_layout_tree_with_parent(&child_bp, parent_style.as_ref());
429                if let Some(parent_layout) =
430                    Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
431                {
432                    parent_layout.children.insert(0, child_layout);
433                }
434
435                self.incremental_relayout(&parent_path)
436            }
437
438            DomMutationType::ChildInserted {
439                parent_uid,
440                child_uid,
441                before_uid,
442            } => {
443                let parent_path = match self.root_blueprint.find_path_by_dom_uid(*parent_uid) {
444                    Some(p) => p,
445                    None => return false,
446                };
447
448                let child_bp = if let Some(doc) = document {
449                    if let Some(child_dom) = doc.get_element_by_uid(*child_uid) {
450                        dom_node_to_blueprint(&child_dom)
451                    } else {
452                        return false;
453                    }
454                } else {
455                    return false;
456                };
457
458                // Find insertion index
459                let insert_idx = match before_uid {
460                    Some(b_uid) => {
461                        let mut idx_opt = None;
462                        if let Some(parent_bp) = self.root_blueprint.find_by_dom_uid(*parent_uid) {
463                            if let NodeBlueprint::Element { children, .. } = parent_bp {
464                                idx_opt = children.iter().position(|c| c.dom_uid() == Some(*b_uid));
465                            }
466                        }
467                        idx_opt
468                    }
469                    None => None,
470                };
471
472                // Insert into blueprint
473                if let Some(parent_bp) =
474                    find_blueprint_node_mut(&mut self.root_blueprint, &parent_path)
475                {
476                    if let NodeBlueprint::Element {
477                        ref mut children, ..
478                    } = parent_bp
479                    {
480                        if let Some(idx) = insert_idx {
481                            if idx < children.len() {
482                                children.insert(idx, child_bp.clone());
483                            } else {
484                                children.push(child_bp.clone());
485                            }
486                        } else {
487                            children.push(child_bp.clone());
488                        }
489                    }
490                }
491
492                // Insert into layout tree
493                let parent_style = Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
494                    .map(|n| n.style.clone());
495                let child_layout =
496                    Self::build_layout_tree_with_parent(&child_bp, parent_style.as_ref());
497                if let Some(parent_layout) =
498                    Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
499                {
500                    if let Some(idx) = insert_idx {
501                        if idx < parent_layout.children.len() {
502                            parent_layout.children.insert(idx, child_layout);
503                        } else {
504                            parent_layout.children.push(child_layout);
505                        }
506                    } else {
507                        parent_layout.children.push(child_layout);
508                    }
509                }
510
511                self.incremental_relayout(&parent_path)
512            }
513
514            DomMutationType::ChildRemoved {
515                parent_uid,
516                child_uid,
517            } => {
518                let parent_path = match self.root_blueprint.find_path_by_dom_uid(*parent_uid) {
519                    Some(p) => p,
520                    None => return false,
521                };
522
523                // Remove from blueprint
524                let mut removed_idx = None;
525                if let Some(parent_bp) =
526                    find_blueprint_node_mut(&mut self.root_blueprint, &parent_path)
527                {
528                    if let NodeBlueprint::Element {
529                        ref mut children, ..
530                    } = parent_bp
531                    {
532                        if let Some(pos) = children
533                            .iter()
534                            .position(|c| c.dom_uid() == Some(*child_uid))
535                        {
536                            children.remove(pos);
537                            removed_idx = Some(pos);
538                        }
539                    }
540                }
541
542                // Remove from layout tree
543                if let Some(idx) = removed_idx {
544                    if let Some(parent_layout) =
545                        Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
546                    {
547                        if idx < parent_layout.children.len() {
548                            parent_layout.children.remove(idx);
549                        }
550                    }
551                }
552
553                self.incremental_relayout(&parent_path)
554            }
555
556            DomMutationType::ChildReplaced {
557                parent_uid,
558                new_child_uid,
559                old_child_uid,
560            } => {
561                let parent_path = match self.root_blueprint.find_path_by_dom_uid(*parent_uid) {
562                    Some(p) => p,
563                    None => return false,
564                };
565
566                let new_child_bp = if let Some(doc) = document {
567                    if let Some(child_dom) = doc.get_element_by_uid(*new_child_uid) {
568                        dom_node_to_blueprint(&child_dom)
569                    } else {
570                        return false;
571                    }
572                } else {
573                    return false;
574                };
575
576                let mut replaced_idx = None;
577                if let Some(parent_bp) =
578                    find_blueprint_node_mut(&mut self.root_blueprint, &parent_path)
579                {
580                    if let NodeBlueprint::Element {
581                        ref mut children, ..
582                    } = parent_bp
583                    {
584                        if let Some(pos) = children
585                            .iter()
586                            .position(|c| c.dom_uid() == Some(*old_child_uid))
587                        {
588                            children[pos] = new_child_bp.clone();
589                            replaced_idx = Some(pos);
590                        }
591                    }
592                }
593
594                if let Some(idx) = replaced_idx {
595                    let parent_style =
596                        Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
597                            .map(|n| n.style.clone());
598                    let new_child_layout =
599                        Self::build_layout_tree_with_parent(&new_child_bp, parent_style.as_ref());
600                    if let Some(parent_layout) =
601                        Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
602                    {
603                        if idx < parent_layout.children.len() {
604                            parent_layout.children[idx] = new_child_layout;
605                        }
606                    }
607                }
608
609                self.incremental_relayout(&parent_path)
610            }
611
612            DomMutationType::InnerHtmlChanged { node_uid, html: _ } => {
613                let path = match self.root_blueprint.find_path_by_dom_uid(*node_uid) {
614                    Some(p) => p,
615                    None => return false,
616                };
617
618                let new_children_bp: Vec<NodeBlueprint> = if let Some(doc) = document {
619                    if let Some(dom_node) = doc.get_element_by_uid(*node_uid) {
620                        dom_node
621                            .children()
622                            .iter()
623                            .map(dom_node_to_blueprint)
624                            .collect()
625                    } else {
626                        Vec::new()
627                    }
628                } else {
629                    Vec::new()
630                };
631
632                // Update blueprint
633                if let Some(bp) = find_blueprint_node_mut(&mut self.root_blueprint, &path) {
634                    if let NodeBlueprint::Element {
635                        ref mut children, ..
636                    } = bp
637                    {
638                        *children = new_children_bp.clone();
639                    }
640                }
641
642                // Update layout tree
643                let parent_style = Self::find_layout_node_mut(&mut self.layout_root, &path)
644                    .map(|n| n.style.clone());
645                let new_layout_children: Vec<LayoutNode> = new_children_bp
646                    .iter()
647                    .map(|c| Self::build_layout_tree_with_parent(c, parent_style.as_ref()))
648                    .collect();
649
650                if let Some(node) = Self::find_layout_node_mut(&mut self.layout_root, &path) {
651                    node.children = new_layout_children;
652                }
653
654                self.incremental_relayout(&path)
655            }
656        }
657    }
658
659    /// Performs incremental layout recomputation along a dirty tree path,
660    /// leveraging layout boundaries or ancestor cache invalidation.
661    pub fn incremental_relayout(&mut self, dirty_path: &[usize]) -> bool {
662        // Invalidate ancestor layout caches so compute_layout traverses down the dirty branch
663        self.layout_root.invalidate_ancestors(dirty_path);
664
665        // Attempt isolated subgrid/boundary layout first if an ancestor layout boundary exists
666        let handled_locally = self
667            .layout_root
668            .compute_subgrid_or_boundary_layout(dirty_path);
669        if !handled_locally {
670            // Full incremental traversal: untouched sibling branches hit layout_cache.is_valid and return in O(1)
671            self.layout_root
672                .compute_layout(self.viewport_width, self.viewport_height);
673        }
674
675        Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
676        self.spatial_index
677            .rebuild(&self.root_blueprint, &self.layout_root);
678        self.tick_frame();
679        true
680    }
681}