use serde::{Deserialize, Serialize}; use serde_json::Value; use super::contextualize::Contextualize; use super::{ id::{IdError, validate_id}, rich_text::RichText, workspace::WorkspaceId, }; #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct DocumentId(String); impl DocumentId { pub const MAX_BYTES: usize = 128; pub fn new(value: impl Into) -> Result { let value = value.into(); validate_id(&value, Self::MAX_BYTES, IdError::Document)?; Ok(Self(value)) } pub fn as_str(&self) -> &str { &self.0 } } /// A document ID identifies a document within its workspace. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct DocumentKey { pub workspace: WorkspaceId, pub document: DocumentId, } #[derive(Clone, Debug, PartialEq)] pub struct Document { pub key: DocumentKey, pub parent_id: Option, pub position: u64, pub content: DocumentContent, } impl Document { pub fn new(key: DocumentKey, content: DocumentContent) -> Self { Self { key, parent_id: None, position: 0, content, } } } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(tag = "kind", content = "data", rename_all = "snake_case")] pub enum DocumentContent { Page { title: String, }, Heading(RichText), Paragraph(RichText), ListItem(RichText), Todo { text: RichText, checked: bool, }, Code { language: String, source: String, }, /// Preserves documents written with the original arbitrary JSON model. Json(Value), } impl Contextualize for DocumentContent { fn render_context(&self) -> String { match self { Self::Page { title } => format!("# {title}"), Self::Heading(text) => format!("## {}", text.render_context()), Self::Paragraph(text) => text.render_context(), Self::ListItem(text) => format!("- {}", text.render_context()), Self::Todo { text, checked } => { let mark = if *checked { 'x' } else { ' ' }; format!("- [{mark}] {}", text.render_context()) } Self::Code { language, source } => format!("Code ({language}):\n{source}"), Self::Json(value) => value.to_string(), } } } impl Contextualize for Document { fn render_context(&self) -> String { self.content.render_context() } }