Skip to main content

nativeview_cli/view_diff/
patch.rs

1//! Typed Tier-1 patch model ([`TypedViewPatch`]) and `AnchorKey`-addressed binary
2//! [`HotPatchMsg::TemplatePatch`] lowering for `view!` files.
3
4use std::fmt;
5
6use nativeview_engine::HotPatchMsg;
7use nativeview_store::{FlatResource, RowPatch};
8use nativeview_view_syntax::AnchorKey;
9
10use crate::hot_diff::attrs::AttrSpec;
11use crate::hot_diff::eval::TypedAttrValue;
12use crate::hot_diff::patch::encode_attr_into_row_patch;
13
14/// Deterministic `AnchorKey` target for one direct-root patchable `view!` node.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct ViewAnchorTarget {
17    /// Collision-free `XXH64` anchor key (`compute_anchor_key(rel_file, ordinal, static_ast_path)`).
18    pub anchor: AnchorKey,
19    /// File-order 0-based ordinal of the enclosing `view!` invocation.
20    pub ordinal: u32,
21    /// Static child-index path within the `view!` invocation.
22    pub static_ast_path: Vec<u16>,
23    /// Element tag name (e.g. `"Column"`, `"Text"`) or `"<text>"` for bare string literals.
24    pub tag: String,
25    /// Optional static `test_id` literal attached to this element.
26    pub test_id: Option<String>,
27}
28
29/// One changed static style/layout/visual/typography attribute on a direct-root `view!` element.
30#[derive(Debug, Clone, PartialEq)]
31pub struct ViewAttrChange {
32    pub target: ViewAnchorTarget,
33    pub attr: &'static AttrSpec,
34    pub old: TypedAttrValue,
35    pub new: TypedAttrValue,
36}
37
38/// One changed static string literal on a direct-root `view!` `Text(...)` or bare string child.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct ViewTextChange {
41    pub target: ViewAnchorTarget,
42    pub old: String,
43    pub new: String,
44}
45
46/// Every typed change of one Tier-1 `view!` save, in source order.
47#[derive(Debug, Clone, Default, PartialEq)]
48pub struct TypedViewPatch {
49    pub attr_changes: Vec<ViewAttrChange>,
50    pub text_changes: Vec<ViewTextChange>,
51}
52
53impl TypedViewPatch {
54    #[inline]
55    pub fn is_empty(&self) -> bool {
56        self.attr_changes.is_empty() && self.text_changes.is_empty()
57    }
58
59    /// Formats concise human-readable change descriptions for `[tier-1]` watch logs.
60    pub fn log_lines(&self) -> Vec<String> {
61        let mut lines = Vec::with_capacity(self.attr_changes.len() + self.text_changes.len());
62        for change in &self.attr_changes {
63            lines.push(change.to_string());
64        }
65        for change in &self.text_changes {
66            lines.push(change.to_string());
67        }
68        lines
69    }
70
71    /// Lowers all changes to `AnchorKey`-addressed binary [`HotPatchMsg::TemplatePatch`] messages
72    /// (`template_key = anchor.0`, `node_path = vec![]`), merging style + text edits targeting the
73    /// same [`AnchorKey`] into one atomic message in first-appearance order.
74    pub fn to_template_patches(&self, generation: u64) -> Result<Vec<HotPatchMsg>, String> {
75        struct AnchorGroup<'a> {
76            target: &'a ViewAnchorTarget,
77            row_patch: RowPatch,
78            has_row_patch: bool,
79            text_updates: Vec<(usize, String)>,
80            text_replacements: Vec<(String, String)>,
81        }
82
83        let mut groups: Vec<AnchorGroup<'_>> = Vec::new();
84
85        for change in &self.text_changes {
86            let group = match groups
87                .iter_mut()
88                .find(|g| g.target.anchor == change.target.anchor)
89            {
90                Some(g) => g,
91                None => {
92                    let idx = groups.len();
93                    groups.push(AnchorGroup {
94                        target: &change.target,
95                        row_patch: RowPatch::new(),
96                        has_row_patch: false,
97                        text_updates: Vec::new(),
98                        text_replacements: Vec::new(),
99                    });
100                    &mut groups[idx]
101                }
102            };
103            if change.old.is_empty() {
104                group.text_updates.push((0, change.new.clone()));
105            } else {
106                group
107                    .text_replacements
108                    .push((change.old.clone(), change.new.clone()));
109            }
110        }
111
112        for change in &self.attr_changes {
113            let group = match groups
114                .iter_mut()
115                .find(|g| g.target.anchor == change.target.anchor)
116            {
117                Some(g) => g,
118                None => {
119                    let idx = groups.len();
120                    groups.push(AnchorGroup {
121                        target: &change.target,
122                        row_patch: RowPatch::new(),
123                        has_row_patch: false,
124                        text_updates: Vec::new(),
125                        text_replacements: Vec::new(),
126                    });
127                    &mut groups[idx]
128                }
129            };
130            encode_attr_into_row_patch(&mut group.row_patch, change.attr, &change.new)?;
131            group.has_row_patch = true;
132        }
133
134        let mut messages = Vec::with_capacity(groups.len());
135        for group in groups {
136            if !group.text_updates.is_empty() && !group.text_replacements.is_empty() {
137                return Err(
138                    "conflicting empty and non-empty text updates on the same AnchorKey".to_owned(),
139                );
140            }
141            let mut row_patch_words = Vec::new();
142            if group.has_row_patch && !group.row_patch.write_words(&mut row_patch_words) {
143                return Err("RowPatch exceeded flat word limit".to_owned());
144            }
145            let template_key = group.target.anchor.0;
146            messages.push(HotPatchMsg::TemplatePatch {
147                generation,
148                template_key,
149                node_path: Vec::new(),
150                // `view!` patches address nodes strictly by `AnchorKey` when keyed so an unmounted
151                // anchor never falls back to corrupting an unrelated live node sharing `test_id`.
152                target_test_id: if template_key != 0 {
153                    None
154                } else {
155                    group.target.test_id.clone()
156                },
157                row_patch_words,
158                text_updates: group.text_updates,
159                text_replacements: group.text_replacements,
160            });
161        }
162        Ok(messages)
163    }
164}
165
166impl fmt::Display for ViewAnchorTarget {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        write!(
169            f,
170            "view#{} {} path {:?} {}",
171            self.ordinal, self.tag, self.static_ast_path, self.anchor
172        )?;
173        if let Some(id) = &self.test_id {
174            write!(f, " test_id {id:?}")?;
175        }
176        Ok(())
177    }
178}
179
180impl fmt::Display for ViewAttrChange {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        write!(
183            f,
184            "{}: {} -> {} ({})",
185            self.attr.name, self.old, self.new, self.target
186        )
187    }
188}
189
190impl fmt::Display for ViewTextChange {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        write!(
193            f,
194            "text: {:?} -> {:?} ({})",
195            self.old, self.new, self.target
196        )
197    }
198}