1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::sync::{
    Arc,
    Mutex,
    MutexGuard,
};

use freya_native_core::NodeId;
use rustc_hash::{
    FxHashMap,
    FxHashSet,
};
use uuid::Uuid;

#[derive(Default, Clone)]
pub struct ParagraphElements {
    pub paragraphs: Arc<Mutex<FxHashMap<Uuid, FxHashSet<NodeId>>>>,
}

impl ParagraphElements {
    pub fn insert_paragraph(&self, node_id: NodeId, text_id: Uuid) {
        let mut paragraphs = self.paragraphs.lock().unwrap();
        let text_group = paragraphs.entry(text_id).or_default();

        text_group.insert(node_id);
    }

    pub fn paragraphs(&self) -> MutexGuard<FxHashMap<Uuid, FxHashSet<NodeId>>> {
        self.paragraphs.lock().unwrap()
    }

    pub fn remove_paragraph(&self, node_id: NodeId, text_id: &Uuid) {
        let mut paragraphs = self.paragraphs.lock().unwrap();
        let text_group = paragraphs.get_mut(text_id);

        if let Some(text_group) = text_group {
            text_group.retain(|id| *id != node_id);

            if text_group.is_empty() {
                paragraphs.remove(text_id);
            }
        }
    }

    pub fn len_paragraphs(&self) -> usize {
        self.paragraphs.lock().unwrap().len()
    }
}