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
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
#[derive(PartialEq, Debug, Serialize, Default, Clone)]
pub struct Document {
    pub sections: Vec<crate::Section>,
    pub pr_sections: linked_hash_map::LinkedHashMap<String, crate::pr::PR>,
}

impl ToString for Document {
    fn to_string(&self) -> String {
        Self::to_string(&self.sections)
    }
}

pub fn get_title(sections: &[crate::Section]) -> String {
    sections
        .iter()
        .filter(|s| crate::Section::is_heading(s))
        .collect::<Vec<_>>()
        .first()
        .map(|s| s.title())
        .unwrap_or_else(|| "".to_string())
}

pub fn get_no_index(sections: &[crate::Section]) -> bool {
    for s in sections.iter() {
        if let crate::Section::Meta(m) = s {
            if m.no_index {
                return true;
            }
        }
    }
    false
}

impl Document {
    pub fn new(sections: &[crate::Section]) -> Self {
        Self {
            sections: sections.to_vec(),
            pr_sections: Self::get_pr_sections_map(sections),
        }
    }

    pub fn set_default_meta(&mut self, meta: crate::Meta) {
        let mut found = false;
        for s in self.sections.iter() {
            if matches!(s, crate::Section::Meta(_)) {
                found = true;
                break;
            }
        }

        if !found {
            self.sections.insert(0, crate::Section::Meta(meta));
        }
    }

    pub fn is_public(&self) -> bool {
        for s in self.sections.iter() {
            if let crate::Section::Meta(m) = s {
                if m.is_public() {
                    return true;
                }
            }
        }

        false
    }

    pub fn can_read(&self, username: Option<String>) -> bool {
        // TODO: email
        if self.is_public() {
            return true;
        }

        if let Some(u) = username {
            for s in self.sections.iter() {
                if let crate::Section::Meta(m) = s {
                    if m.can_read(u.as_str()) {
                        return true;
                    }
                }
            }
        }

        false
    }

    pub fn can_write(&self, username: &str) -> bool {
        // TODO: email

        for s in self.sections.iter() {
            if let crate::Section::Meta(m) = s {
                if m.can_write(username) {
                    return true;
                }
            }
        }

        false
    }

    pub fn can_admin(&self, username: &str) -> bool {
        // TODO: email

        for s in self.sections.iter() {
            if let crate::Section::Meta(m) = s {
                if m.can_admin(username) {
                    return true;
                }
            }
        }

        false
    }

    pub fn without_special(mut self) -> Self {
        self.sections = self
            .sections
            .into_iter()
            .filter(|s| !s.is_meta() && !s.is_header() && !s.is_second())
            .collect();

        self
    }

    pub fn get_toc(&self) -> Option<crate::ToC> {
        for section in self.sections.iter() {
            if let crate::Section::ToC(toc) = section {
                return Some(toc.clone());
            }
        }
        None
    }

    pub fn get_header(&self) -> crate::ToC {
        for section in self.sections.iter() {
            if let crate::Section::Header(toc) = section {
                return toc.clone();
            }
        }
        ToC::default()
    }

    pub fn get_second(&self) -> Option<crate::ToC> {
        for section in self.sections.iter() {
            if let crate::Section::Second(toc) = section {
                return Some(toc.clone());
            }
        }
        None
    }

    pub fn get_design(&self) -> crate::meta::Design {
        self.get_meta().and_then(|m| m.design).unwrap_or_default()
    }

    pub fn get_meta(&self) -> Option<crate::Meta> {
        for section in self.sections.iter() {
            if let crate::Section::Meta(meta) = section {
                return Some(meta.clone());
            }
        }
        None
    }

    pub fn get_meta_ref(&self) -> Option<&crate::Meta> {
        for section in self.sections.iter() {
            if let crate::Section::Meta(meta) = section {
                return Some(meta);
            }
        }
        None
    }

    pub fn get_translation(&self) -> Option<&crate::meta::Translation> {
        self.get_meta_ref().map(|ref x| x.get_translation())
    }

    pub fn get_language_with_default(&self) -> realm_lang::Language {
        self.get_language().unwrap_or(realm_lang::Language::English)
    }

    pub fn get_language(&self) -> Option<realm_lang::Language> {
        self.get_meta_ref().map(|x| *x.lang.inner())
    }

    pub fn get_translation_and_lang(
        &self,
    ) -> Option<(&crate::meta::Translation, &realm_lang::Language)> {
        self.get_meta_ref()
            .map(|ref x| (x.get_translation(), x.get_lang().inner()))
    }

    pub fn get_title(&self) -> String {
        get_title(&self.sections)
    }

    pub fn no_index(&self) -> bool {
        get_no_index(&self.sections)
    }

