82 lines
2.8 KiB
Rust
82 lines
2.8 KiB
Rust
use std::collections::{HashMap, HashSet};
|
|
|
|
use thiserror::Error;
|
|
|
|
use crate::{Document, DocumentId};
|
|
|
|
#[derive(Debug, Error, PartialEq, Eq)]
|
|
pub enum TreeError {
|
|
#[error("all documents in the tree must belong to the same workspace")]
|
|
WorkspaceMismatch,
|
|
#[error("a document ID occurs more than once")]
|
|
DuplicateDocument,
|
|
#[error("the document tree has a missing parent or a cycle")]
|
|
InvalidParent,
|
|
}
|
|
|
|
/// An ordered view assembled from one page or content node and its descendants.
|
|
#[derive(Debug)]
|
|
pub struct DocumentTree {
|
|
root: Document,
|
|
descendants: Vec<(usize, Document)>,
|
|
}
|
|
|
|
impl DocumentTree {
|
|
pub fn new(
|
|
root: Document,
|
|
descendants: impl IntoIterator<Item = Document>,
|
|
) -> Result<Self, TreeError> {
|
|
let mut ids = HashSet::from([root.key.document.clone()]);
|
|
let mut by_parent: HashMap<DocumentId, Vec<Document>> = HashMap::new();
|
|
|
|
for document in descendants {
|
|
if document.key.workspace != root.key.workspace {
|
|
return Err(TreeError::WorkspaceMismatch);
|
|
}
|
|
if !ids.insert(document.key.document.clone()) {
|
|
return Err(TreeError::DuplicateDocument);
|
|
}
|
|
let parent = document.parent_id.clone().ok_or(TreeError::InvalidParent)?;
|
|
by_parent.entry(parent).or_default().push(document);
|
|
}
|
|
if root.parent_id.as_ref().is_some_and(|id| ids.contains(id)) {
|
|
return Err(TreeError::InvalidParent);
|
|
}
|
|
for siblings in by_parent.values_mut() {
|
|
// The ID breaks ties consistently when nodes have the same position.
|
|
siblings.sort_by(|a, b| {
|
|
a.position
|
|
.cmp(&b.position)
|
|
.then_with(|| a.key.document.as_str().cmp(b.key.document.as_str()))
|
|
});
|
|
}
|
|
let mut pending: Vec<_> = by_parent
|
|
.remove(&root.key.document)
|
|
.unwrap_or_default()
|
|
.into_iter()
|
|
.rev()
|
|
.map(|node| (1, node))
|
|
.collect();
|
|
let mut ordered = Vec::with_capacity(ids.len() - 1);
|
|
while let Some((depth, node)) = pending.pop() {
|
|
if let Some(children) = by_parent.remove(&node.key.document) {
|
|
pending.extend(children.into_iter().rev().map(|child| (depth + 1, child)));
|
|
}
|
|
ordered.push((depth, node));
|
|
}
|
|
if !by_parent.is_empty() {
|
|
return Err(TreeError::InvalidParent);
|
|
}
|
|
Ok(Self {
|
|
root,
|
|
descendants: ordered,
|
|
})
|
|
}
|
|
|
|
/// Traverses the root and descendants in display order, with their depth.
|
|
pub fn nodes(&self) -> impl Iterator<Item = (usize, &Document)> {
|
|
std::iter::once((0, &self.root))
|
|
.chain(self.descendants.iter().map(|(depth, node)| (*depth, node)))
|
|
}
|
|
}
|