nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
//! Typed Tier-1 patch model ([`TypedViewPatch`]) and `AnchorKey`-addressed binary
//! [`HotPatchMsg::TemplatePatch`] lowering for `view!` files.

use std::fmt;

use nativeview_engine::HotPatchMsg;
use nativeview_store::{FlatResource, RowPatch};
use nativeview_view_syntax::AnchorKey;

use crate::hot_diff::attrs::AttrSpec;
use crate::hot_diff::eval::TypedAttrValue;
use crate::hot_diff::patch::encode_attr_into_row_patch;

/// Deterministic `AnchorKey` target for one direct-root patchable `view!` node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ViewAnchorTarget {
    /// Collision-free `XXH64` anchor key (`compute_anchor_key(rel_file, ordinal, static_ast_path)`).
    pub anchor: AnchorKey,
    /// File-order 0-based ordinal of the enclosing `view!` invocation.
    pub ordinal: u32,
    /// Static child-index path within the `view!` invocation.
    pub static_ast_path: Vec<u16>,
    /// Element tag name (e.g. `"Column"`, `"Text"`) or `"<text>"` for bare string literals.
    pub tag: String,
    /// Optional static `test_id` literal attached to this element.
    pub test_id: Option<String>,
}

/// One changed static style/layout/visual/typography attribute on a direct-root `view!` element.
#[derive(Debug, Clone, PartialEq)]
pub struct ViewAttrChange {
    pub target: ViewAnchorTarget,
    pub attr: &'static AttrSpec,
    pub old: TypedAttrValue,
    pub new: TypedAttrValue,
}

/// One changed static string literal on a direct-root `view!` `Text(...)` or bare string child.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ViewTextChange {
    pub target: ViewAnchorTarget,
    pub old: String,
    pub new: String,
}

/// Every typed change of one Tier-1 `view!` save, in source order.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TypedViewPatch {
    pub attr_changes: Vec<ViewAttrChange>,
    pub text_changes: Vec<ViewTextChange>,
}

impl TypedViewPatch {
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.attr_changes.is_empty() && self.text_changes.is_empty()
    }

    /// Formats concise human-readable change descriptions for `[tier-1]` watch logs.
    pub fn log_lines(&self) -> Vec<String> {
        let mut lines = Vec::with_capacity(self.attr_changes.len() + self.text_changes.len());
        for change in &self.attr_changes {
            lines.push(change.to_string());
        }
        for change in &self.text_changes {
            lines.push(change.to_string());
        }
        lines
    }

    /// Lowers all changes to `AnchorKey`-addressed binary [`HotPatchMsg::TemplatePatch`] messages
    /// (`template_key = anchor.0`, `node_path = vec![]`), merging style + text edits targeting the
    /// same [`AnchorKey`] into one atomic message in first-appearance order.
    pub fn to_template_patches(&self, generation: u64) -> Result<Vec<HotPatchMsg>, String> {
        struct AnchorGroup<'a> {
            target: &'a ViewAnchorTarget,
            row_patch: RowPatch,
            has_row_patch: bool,
            text_updates: Vec<(usize, String)>,
            text_replacements: Vec<(String, String)>,
        }

        let mut groups: Vec<AnchorGroup<'_>> = Vec::new();

        for change in &self.text_changes {
            let group = match groups
                .iter_mut()
                .find(|g| g.target.anchor == change.target.anchor)
            {
                Some(g) => g,
                None => {
                    let idx = groups.len();
                    groups.push(AnchorGroup {
                        target: &change.target,
                        row_patch: RowPatch::new(),
                        has_row_patch: false,
                        text_updates: Vec::new(),
                        text_replacements: Vec::new(),
                    });
                    &mut groups[idx]
                }
            };
            if change.old.is_empty() {
                group.text_updates.push((0, change.new.clone()));
            } else {
                group
                    .text_replacements
                    .push((change.old.clone(), change.new.clone()));
            }
        }

        for change in &self.attr_changes {
            let group = match groups
                .iter_mut()
                .find(|g| g.target.anchor == change.target.anchor)
            {
                Some(g) => g,
                None => {
                    let idx = groups.len();
                    groups.push(AnchorGroup {
                        target: &change.target,
                        row_patch: RowPatch::new(),
                        has_row_patch: false,
                        text_updates: Vec::new(),
                        text_replacements: Vec::new(),
                    });
                    &mut groups[idx]
                }
            };
            encode_attr_into_row_patch(&mut group.row_patch, change.attr, &change.new)?;
            group.has_row_patch = true;
        }

        let mut messages = Vec::with_capacity(groups.len());
        for group in groups {
            if !group.text_updates.is_empty() && !group.text_replacements.is_empty() {
                return Err(
                    "conflicting empty and non-empty text updates on the same AnchorKey".to_owned(),
                );
            }
            let mut row_patch_words = Vec::new();
            if group.has_row_patch && !group.row_patch.write_words(&mut row_patch_words) {
                return Err("RowPatch exceeded flat word limit".to_owned());
            }
            let template_key = group.target.anchor.0;
            messages.push(HotPatchMsg::TemplatePatch {
                generation,
                template_key,
                node_path: Vec::new(),
                // `view!` patches address nodes strictly by `AnchorKey` when keyed so an unmounted
                // anchor never falls back to corrupting an unrelated live node sharing `test_id`.
                target_test_id: if template_key != 0 {
                    None
                } else {
                    group.target.test_id.clone()
                },
                row_patch_words,
                text_updates: group.text_updates,
                text_replacements: group.text_replacements,
            });
        }
        Ok(messages)
    }
}

impl fmt::Display for ViewAnchorTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "view#{} {} path {:?} {}",
            self.ordinal, self.tag, self.static_ast_path, self.anchor
        )?;
        if let Some(id) = &self.test_id {
            write!(f, " test_id {id:?}")?;
        }
        Ok(())
    }
}

impl fmt::Display for ViewAttrChange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: {} -> {} ({})",
            self.attr.name, self.old, self.new, self.target
        )
    }
}

impl fmt::Display for ViewTextChange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "text: {:?} -> {:?} ({})",
            self.old, self.new, self.target
        )
    }
}