nmd_core/dossier/document/chapter/paragraph/paragraph_loading_rule/
common_paragraph_loading_rule.rs

1use once_cell::sync::Lazy;
2use regex::Regex;
3use super::MultiParagraphLoadingRule;
4use crate::{codex::{modifier::constants::{MULTI_LINES_CONTENT_EXCLUDING_HEADINGS_PATTERN, NEW_LINE_PATTERN}, Codex}, dossier::document::chapter::paragraph::{common_paragraph::CommonParagraph, Paragraph}, load::{LoadConfiguration, LoadConfigurationOverLay, LoadError}};
5
6
7static EXTRACT_PARAGRAPH_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(&format!("{}{}{}", MULTI_LINES_CONTENT_EXCLUDING_HEADINGS_PATTERN, NEW_LINE_PATTERN, NEW_LINE_PATTERN)).unwrap());
8
9
10#[derive(Debug)]
11pub struct CommonParagraphLoadingRule {
12}
13
14
15impl CommonParagraphLoadingRule {
16
17    pub fn new() -> Self {
18        Self {}
19    }
20
21    fn inner_load(&self, raw_content: &str, _codex: &Codex, _configuration: &LoadConfiguration, _configuration_overlay: LoadConfigurationOverLay) -> Vec<CommonParagraph> {
22        
23        let mut raw_content = String::from(raw_content);
24
25        while !raw_content.ends_with("\n\n") {
26            raw_content.push_str("\n");
27        }
28
29        let mut paragraphs: Vec<CommonParagraph> = Vec::new(); 
30
31        for m in EXTRACT_PARAGRAPH_REGEX.find_iter(&raw_content) {
32            paragraphs.push(
33                CommonParagraph::new(m.as_str().to_string())
34            );
35        }
36
37        paragraphs
38    }
39}
40
41
42impl MultiParagraphLoadingRule for CommonParagraphLoadingRule {
43    fn load(&self, raw_content: &str, codex: &Codex, configuration: &LoadConfiguration, configuration_overlay: LoadConfigurationOverLay) -> Result<Vec<Box<dyn Paragraph>>, LoadError> {
44        
45        Ok(self.inner_load(raw_content, codex, configuration, configuration_overlay).into_iter().map(|p| {
46            Box::new(p) as Box<dyn Paragraph>
47        }).collect())
48    }
49}
50
51
52#[cfg(test)]
53mod test {
54
55    use crate::{codex::Codex, load::{LoadConfiguration, LoadConfigurationOverLay}};
56    use super::CommonParagraphLoadingRule;
57
58
59    #[test]
60    fn load_common_paragraph() {
61        let nmd_text = concat!(
62            "a\n",
63            "b\n",
64            "\n",
65            "c\n",
66            "\n\n\n\n",
67            "d",
68        );
69
70        let rule = CommonParagraphLoadingRule::new();
71
72        let paragraphs = rule.inner_load(&nmd_text, &Codex::of_html(), &LoadConfiguration::default(), LoadConfigurationOverLay::default());    
73    
74        assert_eq!(paragraphs.len(), 3);
75    }
76
77
78}