moduforge-model 0.7.0

不可变数据结构与事务系统基础
Documentation
use rpds::VectorSync;
use super::attrs::Attrs;
use super::mark::Mark;
use super::types::NodeId;
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// 基础节点定义,任何数据都可以认为是节点
///
/// # 属性
///
/// * `id` - 节点唯一标识符
/// * `type` - 节点类型
/// * `attrs` - 节点属性,一般用于元数据的存储
/// * `content` - 子节点列表
/// * `marks` - 节点标记列表
///
/// # 示例
///
/// ```
/// use mf_rs::model::node::Node;
/// use mf_rs::model::attrs::Attrs;
///
/// let node = Node::new(
///     "node1",
///     "paragraph".to_string(),
///     Attrs::default(),
///     vec![],
///     vec![],
/// );
/// ```

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
    #[serde(rename = "i")]
    pub id: NodeId,
    #[serde(rename = "t")]
    pub r#type: String,
    #[serde(rename = "a")]
    pub attrs: Attrs,
    #[serde(rename = "c")]
    pub content: VectorSync<NodeId>, // 使用im::Vector替代Arc<Vec>
    #[serde(rename = "m")]
    pub marks: VectorSync<Mark>,
}

impl Node {
    /// 创建一个新的节点实例
    ///
    /// # 参数
    ///
    /// * `id` - 节点ID,字符串引用
    /// * `type` - 节点类型
    /// * `attrs` - 节点属性
    /// * `content` - 子节点ID列表
    /// * `marks` - 节点标记列表
    ///
    /// # 返回值
    ///
    /// 返回一个新的 `Node` 实例
    pub fn new(
        id: &str, // 接受字符串引用
        r#type: String,
        attrs: Attrs,
        content: Vec<NodeId>,
        marks: Vec<Mark>,
    ) -> Self {
        let mut vector = rpds::VectorSync::new_sync();
        for c in content {
            vector = vector.push_back(c);
        }
        let mut mks = rpds::VectorSync::new_sync();
        for m in marks {
            mks = mks.push_back(m);
        }
        Node {
            id: id.into(), // 转换为Arc<str>
            r#type,
            attrs,
            content: vector,
            marks: mks,
        }
    }
    /// 获取子节点数量
    ///
    /// # 返回值
    ///
    /// 返回节点包含的子节点数量
    pub fn child_count(&self) -> usize {
        self.content.len()
    }
    /// 更新节点属性
    ///
    /// # 参数
    ///
    /// * `new_values` - 新的属性值
    ///
    /// # 返回值
    pub fn update_attr(
        &self,
        new_values: rpds::HashTrieMapSync<String, Value>,
    ) -> Self {
        let mut new_node = self.clone();
        let new_attrs = self.attrs.update(new_values);
        new_node.attrs = new_attrs;
        new_node
    }
    /// 在指定位置插入子节点
    ///
    /// # 参数
    ///
    /// * `index` - 插入位置
    /// * `node_id` - 子节点ID
    ///
    pub fn insert_content_at_index(
        &self,
        index: usize,
        node_id: &str,
    ) -> Self {
        let mut new_node = self.clone(); // 通过迭代器重建 Vector,在指定位置插入新元素
        new_node.content = self
            .content
            .iter()
            .take(index)
            .cloned()
            .chain(std::iter::once(node_id.into()))
            .chain(self.content.iter().skip(index).cloned())
            .collect();

        new_node
    }
    /// 在末尾插入多个子节点
    ///
    /// # 参数
    ///
    /// * `node_ids` - 子节点ID列表
    ///
    pub fn insert_contents(
        &self,
        node_ids: &Vec<NodeId>,
    ) -> Self {
        let mut new_node = self.clone();
        for node_id in node_ids {
            new_node.content = new_node.content.push_back(node_id.clone());
        }
        new_node
    }
    pub fn contains(
        &self,
        id: &NodeId,
    ) -> bool {
        self.content.iter().any(|x| x.eq(id))
    }
    pub fn remove_content(
        &mut self,
        id: &NodeId,
    ) -> Self {
        let mut new_node = self.clone();
        let mut new_vector = VectorSync::new_sync();
        for c in self.content.iter() {
            if !c.eq(id) {
                new_vector.push_back_mut(c.clone());
            }
        }
        new_node.content = new_vector;
        new_node
    }

    pub fn swap(
        &self,
        i: usize,
        j: usize,
    ) -> Option<Node> {
        if i >= self.content.len() || j >= self.content.len() {
            return None;
        }

        let value_i = self.content.get(i)?;
        let value_j = self.content.get(j)?;

        let mut new_vector = self.content.clone();
        new_vector.set_mut(i, value_j.clone());
        new_vector.set_mut(j, value_i.clone());
        let mut new_node = self.clone();
        new_node.content = new_vector;
        Some(new_node)
    }
    /// 在末尾插入一个子节点
    ///
    /// # 参数
    ///
    /// * `node_id` - 子节点ID
    ///
    pub fn insert_content(
        &self,
        node_id: &str,
    ) -> Self {
        let mut new_node = self.clone();
        new_node.content = new_node.content.push_back(node_id.into());
        new_node
    }

    /// 移除指定名称的标记
    ///
    /// # 参数
    ///
    /// * `mark_name` - 标记名称
    ///
    pub fn remove_mark_by_name(
        &self,
        mark_name: &str,
    ) -> Self {
        let mut new_node = self.clone();
        new_node.marks = new_node
            .marks
            .iter()
            .filter(|&m| m.r#type != mark_name)
            .cloned()
            .collect();
        new_node
    }
    /// 移除指定类型的标记
    ///
    /// # 参数
    ///
    /// * `mark_types` - 标记类型列表
    ///
    pub fn remove_mark(
        &self,
        mark_types: &[String],
    ) -> Self {
        let mut new_node = self.clone();
        new_node.marks = new_node
            .marks
            .iter()
            .filter(|&m| !mark_types.contains(&m.r#type))
            .cloned()
            .collect();
        new_node
    }
    /// 添加多个标记 如果存在相同类型的mark,则覆盖
    ///
    /// # 参数
    ///
    /// * `marks` - 标记列表
    ///
    pub fn add_marks(
        &self,
        marks: &[Mark],
    ) -> Self {
        let mark_types =
            marks.iter().map(|m| m.r#type.clone()).collect::<Vec<String>>();
        let mut new_node = self.clone();
        //如果存在相同类型的mark,则覆盖
        new_node.marks = new_node
            .marks
            .iter()
            .filter(|m| !mark_types.contains(&m.r#type))
            .cloned()
            .collect();
        new_node.marks.extend(marks.iter().cloned());
        new_node
    }
}