ziyy_core/resolver/document/
node.rs

1use std::{
2    cell::{Ref, RefCell},
3    rc::{Rc, Weak},
4};
5
6use super::Document;
7use crate::parser::chunk::Chunk;
8
9#[derive(Debug, Clone)]
10struct Kin {
11    parent: Option<u32>,
12    prev_sibling: Option<u32>,
13    next_sibling: Option<u32>,
14    children: Option<(u32, u32)>,
15}
16
17pub type RNode<'a> = Rc<Node<'a>>;
18
19#[derive(Debug, Clone)]
20
21pub struct Node<'a> {
22    pub(super) id: u32,
23    kin: RefCell<Kin>,
24    doc: Weak<Document<'a>>,
25    chunk: RefCell<Chunk<'a>>,
26}
27
28impl<'a> Node<'a> {
29    pub fn new(id: u32, chunk: Chunk<'a>, doc: Weak<Document<'a>>) -> Self {
30        Self {
31            id,
32            kin: RefCell::new(Kin {
33                parent: None,
34                prev_sibling: None,
35                next_sibling: None,
36                children: None,
37            }),
38            doc,
39            chunk: RefCell::new(chunk),
40        }
41    }
42
43    pub fn id(&self) -> u32 {
44        self.id
45    }
46
47    pub fn doc(&self) -> Rc<Document<'a>> {
48        self.doc.upgrade().unwrap()
49    }
50
51    /// Returns the chunk of this node.
52    pub fn chunk<'b>(self: &'b RNode<'a>) -> &'b RefCell<Chunk<'a>> {
53        &self.chunk
54    }
55
56    fn axis<F>(&self, f: F) -> Option<RNode<'a>>
57    where
58        F: FnOnce(Ref<Kin>) -> Option<u32>,
59    {
60        f(self.kin.borrow()).map(|id| self.doc().get(id))
61    }
62
63    /// Returns the parent of this node.
64    pub fn parent(&self) -> Option<Rc<Self>> {
65        self.axis(|node| node.parent)
66    }
67
68    /// Returns the previous sibling of this node.
69    pub fn prev_sibling(&self) -> Option<Rc<Self>> {
70        self.axis(|node| node.prev_sibling)
71    }
72
73    /// Returns the next sibling of this node.
74    pub fn next_sibling(&self) -> Option<Rc<Self>> {
75        self.axis(|node| node.next_sibling)
76    }
77
78    /// Returns the first child of this node.
79    pub fn first_child(&self) -> Option<Rc<Self>> {
80        self.axis(|node| node.children.map(|(id, _)| id))
81    }
82
83    /// Returns the last child of this node.
84    pub fn last_child(&self) -> Option<Rc<Self>> {
85        self.axis(|node| node.children.map(|(_, id)| id))
86    }
87
88    /// Returns true if this node has children.
89    pub fn has_children(&self) -> bool {
90        self.kin.borrow().children.is_some()
91    }
92
93    /// Appends a new child to this node.
94    pub fn append(&self, value: Chunk<'a>) -> RNode<'a> {
95        let id = self.doc().orphan(value).id;
96        self.append_id(id)
97    }
98
99    /// Prepends a new child to this node.
100    #[allow(dead_code)]
101    pub fn prepend(&self, value: Chunk<'a>) -> RNode<'a> {
102        let id = self.doc().orphan(value).id;
103        self.prepend_id(id)
104    }
105
106    /// Inserts a new sibling before this node.
107    ///
108    /// # Panics
109    ///
110    /// Panics if this node is an orphan.
111    pub fn insert_before(&self, value: Chunk<'a>) -> RNode<'a> {
112        let id = self.doc().orphan(value).id;
113        self.insert_id_before(id)
114    }
115
116    /// Inserts a new sibling after this node.
117    ///
118    /// # Panics
119    ///
120    /// Panics if this node is an orphan.
121    pub fn insert_after(&self, value: Chunk<'a>) -> RNode<'a> {
122        let id = self.doc().orphan(value).id;
123        self.insert_id_after(id)
124    }
125
126    /// Detaches this node from its parent.
127    pub fn detach(&self, recycle: bool) {
128        let mut kin = self.kin.borrow_mut();
129        let parent_id = match kin.parent {
130            Some(id) => id,
131            None => return,
132        };
133        let prev_sibling_id = kin.prev_sibling;
134        let next_sibling_id = kin.next_sibling;
135
136        {
137            kin.parent = None;
138            kin.prev_sibling = None;
139            kin.next_sibling = None;
140        }
141
142        if let Some(id) = prev_sibling_id {
143            self.doc().node(id).kin.borrow_mut().next_sibling = next_sibling_id;
144        }
145        if let Some(id) = next_sibling_id {
146            self.doc().node(id).kin.borrow_mut().prev_sibling = prev_sibling_id;
147        }
148
149        let doc = self.doc();
150        let parent = doc.node(parent_id);
151        let mut parent_kin = parent.kin.borrow_mut();
152        let (first_child_id, last_child_id) = parent_kin.children.unwrap();
153        if first_child_id == last_child_id {
154            parent_kin.children = None;
155        } else if first_child_id == self.id {
156            parent_kin.children = Some((next_sibling_id.unwrap(), last_child_id));
157        } else if last_child_id == self.id {
158            parent_kin.children = Some((first_child_id, prev_sibling_id.unwrap()));
159        }
160
161        if recycle {
162            self.doc().recycled.borrow_mut().push(self.id);
163        }
164    }
165
166    /// Appends a child to this node.
167    pub fn append_id(&self, new_child_id: u32) -> RNode<'a> {
168        assert_ne!(
169            self.id, new_child_id,
170            "Cannot append node as a child to itself"
171        );
172
173        let mut kin = self.kin.borrow_mut();
174
175        let last_child_id = kin.children.map(|(_, id)| id);
176
177        if last_child_id != Some(new_child_id) {
178            {
179                let new_child = self.doc().get(new_child_id);
180                new_child.detach(true);
181                let mut new_child_kin = new_child.kin.borrow_mut();
182                new_child_kin.parent = Some(self.id);
183                new_child_kin.prev_sibling = last_child_id;
184            }
185
186            if let Some(id) = last_child_id {
187                self.doc().node(id).kin.borrow_mut().next_sibling = Some(new_child_id);
188            }
189
190            kin.children = match kin.children {
191                Some((first_child_id, _)) => Some((first_child_id, new_child_id)),
192                None => Some((new_child_id, new_child_id)),
193            };
194        }
195
196        self.doc().get(new_child_id)
197    }
198
199    /// Prepends a child to this node.
200    #[allow(dead_code)]
201    pub fn prepend_id(&self, new_child_id: u32) -> RNode<'a> {
202        assert_ne!(
203            self.id, new_child_id,
204            "Cannot prepend node as a child to itself"
205        );
206
207        let mut kin = self.kin.borrow_mut();
208
209        let first_child_id = kin.children.map(|(id, _)| id);
210
211        if first_child_id != Some(new_child_id) {
212            let new_child = self.doc().get(new_child_id);
213            new_child.detach(true);
214            let mut new_child_kin = new_child.kin.borrow_mut();
215            new_child_kin.parent = Some(self.id);
216            new_child_kin.next_sibling = first_child_id;
217
218            if let Some(id) = first_child_id {
219                self.doc().node(id).kin.borrow_mut().prev_sibling = Some(new_child_id);
220            }
221
222            kin.children = match kin.children {
223                Some((_, last_child_id)) => Some((new_child_id, last_child_id)),
224                None => Some((new_child_id, new_child_id)),
225            };
226        }
227
228        self.doc().get(new_child_id)
229    }
230
231    /// Inserts a sibling before this node.
232    ///
233    /// # Panics
234    ///
235    /// - Panics if `new_sibling_id` is not valid.
236    /// - Panics if this node is an orphan.
237    pub fn insert_id_before(&self, new_sibling_id: u32) -> RNode<'a> {
238        assert_ne!(
239            self.id, new_sibling_id,
240            "Cannot insert node as a sibling of itself"
241        );
242
243        let mut kin = self.kin.borrow_mut();
244
245        let parent_id = kin.parent.unwrap();
246        let prev_sibling_id = kin.prev_sibling;
247
248        {
249            let new_sibling = self.doc().get(new_sibling_id);
250            new_sibling.detach(true);
251            let mut new_sibling_kin = new_sibling.kin.borrow_mut();
252            new_sibling_kin.parent = Some(parent_id);
253            new_sibling_kin.prev_sibling = prev_sibling_id;
254            new_sibling_kin.next_sibling = Some(self.id);
255        }
256
257        if let Some(id) = prev_sibling_id {
258            self.doc().node(id).kin.borrow_mut().next_sibling = Some(new_sibling_id);
259        }
260
261        kin.prev_sibling = Some(new_sibling_id);
262
263        {
264            let doc = self.doc();
265            let parent = doc.node(parent_id);
266            let mut parent_kin = parent.kin.borrow_mut();
267            let (first_child_id, last_child_id) = parent_kin.children.unwrap();
268            if first_child_id == self.id {
269                parent_kin.children = Some((new_sibling_id, last_child_id));
270            }
271        }
272
273        self.doc().get(new_sibling_id)
274    }
275
276    /// Inserts a sibling after this node.
277    ///
278    /// # Panics
279    ///
280    /// - Panics if `new_sibling_id` is not valid.
281    /// - Panics if this node is an orphan.
282    pub fn insert_id_after(&self, new_sibling_id: u32) -> RNode<'a> {
283        assert_ne!(
284            self.id, new_sibling_id,
285            "Cannot insert node as a sibling of itself"
286        );
287
288        let mut kin = self.kin.borrow_mut();
289
290        let parent_id = kin.parent.unwrap();
291        let next_sibling_id = kin.next_sibling;
292
293        {
294            let new_sibling = self.doc().get(new_sibling_id);
295            new_sibling.detach(true);
296            let mut new_sibling_kin = new_sibling.kin.borrow_mut();
297            new_sibling_kin.parent = Some(parent_id);
298            new_sibling_kin.prev_sibling = Some(self.id);
299            new_sibling_kin.next_sibling = next_sibling_id;
300        }
301
302        if let Some(id) = next_sibling_id {
303            self.doc().node(id).kin.borrow_mut().prev_sibling = Some(new_sibling_id);
304        }
305
306        kin.next_sibling = Some(new_sibling_id);
307
308        {
309            let doc = self.doc();
310            let parent = doc.node(parent_id);
311            let mut parent_kin = parent.kin.borrow_mut();
312            let (first_child_id, last_child_id) = parent_kin.children.unwrap();
313            if last_child_id == self.id {
314                parent_kin.children = Some((first_child_id, new_sibling_id));
315            }
316        }
317
318        self.doc().get(new_sibling_id)
319    }
320
321    /// Returns the string representation of this node.
322    pub fn to_string(&self, buf: &mut String) {
323        if self.has_children() {
324            let tag_chunk = self.chunk.borrow();
325            let tag = tag_chunk.data.tag().unwrap();
326            buf.push_str(tag.to_string().as_str());
327            for child in self.children() {
328                child.to_string(buf);
329            }
330            //buf.push_str((!tag.clone()).to_string().as_str());
331        } else {
332            buf.push_str(self.chunk.borrow().data.to_string().as_str());
333        }
334    }
335
336    pub fn strip_styles(&self) {
337        if self.chunk.borrow().is_tag() {
338            let mut tag_chunk = self.chunk.borrow_mut();
339            let tag = tag_chunk.data.tag_mut().unwrap();
340            tag.reset_styles();
341            for child in self.children() {
342                child.strip_styles();
343            }
344        }
345    }
346
347    pub fn word_len(&self, len: &mut usize) {
348        for child in self.children() {
349            if child.chunk.borrow().is_word() {
350                *len += child.chunk.borrow().word().unwrap().chars().count()
351            } else if child.chunk.borrow().is_ws() {
352                *len += child.chunk.borrow().ws().unwrap().chars().count()
353            } else {
354                child.word_len(len);
355            }
356        }
357    }
358}
359
360impl<'a> PartialEq for Node<'a> {
361    fn eq(&self, other: &Self) -> bool {
362        let kin = self.kin.borrow();
363        let other_kin = other.kin.borrow();
364        self.id == other.id
365            && kin.parent == other_kin.parent
366            && kin.prev_sibling == other_kin.prev_sibling
367            && kin.next_sibling == other_kin.next_sibling
368            && kin.children == other_kin.children
369            && self.chunk == other.chunk
370    }
371}
372
373impl<'a> Eq for Node<'a> {}