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
use crate::ast::Ast;
use crate::raw::{parse_to_doc, ComposedMarkdown, RawDocument, Special};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct Document<T: Serialize> {
    pub meta: Metadata,
    pub content: T,
    pub code_outputs: HashMap<u64, CodeOutput>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Metadata {
    pub title: String,
    #[serde(default)]
    pub draft: bool,
    #[serde(default = "default_true")]
    pub exercises: bool,
    #[serde(default)]
    pub code_solutions: bool,
    #[serde(default = "default_true")]
    pub cell_outputs: bool,
    #[serde(default)]
    pub interactive: bool,
    #[serde(default)]
    pub editable: bool,
    #[serde(default)]
    pub layout: LayoutSettings,
    #[serde(default)]
    pub exclude_outputs: Option<Vec<String>>,

    #[serde(flatten)]
    pub user_defined: HashMap<String, Value>,
}

const fn default_true() -> bool {
    true
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct LayoutSettings {
    pub hide_sidebar: bool,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Default)]
pub struct CodeOutput {
    pub values: Vec<Outval>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum Outval {
    Text(String),
    Image(Image),
    Json(Value),
    Html(String),
    Javascript(String),
    Error(String),
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum Image {
    Png(String),
    Svg(String),
}

fn parse_raw(doc: RawDocument) -> Result<Document<Ast>> {
    let composed = ComposedMarkdown::from(doc.src);
    let code_outputs = composed
        .children
        .iter()
        .filter_map(|c| match &c.elem {
            Special::CodeBlock { inner, .. } => Some((inner.hash, CodeOutput::default())),
            _ => None,
        })
        .collect();

    let ast = composed.into();

    let doc = Document {
        content: Ast(ast),
        meta: doc.meta.map_or(
            Ok::<Metadata, serde_yaml::Error>(Metadata::default()),
            |meta| serde_yaml::from_str(&meta),
        )?,
        code_outputs,
    };

    Ok(doc)
}

impl TryFrom<&str> for Document<Ast> {
    type Error = anyhow::Error;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let raw = parse_to_doc(value)?;
        parse_raw(raw)
    }
}

impl<T: Serialize> Document<T> {
    pub fn map<O: Serialize, F: Fn(T) -> O>(self, f: F) -> Document<O> {
        Document {
            content: f(self.content),
            meta: self.meta,
            code_outputs: self.code_outputs,
            // references: self.references,
            // references_by_type: self.references_by_type,
        }
    }

    pub fn try_map<O: Serialize, F: Fn(T) -> Result<O>>(self, f: F) -> Result<Document<O>> {
        Ok(Document {
            content: f(self.content)?,
            meta: self.meta,
            code_outputs: self.code_outputs,
            // references: self.references,
            // references_by_type: self.references_by_type,
        })
    }
}