Model pages and blocks as document nodes
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
use crate::{
|
||||
Document, DocumentContent, DocumentTree, Inline, Organization, OrganizationMembership,
|
||||
OrganizationRole, RichText, User, Workspace,
|
||||
};
|
||||
|
||||
/// Produces a textual description from already available data.
|
||||
pub trait Contextualize {
|
||||
fn render_context(&self) -> String;
|
||||
}
|
||||
|
||||
impl Contextualize for RichText {
|
||||
fn render_context(&self) -> String {
|
||||
let mut text = String::new();
|
||||
for item in &self.0 {
|
||||
match item {
|
||||
Inline::Text(value) => text.push_str(value),
|
||||
Inline::Link { label, url } => {
|
||||
text.push_str(label);
|
||||
text.push_str(" (");
|
||||
text.push_str(url);
|
||||
text.push(')');
|
||||
}
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
impl Contextualize for DocumentTree {
|
||||
fn render_context(&self) -> String {
|
||||
let mut text = String::new();
|
||||
let mut first_line = true;
|
||||
for (depth, node) in self.nodes() {
|
||||
let rendered = node.render_context();
|
||||
for line in rendered.split('\n') {
|
||||
if !first_line {
|
||||
text.push('\n');
|
||||
}
|
||||
first_line = false;
|
||||
for _ in 1..depth {
|
||||
text.push_str(" ");
|
||||
}
|
||||
text.push_str(line);
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
impl Contextualize for User {
|
||||
fn render_context(&self) -> String {
|
||||
format!("User: {}", self.display_name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Contextualize for Workspace {
|
||||
fn render_context(&self) -> String {
|
||||
format!("Workspace: {}", self.name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Contextualize for Organization {
|
||||
fn render_context(&self) -> String {
|
||||
format!("Organization: {}", self.name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Contextualize for OrganizationMembership {
|
||||
fn render_context(&self) -> String {
|
||||
let role = match self.role {
|
||||
OrganizationRole::Owner => "owner",
|
||||
OrganizationRole::Admin => "admin",
|
||||
OrganizationRole::Member => "member",
|
||||
};
|
||||
format!(
|
||||
"User {} is a {role} of organization {}",
|
||||
self.user_id.as_str(),
|
||||
self.organization_id.as_str()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{
|
||||
id::{IdError, validate_id},
|
||||
rich_text::RichText,
|
||||
workspace::WorkspaceId,
|
||||
};
|
||||
|
||||
@@ -32,5 +34,39 @@ pub struct DocumentKey {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Document {
|
||||
pub key: DocumentKey,
|
||||
pub body: Value,
|
||||
pub parent_id: Option<DocumentId>,
|
||||
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),
|
||||
}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
//! Logical models for documents, workspaces, users, and organizations.
|
||||
|
||||
mod context;
|
||||
mod document;
|
||||
mod id;
|
||||
mod organization;
|
||||
mod rich_text;
|
||||
mod tree;
|
||||
mod user;
|
||||
mod workspace;
|
||||
|
||||
pub use document::{Document, DocumentId, DocumentKey};
|
||||
pub use context::Contextualize;
|
||||
pub use document::{Document, DocumentContent, DocumentId, DocumentKey};
|
||||
pub use id::IdError;
|
||||
pub use organization::{Organization, OrganizationId, OrganizationMembership, OrganizationRole};
|
||||
pub use rich_text::{Inline, RichText};
|
||||
pub use tree::{DocumentTree, TreeError};
|
||||
pub use user::{User, UserId};
|
||||
pub use workspace::{Workspace, WorkspaceId};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
|
||||
pub enum Inline {
|
||||
Text(String),
|
||||
Link { label: String, url: String },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct RichText(pub Vec<Inline>);
|
||||
|
||||
impl From<&str> for RichText {
|
||||
fn from(value: &str) -> Self {
|
||||
Self(vec![Inline::Text(value.into())])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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)))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user