mf_model/
node.rs

1use rpds::VectorSync;
2use super::attrs::Attrs;
3use super::mark::Mark;
4use super::types::NodeId;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7/// 基础节点定义,任何数据都可以认为是节点
8///
9/// # 属性
10///
11/// * `id` - 节点唯一标识符
12/// * `type` - 节点类型
13/// * `attrs` - 节点属性,一般用于元数据的存储
14/// * `content` - 子节点列表
15/// * `marks` - 节点标记列表
16///
17/// # 示例
18///
19/// ```
20/// use mf_rs::model::node::Node;
21/// use mf_rs::model::attrs::Attrs;
22///
23/// let node = Node::new(
24///     "node1",
25///     "paragraph".to_string(),
26///     Attrs::default(),
27///     vec![],
28///     vec![],
29/// );
30/// ```
31
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct Node {
34    #[serde(rename = "i")]
35    pub id: NodeId,
36    #[serde(rename = "t")]
37    pub r#type: String,
38    #[serde(rename = "a")]
39    pub attrs: Attrs,
40    #[serde(rename = "c")]
41    pub content: VectorSync<NodeId>, // 使用im::Vector替代Arc<Vec>
42    #[serde(rename = "m")]
43    pub marks: VectorSync<Mark>,
44}
45
46impl Node {
47    /// 创建一个新的节点实例
48    ///
49    /// # 参数
50    ///
51    /// * `id` - 节点ID,字符串引用
52    /// * `type` - 节点类型
53    /// * `attrs` - 节点属性
54    /// * `content` - 子节点ID列表
55    /// * `marks` - 节点标记列表
56    ///
57    /// # 返回值
58    ///
59    /// 返回一个新的 `Node` 实例
60    pub fn new(
61        id: &str, // 接受字符串引用
62        r#type: String,
63        attrs: Attrs,
64        content: Vec<NodeId>,
65        marks: Vec<Mark>,
66    ) -> Self {
67        let mut vector = rpds::VectorSync::new_sync();
68        for c in content {
69            vector = vector.push_back(c);
70        }
71        let mut mks = rpds::VectorSync::new_sync();
72        for m in marks {
73            mks = mks.push_back(m);
74        }
75        Node {
76            id: id.into(), // 转换为Arc<str>
77            r#type,
78            attrs,
79            content: vector,
80            marks: mks,
81        }
82    }
83    /// 获取子节点数量
84    ///
85    /// # 返回值
86    ///
87    /// 返回节点包含的子节点数量
88    pub fn child_count(&self) -> usize {
89        self.content.len()
90    }
91    /// 更新节点属性
92    ///
93    /// # 参数
94    ///
95    /// * `new_values` - 新的属性值
96    ///
97    /// # 返回值
98    pub fn update_attr(
99        &self,
100        new_values: rpds::HashTrieMapSync<String, Value>,
101    ) -> Self {
102        let mut new_node = self.clone();
103        let new_attrs = self.attrs.update(new_values);
104        new_node.attrs = new_attrs;
105        new_node
106    }
107    /// 在指定位置插入子节点
108    ///
109    /// # 参数
110    ///
111    /// * `index` - 插入位置
112    /// * `node_id` - 子节点ID
113    ///
114    pub fn insert_content_at_index(
115        &self,
116        index: usize,
117        node_id: &str,
118    ) -> Self {
119        let mut new_node = self.clone(); // 通过迭代器重建 Vector,在指定位置插入新元素
120        new_node.content = self
121            .content
122            .iter()
123            .take(index)
124            .cloned()
125            .chain(std::iter::once(node_id.into()))
126            .chain(self.content.iter().skip(index).cloned())
127            .collect();
128
129        new_node
130    }
131    /// 在末尾插入多个子节点
132    ///
133    /// # 参数
134    ///
135    /// * `node_ids` - 子节点ID列表
136    ///
137    pub fn insert_contents(
138        &self,
139        node_ids: &Vec<NodeId>,
140    ) -> Self {
141        let mut new_node = self.clone();
142        for node_id in node_ids {
143            new_node.content = new_node.content.push_back(node_id.clone());
144        }
145        new_node
146    }
147    pub fn contains(
148        &self,
149        id: &NodeId,
150    ) -> bool {
151        self.content.iter().any(|x| x.eq(id))
152    }
153    pub fn remove_content(
154        &mut self,
155        id: &NodeId,
156    ) -> Self {
157        let mut new_node = self.clone();
158        let mut new_vector = VectorSync::new_sync();
159        for c in self.content.iter() {
160            if !c.eq(id) {
161                new_vector.push_back_mut(c.clone());
162            }
163        }
164        new_node.content = new_vector;
165        new_node
166    }
167
168    pub fn swap(
169        &self,
170        i: usize,
171        j: usize,
172    ) -> Option<Node> {
173        if i >= self.content.len() || j >= self.content.len() {
174            return None;
175        }
176
177        let value_i = self.content.get(i)?;
178        let value_j = self.content.get(j)?;
179
180        let mut new_vector = self.content.clone();
181        new_vector.set_mut(i, value_j.clone());
182        new_vector.set_mut(j, value_i.clone());
183        let mut new_node = self.clone();
184        new_node.content = new_vector;
185        Some(new_node)
186    }
187    /// 在末尾插入一个子节点
188    ///
189    /// # 参数
190    ///
191    /// * `node_id` - 子节点ID
192    ///
193    pub fn insert_content(
194        &self,
195        node_id: &str,
196    ) -> Self {
197        let mut new_node = self.clone();
198        new_node.content = new_node.content.push_back(node_id.into());
199        new_node
200    }
201
202    /// 移除指定名称的标记
203    ///
204    /// # 参数
205    ///
206    /// * `mark_name` - 标记名称
207    ///
208    pub fn remove_mark_by_name(
209        &self,
210        mark_name: &str,
211    ) -> Self {
212        let mut new_node = self.clone();
213        new_node.marks = new_node
214            .marks
215            .iter()
216            .filter(|&m| m.r#type != mark_name)
217            .cloned()
218            .collect();
219        new_node
220    }
221    /// 移除指定类型的标记
222    ///
223    /// # 参数
224    ///
225    /// * `mark_types` - 标记类型列表
226    ///
227    pub fn remove_mark(
228        &self,
229        mark_types: &[String],
230    ) -> Self {
231        let mut new_node = self.clone();
232        new_node.marks = new_node
233            .marks
234            .iter()
235            .filter(|&m| !mark_types.contains(&m.r#type))
236            .cloned()
237            .collect();
238        new_node
239    }
240    /// 添加多个标记 如果存在相同类型的mark,则覆盖
241    ///
242    /// # 参数
243    ///
244    /// * `marks` - 标记列表
245    ///
246    pub fn add_marks(
247        &self,
248        marks: &[Mark],
249    ) -> Self {
250        let mark_types =
251            marks.iter().map(|m| m.r#type.clone()).collect::<Vec<String>>();
252        let mut new_node = self.clone();
253        //如果存在相同类型的mark,则覆盖
254        new_node.marks = new_node
255            .marks
256            .iter()
257            .filter(|m| !mark_types.contains(&m.r#type))
258            .cloned()
259            .collect();
260        new_node.marks.extend(marks.iter().cloned());
261        new_node
262    }
263}