use serde::{Deserialize, Serialize};
use super::node::Block;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct BlockMeta {
pub source_line: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Document {
pub blocks: Vec<Block>,
#[serde(default)]
pub block_meta: Vec<BlockMeta>,
pub slot_only: bool,
}
impl Document {
pub fn new() -> Self {
Self::default()
}
pub fn from_blocks(blocks: Vec<Block>) -> Self {
let block_meta = vec![BlockMeta::default(); blocks.len()];
Self {
blocks,
block_meta,
slot_only: false,
}
}
pub fn from_blocks_with_meta(blocks: Vec<Block>, block_meta: Vec<BlockMeta>) -> Self {
debug_assert_eq!(
blocks.len(),
block_meta.len(),
"Document::from_blocks_with_meta: blocks and block_meta must be equal length"
);
Self {
blocks,
block_meta,
slot_only: false,
}
}
pub fn has_shortcode(&self, kind: super::shortcode::ShortcodeKind) -> bool {
self.blocks.iter().any(|b| match b {
Block::Shortcode(sc) => sc.kind() == kind,
_ => false,
})
}
}
#[cfg(test)]
mod tests {
use super::super::node::Inline;
use super::*;
#[test]
fn empty_document_has_no_blocks() {
let d = Document::new();
assert!(d.blocks.is_empty());
assert!(!d.slot_only);
}
#[test]
fn from_blocks_constructs_with_blocks() {
let d = Document::from_blocks(vec![Block::ThematicBreak]);
assert_eq!(d.blocks.len(), 1);
assert!(!d.slot_only);
}
#[test]
fn slot_only_default_is_false() {
let d = Document::default();
assert!(!d.slot_only);
}
#[test]
fn slot_only_settable() {
let mut d = Document::new();
d.slot_only = true;
assert!(d.slot_only);
}
#[test]
fn document_round_trips_through_serde() {
let mut original = Document::new();
original.blocks.push(Block::Paragraph(vec![Inline::Text(
"hello".to_string(),
)]));
original.slot_only = true;
let s = serde_json::to_string(&original).expect("serialize");
let back: Document = serde_json::from_str(&s).expect("deserialize");
assert_eq!(original, back);
}
#[test]
fn has_shortcode_returns_false_when_empty() {
let d = Document::new();
assert!(!d.has_shortcode(super::super::shortcode::ShortcodeKind::Subscribe));
}
}