use crate::Attrs;
use crate::BlockId;
use crate::BlockTypeId;
use crate::InlineText;
#[derive(Clone, Debug, PartialEq)]
pub enum Content {
Inline(InlineText),
Blocks(Vec<BlockId>),
Leaf,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Block {
pub(crate) id: BlockId,
pub(crate) kind: BlockTypeId,
pub(crate) attrs: Attrs,
pub(crate) parent: Option<BlockId>,
pub(crate) content: Content,
pub(crate) rev: u32,
}
impl Block {
#[must_use]
pub fn id(&self) -> BlockId {
self.id
}
#[must_use]
pub fn kind(&self) -> BlockTypeId {
self.kind
}
#[must_use]
pub fn attrs(&self) -> &Attrs {
&self.attrs
}
#[must_use]
pub fn parent(&self) -> Option<BlockId> {
self.parent
}
#[must_use]
pub fn content(&self) -> &Content {
&self.content
}
#[must_use]
pub fn inline(&self) -> Option<&InlineText> {
match &self.content {
Content::Inline(text) => Some(text),
_ => None,
}
}
#[must_use]
pub fn children(&self) -> &[BlockId] {
match &self.content {
Content::Blocks(children) => children,
_ => &[],
}
}
#[must_use]
pub fn rev(&self) -> u32 {
self.rev
}
pub(crate) fn touch(&mut self) {
self.rev = self.rev.wrapping_add(1);
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum TreeContent {
Inline(InlineText),
Blocks(Vec<BlockTree>),
Leaf,
}
#[derive(Clone, Debug, PartialEq)]
pub struct BlockTree {
pub id: BlockId,
pub kind: BlockTypeId,
pub attrs: Attrs,
pub content: TreeContent,
}
impl BlockTree {
#[must_use]
pub fn text(id: BlockId, kind: BlockTypeId, text: InlineText) -> Self {
Self {
id,
kind,
attrs: Attrs::new(),
content: TreeContent::Inline(text),
}
}
#[must_use]
pub fn container(id: BlockId, kind: BlockTypeId, children: Vec<Self>) -> Self {
Self {
id,
kind,
attrs: Attrs::new(),
content: TreeContent::Blocks(children),
}
}
#[must_use]
pub fn leaf(id: BlockId, kind: BlockTypeId) -> Self {
Self {
id,
kind,
attrs: Attrs::new(),
content: TreeContent::Leaf,
}
}
#[must_use]
pub fn with_attrs(mut self, attrs: Attrs) -> Self {
self.attrs = attrs;
self
}
pub fn walk(&self, visit: &mut impl FnMut(&Self)) {
visit(self);
if let TreeContent::Blocks(children) = &self.content {
for child in children {
child.walk(visit);
}
}
}
}