use std::sync::Arc;
use rustc_hash::FxHashMap;
use crate::Attrs;
macro_rules! type_id {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct $name(u16);
impl $name {
#[must_use]
pub const fn index(self) -> usize {
self.0 as usize
}
}
};
}
type_id!(
BlockTypeId
);
type_id!(
MarkTypeId
);
type_id!(
EmbedTypeId
);
#[derive(Clone, Debug, PartialEq)]
pub enum ContentSpec {
Inline,
Blocks(Vec<Arc<str>>),
Leaf,
}
#[derive(Clone, Debug)]
pub struct BlockSpec {
pub name: Arc<str>,
pub content: ContentSpec,
pub groups: Vec<Arc<str>>,
pub attrs: Attrs,
}
impl BlockSpec {
#[must_use]
pub fn text(name: &str) -> Self {
Self::new(name, ContentSpec::Inline)
}
#[must_use]
pub fn container(name: &str, children: &[&str]) -> Self {
let children = children.iter().map(|&child| child.into()).collect();
Self::new(name, ContentSpec::Blocks(children))
}
#[must_use]
pub fn leaf(name: &str) -> Self {
Self::new(name, ContentSpec::Leaf)
}
#[must_use]
pub fn attrs(mut self, attrs: Attrs) -> Self {
self.attrs = attrs;
self
}
#[must_use]
pub fn groups(mut self, groups: &[&str]) -> Self {
self.groups = groups.iter().map(|&group| group.into()).collect();
self
}
fn new(name: &str, content: ContentSpec) -> Self {
Self {
name: name.into(),
content,
groups: vec!["block".into()],
attrs: Attrs::new(),
}
}
}
#[derive(Clone, Debug)]
pub struct MarkSpec {
pub name: Arc<str>,
pub inclusive: bool,
pub excludes: Vec<Arc<str>>,
pub excludes_registered: Vec<Arc<str>>,
pub attrs: Attrs,
}
impl MarkSpec {
#[must_use]
pub fn new(name: &str) -> Self {
Self {
name: name.into(),
inclusive: true,
excludes: Vec::new(),
excludes_registered: Vec::new(),
attrs: Attrs::new(),
}
}
#[must_use]
pub fn inclusive(mut self, inclusive: bool) -> Self {
self.inclusive = inclusive;
self
}
#[must_use]
pub fn excludes(mut self, names: &[&str]) -> Self {
self.excludes = names.iter().map(|&name| name.into()).collect();
self
}
#[must_use]
pub fn excludes_registered(mut self, names: &[&str]) -> Self {
self.excludes_registered = names.iter().map(|&name| name.into()).collect();
self
}
#[must_use]
pub fn attrs(mut self, attrs: Attrs) -> Self {
self.attrs = attrs;
self
}
}
#[derive(Clone, Debug)]
pub struct EmbedSpec {
pub name: Arc<str>,
pub attrs: Attrs,
}
impl EmbedSpec {
#[must_use]
pub fn new(name: &str) -> Self {
Self {
name: name.into(),
attrs: Attrs::new(),
}
}
#[must_use]
pub fn attrs(mut self, attrs: Attrs) -> Self {
self.attrs = attrs;
self
}
}
#[derive(Clone, Debug)]
struct SharedAttrs {
types: Vec<Arc<str>>,
attrs: Attrs,
}
impl SharedAttrs {
fn new(types: &[&str], attrs: Attrs) -> Self {
Self {
types: types.iter().map(|&name| name.into()).collect(),
attrs,
}
}
fn extend(&self, name: &Arc<str>, target: &mut Attrs) {
if !self.types.contains(name) {
return;
}
for (key, value) in self.attrs.iter() {
if target.get(key).is_none() {
target.set(key, value.clone());
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContentKind {
Inline,
Blocks(Vec<BlockTypeId>),
Leaf,
}
#[derive(Clone, Debug)]
pub struct BlockType {
pub id: BlockTypeId,
pub name: Arc<str>,
pub content: ContentKind,
pub attrs: Attrs,
}
#[derive(Clone, Debug)]
pub struct MarkType {
pub id: MarkTypeId,
pub name: Arc<str>,
pub inclusive: bool,
pub excludes: Vec<MarkTypeId>,
pub attrs: Attrs,
}
#[derive(Clone, Debug)]
pub struct EmbedType {
pub id: EmbedTypeId,
pub name: Arc<str>,
pub attrs: Attrs,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SchemaError {
#[error("duplicate {kind} type `{name}`")]
Duplicate {
kind: &'static str,
name: Arc<str>,
},
#[error("`{owner}` refers to unknown {kind} or group `{name}`")]
Unknown {
owner: Arc<str>,
kind: &'static str,
name: Arc<str>,
},
#[error("the root content must allow at least one text block")]
NoTextBlock,
#[error("too many {0} types")]
TooMany(&'static str),
}
#[derive(Clone, Debug, Default)]
pub struct SchemaBuilder {
blocks: Vec<BlockSpec>,
marks: Vec<MarkSpec>,
embeds: Vec<EmbedSpec>,
root: Vec<Arc<str>>,
block_attrs: Vec<SharedAttrs>,
mark_attrs: Vec<SharedAttrs>,
}
impl SchemaBuilder {
#[must_use]
pub fn new() -> Self {
Self {
root: vec!["block".into()],
..Self::default()
}
}
#[must_use]
pub fn block(mut self, spec: BlockSpec) -> Self {
self.blocks.push(spec);
self
}
#[must_use]
pub fn mark(mut self, spec: MarkSpec) -> Self {
self.marks.push(spec);
self
}
#[must_use]
pub fn embed(mut self, spec: EmbedSpec) -> Self {
self.embeds.push(spec);
self
}
#[must_use]
pub fn root(mut self, children: &[&str]) -> Self {
self.root = children.iter().map(|&child| child.into()).collect();
self
}
#[must_use]
pub fn block_attrs(mut self, types: &[&str], attrs: Attrs) -> Self {
self.block_attrs.push(SharedAttrs::new(types, attrs));
self
}
#[must_use]
pub fn mark_attrs(mut self, types: &[&str], attrs: Attrs) -> Self {
self.mark_attrs.push(SharedAttrs::new(types, attrs));
self
}
fn share_attrs(&mut self) {
for shared in &self.block_attrs {
for spec in &mut self.blocks {
shared.extend(&spec.name, &mut spec.attrs);
}
}
for shared in &self.mark_attrs {
for spec in &mut self.marks {
shared.extend(&spec.name, &mut spec.attrs);
}
}
}
pub fn build(mut self) -> Result<Schema, SchemaError> {
self.share_attrs();
let block_names = index_names("block", self.blocks.iter().map(|spec| &spec.name))?;
let mark_names = index_names("mark", self.marks.iter().map(|spec| &spec.name))?;
let embed_names = index_names("embed", self.embeds.iter().map(|spec| &spec.name))?;
let resolver = ChildResolver::new(&self.blocks, &block_names);
let blocks = self
.blocks
.iter()
.enumerate()
.map(|(index, spec)| resolve_block(index, spec, &resolver))
.collect::<Result<Vec<_>, _>>()?;
let marks = self
.marks
.iter()
.enumerate()
.map(|(index, spec)| resolve_mark(index, spec, &mark_names))
.collect::<Result<Vec<_>, _>>()?;
let embeds = self
.embeds
.into_iter()
.enumerate()
.map(|(index, spec)| resolve_embed(index, spec))
.collect();
let root = resolver.resolve(&"doc".into(), &self.root)?;
let default_text_block = root
.iter()
.copied()
.find(|id| blocks[id.index()].content == ContentKind::Inline)
.ok_or(SchemaError::NoTextBlock)?;
Ok(Schema {
blocks,
marks,
embeds,
root,
default_text_block,
block_names,
mark_names,
embed_names,
})
}
}
fn index_names<'a>(
kind: &'static str,
names: impl Iterator<Item = &'a Arc<str>>,
) -> Result<FxHashMap<Arc<str>, u16>, SchemaError> {
let mut index = FxHashMap::default();
for (position, name) in names.enumerate() {
let id = u16::try_from(position).map_err(|_| SchemaError::TooMany(kind))?;
if index.insert(name.clone(), id).is_some() {
return Err(SchemaError::Duplicate {
kind,
name: name.clone(),
});
}
}
Ok(index)
}
struct ChildResolver<'a> {
names: &'a FxHashMap<Arc<str>, u16>,
groups: FxHashMap<Arc<str>, Vec<BlockTypeId>>,
}
impl<'a> ChildResolver<'a> {
fn new(specs: &[BlockSpec], names: &'a FxHashMap<Arc<str>, u16>) -> Self {
let mut groups: FxHashMap<Arc<str>, Vec<BlockTypeId>> = FxHashMap::default();
for (index, spec) in specs.iter().enumerate() {
for group in &spec.groups {
groups
.entry(group.clone())
.or_default()
.push(BlockTypeId(index as u16));
}
}
Self { names, groups }
}
fn resolve(
&self,
owner: &Arc<str>,
children: &[Arc<str>],
) -> Result<Vec<BlockTypeId>, SchemaError> {
let mut ids = Vec::new();
for child in children {
ids.extend(self.lookup(owner, child)?);
}
ids.sort_unstable();
ids.dedup();
Ok(ids)
}
fn lookup(&self, owner: &Arc<str>, child: &Arc<str>) -> Result<Vec<BlockTypeId>, SchemaError> {
if let Some(&id) = self.names.get(child) {
return Ok(vec![BlockTypeId(id)]);
}
self.groups.get(child).cloned().ok_or_else(|| {
SchemaError::Unknown {
owner: owner.clone(),
kind: "block",
name: child.clone(),
}
})
}
}
fn resolve_block(
index: usize,
spec: &BlockSpec,
resolver: &ChildResolver<'_>,
) -> Result<BlockType, SchemaError> {
let content = match &spec.content {
ContentSpec::Inline => ContentKind::Inline,
ContentSpec::Leaf => ContentKind::Leaf,
ContentSpec::Blocks(children) => {
ContentKind::Blocks(resolver.resolve(&spec.name, children)?)
}
};
Ok(BlockType {
id: BlockTypeId(index as u16),
name: spec.name.clone(),
content,
attrs: spec.attrs.clone(),
})
}
fn resolve_mark(
index: usize,
spec: &MarkSpec,
names: &FxHashMap<Arc<str>, u16>,
) -> Result<MarkType, SchemaError> {
let id = MarkTypeId(index as u16);
let mut excludes = vec![id];
for name in &spec.excludes {
let other = names.get(name).ok_or_else(|| {
SchemaError::Unknown {
owner: spec.name.clone(),
kind: "mark",
name: name.clone(),
}
})?;
excludes.push(MarkTypeId(*other));
}
let registered = spec
.excludes_registered
.iter()
.filter_map(|name| names.get(name));
excludes.extend(registered.map(|&other| MarkTypeId(other)));
excludes.sort_unstable();
excludes.dedup();
Ok(MarkType {
id,
name: spec.name.clone(),
inclusive: spec.inclusive,
excludes,
attrs: spec.attrs.clone(),
})
}
fn resolve_embed(index: usize, spec: EmbedSpec) -> EmbedType {
EmbedType {
id: EmbedTypeId(index as u16),
name: spec.name,
attrs: spec.attrs,
}
}
#[derive(Clone, Debug)]
pub struct Schema {
blocks: Vec<BlockType>,
marks: Vec<MarkType>,
embeds: Vec<EmbedType>,
root: Vec<BlockTypeId>,
default_text_block: BlockTypeId,
block_names: FxHashMap<Arc<str>, u16>,
mark_names: FxHashMap<Arc<str>, u16>,
embed_names: FxHashMap<Arc<str>, u16>,
}
impl Schema {
#[must_use]
pub fn builder() -> SchemaBuilder {
SchemaBuilder::new()
}
#[must_use]
pub fn block(&self, id: BlockTypeId) -> &BlockType {
&self.blocks[id.index()]
}
#[must_use]
pub fn mark(&self, id: MarkTypeId) -> &MarkType {
&self.marks[id.index()]
}
#[must_use]
pub fn embed(&self, id: EmbedTypeId) -> &EmbedType {
&self.embeds[id.index()]
}
#[must_use]
pub fn block_type(&self, name: &str) -> Option<BlockTypeId> {
self.block_names.get(name).copied().map(BlockTypeId)
}
#[must_use]
pub fn mark_type(&self, name: &str) -> Option<MarkTypeId> {
self.mark_names.get(name).copied().map(MarkTypeId)
}
#[must_use]
pub fn embed_type(&self, name: &str) -> Option<EmbedTypeId> {
self.embed_names.get(name).copied().map(EmbedTypeId)
}
#[must_use]
pub fn blocks(&self) -> &[BlockType] {
&self.blocks
}
#[must_use]
pub fn marks(&self) -> &[MarkType] {
&self.marks
}
#[must_use]
pub fn root_children(&self) -> &[BlockTypeId] {
&self.root
}
#[must_use]
pub fn default_text_block(&self) -> BlockTypeId {
self.default_text_block
}
#[must_use]
pub fn allows_child(&self, parent: Option<BlockTypeId>, child: BlockTypeId) -> bool {
let allowed = match parent {
None => &self.root,
Some(parent) => {
match &self.block(parent).content {
ContentKind::Blocks(allowed) => allowed,
ContentKind::Inline | ContentKind::Leaf => return false,
}
}
};
allowed.binary_search(&child).is_ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Value;
fn sample() -> Schema {
Schema::builder()
.block(BlockSpec::text("paragraph"))
.block(BlockSpec::text("heading").attrs(Attrs::new().with("level", 1)))
.block(BlockSpec::container("bullet_list", &["list_item"]))
.block(BlockSpec::container("list_item", &["paragraph", "bullet_list"]).groups(&[]))
.block(BlockSpec::leaf("divider"))
.mark(MarkSpec::new("bold"))
.mark(MarkSpec::new("code").excludes(&["bold"]))
.mark(MarkSpec::new("link").inclusive(false))
.embed(EmbedSpec::new("mention"))
.build()
.expect("sample schema is valid")
}
#[test]
fn resolves_groups_and_names() {
let schema = sample();
let list = schema.block_type("bullet_list").expect("list exists");
let item = schema.block_type("list_item").expect("item exists");
let paragraph = schema.block_type("paragraph").expect("paragraph exists");
assert!(schema.allows_child(None, list));
assert!(
!schema.allows_child(None, item),
"list_item is not in the block group"
);
assert!(schema.allows_child(Some(list), item));
assert!(schema.allows_child(Some(item), paragraph));
assert!(!schema.allows_child(Some(paragraph), paragraph));
assert_eq!(schema.default_text_block(), paragraph);
}
#[test]
fn marks_always_exclude_themselves() {
let schema = sample();
let bold = schema.mark_type("bold").expect("bold exists");
let code = schema.mark_type("code").expect("code exists");
assert_eq!(schema.mark(bold).excludes, [bold]);
assert_eq!(schema.mark(code).excludes, [bold, code]);
assert!(
!schema
.mark(schema.mark_type("link").expect("link exists"))
.inclusive
);
}
#[test]
fn rejects_duplicates_and_unknown_references() {
let duplicate = Schema::builder()
.block(BlockSpec::text("paragraph"))
.block(BlockSpec::text("paragraph"))
.build();
let unknown = Schema::builder()
.block(BlockSpec::text("paragraph"))
.block(BlockSpec::container("list", &["missing"]))
.build();
assert!(matches!(
duplicate,
Err(SchemaError::Duplicate { kind: "block", .. })
));
assert!(matches!(unknown, Err(SchemaError::Unknown { .. })));
}
#[test]
fn shares_attributes_with_the_types_they_name() {
let schema = Schema::builder()
.block(BlockSpec::text("paragraph"))
.block(BlockSpec::text("heading").attrs(Attrs::new().with("level", 1)))
.block_attrs(
&["paragraph", "heading", "missing"],
Attrs::new().with("textAlign", Value::Null).with("level", 9),
)
.mark(MarkSpec::new("textStyle"))
.mark_attrs(&["textStyle"], Attrs::new().with("color", Value::Null))
.build()
.expect("shared attributes are valid");
let paragraph = schema.block_type("paragraph").expect("paragraph exists");
let heading = schema.block_type("heading").expect("heading exists");
let style = schema.mark_type("textStyle").expect("textStyle exists");
assert_eq!(
schema.block(paragraph).attrs.get("textAlign"),
Some(&Value::Null)
);
assert_eq!(
schema.block(heading).attrs.get("level"),
Some(&Value::Int(1)),
"the type's own default wins"
);
assert_eq!(schema.mark(style).attrs.get("color"), Some(&Value::Null));
}
#[test]
fn excludes_registered_marks_and_skips_missing_ones() {
let schema = Schema::builder()
.block(BlockSpec::text("paragraph"))
.mark(MarkSpec::new("subscript").excludes_registered(&["superscript"]))
.mark(MarkSpec::new("superscript").excludes_registered(&["subscript"]))
.mark(MarkSpec::new("small").excludes_registered(&["missing"]))
.build()
.expect("missing names are skipped");
let sub = schema.mark_type("subscript").expect("subscript exists");
let sup = schema.mark_type("superscript").expect("superscript exists");
assert_eq!(schema.mark(sub).excludes, [sub, sup]);
assert_eq!(schema.mark(sup).excludes, [sub, sup]);
}
#[test]
fn requires_a_root_text_block() {
let schema = Schema::builder().block(BlockSpec::leaf("divider")).build();
assert_eq!(schema.err(), Some(SchemaError::NoTextBlock));
}
}