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