    pub fn get_pr_sections(&self) -> Vec<&crate::pr::PR> {
        let mut v = vec![];
        for section in self.sections.iter() {
            if let crate::Section::PR(pr) = section {
                v.push(pr)
            }
        }
        v
    }

    pub fn get_pr_sections_map(
        sections: &[crate::Section],
    ) -> linked_hash_map::LinkedHashMap<String, crate::pr::PR> {
        let mut map: linked_hash_map::LinkedHashMap<String, crate::pr::PR> =
            linked_hash_map::LinkedHashMap::new();
        for section in sections.iter() {
            if let crate::Section::PR(pr) = section.clone() {
                map.insert(pr.unique_id(), pr);
            }
        }
        map
    }

    pub fn parse(s: &str, id: &str) -> Result<Self, ParseError> {
        Self::parse_(s).map_err(|e| {
            observer::log("failed to parse ftd document");
            observer::observe_string("id", id);
            observer::observe_string("err", e.to_string().as_str());
            e
        })
    }

    fn parse_(s: &str) -> Result<Self, ParseError> {
        let p1 = crate::p1::parse(s)?;
        let mut sections = vec![];
        for s in p1 {
            let section = crate::Section::from_p1(&s)?;
            let body = if section.is_heading() && s.body.is_some() {
                s.body.clone()
            } else {
                None
            };
            sections.push(section);
            if let Some(b) = body {
                sections.push(crate::Section::Markdown(crate::Markdown {
                    body: crate::Rendered::from(b.as_str()),
                    hard_breaks: false,
                    auto_links: true,
                    align: Align::default(),
                    direction: TextDirection::default(),
                    two_columns: false,
                    collapsed: false,
                    caption: None,
                }))
            }
        }
        let pr_sections = Self::get_pr_sections_map(&sections);
        Ok(Document {
            sections,
            pr_sections,
        })
    }

    pub fn to_string(sections: &[crate::Section]) -> String {
        sections
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<String>>()
            .join("\n\n\n")
    }
}

#[derive(PartialEq, Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum Align {
    Left,
    Center,
    Right,
}

impl Default for Align {
    fn default() -> Align {
        Align::Left
    }
}

impl Align {
    pub fn as_str(&self) -> &'static str {
        match self {
            Align::Left => "left",
            Align::Center => "center",
            Align::Right => "right",
        }
    }
}

impl std::str::FromStr for Align {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "left" => Ok(Align::Left),
            "right" => Ok(Align::Right),
            "center" => Ok(Align::Center),
            "centre" => Ok(Align::Center),
            _ => Err(
                format!("accepted values: left | right | center, found: {}", s)
                    .as_str()
                    .into(),
            ),
        }
    }
}

#[derive(PartialEq, Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum TextDirection {
    RightToLeft,
    LeftToRight,
}

impl std::str::FromStr for TextDirection {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "rtl" => Ok(TextDirection::RightToLeft),
            "ltr" => Ok(TextDirection::LeftToRight),
            _ => Err(format!("accepted values: ltr | rtl, found: {}", s)
                .as_str()
                .into()),
        }
    }
}

impl Default for TextDirection {
    fn default() -> TextDirection {
        TextDirection::LeftToRight
    }
}

impl TextDirection {
    pub fn as_str(&self) -> &'static str {
        match self {
            TextDirection::LeftToRight => "ltr",
            TextDirection::RightToLeft => "rtl",
        }
    }
}

#[derive(PartialEq, Debug, Clone, Serialize)]
pub struct Table {
    pub caption: crate::Rendered,
    pub header: Vec<crate::Rendered>,
    pub rows: Vec<Vec<crate::Rendered>>,
}

impl ToString for Table {
    fn to_string(&self) -> String {
        todo!()
    }
}

impl Table {
    pub fn to_p1(&self) -> crate::p1::Section {
        todo!()
    }
}

use crate::ToC;
use thiserror::Error as Error_;

#[derive(Error_, Debug)]
pub enum ParseError {
    #[error("P1Error: {0}")]
    P1Error(crate::p1::Error),
    #[error("IntError: {0}")]
    IntError(std::num::ParseIntError),
    #[error("LangError: {0}")]
    LangError(realm_lang::Error),
    #[error("ValidationError: {0}")]
    ValidationError(String),
    #[error("ColorParseError: {0}")]
    ColorParseError(css_color_parser::ColorParseError),
    #[error("ToCError: {0}")]
    ToCError(crate::toc::ParseError),
}

impl From<css_color_parser::ColorParseError> for ParseError {
    fn from(p: css_color_parser::ColorParseError) -> ParseError {
        ParseError::ColorParseError(p)
    }
}

impl From<crate::toc::ParseError> for ParseError {
    fn from(p: crate::toc::ParseError) -> ParseError {
        ParseError::ToCError(p)
    }
}

impl From<std::num::ParseIntError> for ParseError {
    fn from(p: std::num::ParseIntError) -> ParseError {
        ParseError::IntError(p)
    }
}

impl From<crate::p1::Error> for ParseError {
    fn from(p: crate::p1::Error) -> ParseError {
        ParseError::P1Error(p)
    }
}

impl From<&str> for ParseError {
    fn from(s: &str) -> ParseError {
        ParseError::ValidationError(s.to_string())
    }
}

impl From<String> for ParseError {
    fn from(s: String) -> ParseError {
        ParseError::ValidationError(s)
    }
}

impl From<realm_lang::Error> for ParseError {
    fn from(e: realm_lang::Error) -> Self {
        ParseError::LangError(e)
    }
}

#[cfg(test)]
#[track_caller]
pub fn p(s: &str, t: &[crate::Section]) {
    use pretty_assertions::assert_eq;

    assert_eq!(
        Document::parse(s, "foo/bar")
            .unwrap_or_else(|e| panic!("{}", e))
            .sections,
        t
    )
}

#[cfg(test)]
#[track_caller]
pub fn f(s: &str, m: &str) {
    use pretty_assertions::assert_eq;

    match Document::parse(s, "foo/bar") {
        Ok(r) => panic!("expected failure, found: {:?}", r),
        Err(e) => assert_eq!(e.to_string(), m.trim()),
    }
}

pub fn err<T>(msg: &str) -> Result<T, ParseError> {
    Err(crate::document::ParseError::ValidationError(
        msg.to_string(),
    ))
}

#[cfg(test)]
mod test {
    use crate::prelude::*;

    #[test]
    fn escaping() {
        p(
            &indoc!(
                "
            -- code:
            lang: py

            \\-- hello: world
            \\--- damn: man
            "
            ),
            &vec![crate::Section::Code(
                crate::Code::default()
                    .with_code("-- hello: world\n--- damn: man")
                    .with_lang("py"),
            )],
        );
    }

    #[test]
    #[ignore]
    fn definition_list() {
        p(
            &indoc!(
                "
                 -- definition-list: hello list
                 hello:
                     world is
                     not enough

                     lol

                 super:
                    awesome

                 this: is another test
            "
            ),
            &vec![crate::Section::DefinitionList(crate::DefinitionList {
                caption: crate::Rendered::line("hello list"),
                list: vec![
                    (
                        crate::Rendered::line("hello"),
                        crate::Rendered::from("world is\nnot enough\n\nlol"),
                    ),
                    (
                        crate::Rendered::line("super"),
                        crate::Rendered::from("awesome"),
                    ),
                    (
                        crate::Rendered::line("this"),
                        crate::Rendered::from("is another test"),
                    ),
                ],
            })],
        );
        p(
            &indoc!(
                "
                 -- definition-list:
                 without: title
            "
            ),
            &vec![crate::Section::DefinitionList(crate::DefinitionList {
                caption: crate::Rendered::default(),
                list: vec![(
                    crate::Rendered::line("without"),
                    crate::Rendered::from("title"),
                )],
            })],
        );

        f(
            "-- definition-list: items are required",
            indoc!(
                "
                 PestError:  --> 1:1
                   |
                 1 | -- definition-list: items are required
                   | ^---
                   |
                   = expected section
             "
            ),
        );
    }

    // #[test] -- TODO
    #[allow(dead_code)]
    fn latex() {
        p(
            &indoc!(
                "
                 -- latex:
                 hello world is

                     not enough

                     lol
            "
            ),
            &vec![crate::Section::Latex(crate::Latex {
                caption: Some(crate::Rendered::default()),
                body: crate::Rendered::from("hello world is\n\n    not enough\n\n    lol\n"),
            })],
        );

        p(
            &indoc!(
                "
                 -- latex: some title
                 hello world is

                     not enough

                     lol
            "
            ),
            &vec![crate::Section::Latex(crate::Latex {
                caption: Some(crate::Rendered::line("some title")),
                body: crate::Rendered::from("hello world is\n\n    not enough\n\n    lol\n"),
            })],
        );

        f(
            "-- latex: without body",
            indoc!(
                "
                   --> 1:1
                   |
                 1 | -- latex: without body
                   | ^---
                   |
                   = expected section
             "
            ),
        );
        f(
            "-- latex:\n-- latex:",
            indoc!(
                "
                   --> 1:10
                   |
                 1 | -- latex:␊
                   |          ^---
                   |
                   = expected text_till_eol
             "
            ),
        );
        f(
            "-- latex:  \n-- latex:",
            indoc!(
                "
                   --> 1:1
                   |
                 1 | -- latex:  ␊
                   | ^---
                   |
                   = expected section
             "
            ),
        );
    }
}