canvist_model 0.2.2

Block-based rich-text document model for the canvist editor: schema, inline mark runs, invertible steps, and transactions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Schemas describe which blocks, marks, and inline embeds a document allows.
//!
//! Extensions contribute [`BlockSpec`]s, [`MarkSpec`]s, and [`EmbedSpec`]s to a
//! [`SchemaBuilder`]; [`SchemaBuilder::build`] resolves every name into a
//! compact numeric id so that documents store `u16` type ids instead of
//! strings. Only the extensions an app registers end up in its schema, which
//! is how canvist keeps "pay for what you use".

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 {
			/// The index of this type within its schema.
			#[must_use]
			pub const fn index(self) -> usize {
				self.0 as usize
			}
		}
	};
}

type_id!(
	/// Identifies a block type within one [`Schema`].
	BlockTypeId
);
type_id!(
	/// Identifies a mark type within one [`Schema`].
	MarkTypeId
);
type_id!(
	/// Identifies an inline embed type within one [`Schema`].
	EmbedTypeId
);

/// What a block type may contain, as declared by an extension.
#[derive(Clone, Debug, PartialEq)]
pub enum ContentSpec {
	/// Inline text with marks and embeds, e.g. a paragraph or heading.
	Inline,
	/// Child blocks whose type name or group appears in the list, e.g. a list
	/// containing `list_item`s or a blockquote containing the `block` group.
	Blocks(Vec<Arc<str>>),
	/// No content at all, e.g. a divider or an image.
	Leaf,
}

/// Declares a block type.
#[derive(Clone, Debug)]
pub struct BlockSpec {
	/// Unique name, e.g. `paragraph`.
	pub name: Arc<str>,
	/// What the block may contain.
	pub content: ContentSpec,
	/// Groups this block belongs to, e.g. `block`, usable in content rules.
	pub groups: Vec<Arc<str>>,
	/// Default attributes for newly created blocks.
	pub attrs: Attrs,
}

impl BlockSpec {
	/// A block holding inline text, in the `block` group.
	#[must_use]
	pub fn text(name: &str) -> Self {
		Self::new(name, ContentSpec::Inline)
	}

	/// A block holding child blocks of the given types or groups.
	#[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))
	}

	/// A block with no content.
	#[must_use]
	pub fn leaf(name: &str) -> Self {
		Self::new(name, ContentSpec::Leaf)
	}

	/// Replace the default attributes.
	#[must_use]
	pub fn attrs(mut self, attrs: Attrs) -> Self {
		self.attrs = attrs;
		self
	}

	/// Replace the groups (the default is `["block"]`).
	#[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(),
		}
	}
}

/// Declares a mark type such as bold or link.
#[derive(Clone, Debug)]
pub struct MarkSpec {
	/// Unique name, e.g. `bold`.
	pub name: Arc<str>,
	/// Whether text typed at the end of the mark extends it. Links are
	/// usually not inclusive; bold usually is.
	pub inclusive: bool,
	/// Other mark types that cannot coexist with this one. A mark always
	/// excludes other instances of its own type.
	pub excludes: Vec<Arc<str>>,
	/// Mark types this one excludes when the schema has them, such as
	/// subscript and superscript, which an app may register one without the
	/// other.
	pub excludes_registered: Vec<Arc<str>>,
	/// Default attributes.
	pub attrs: Attrs,
}

impl MarkSpec {
	/// An inclusive mark with no exclusions.
	#[must_use]
	pub fn new(name: &str) -> Self {
		Self {
			name: name.into(),
			inclusive: true,
			excludes: Vec::new(),
			excludes_registered: Vec::new(),
			attrs: Attrs::new(),
		}
	}

	/// Set whether typing at the mark's end extends it.
	#[must_use]
	pub fn inclusive(mut self, inclusive: bool) -> Self {
		self.inclusive = inclusive;
		self
	}

	/// Declare mark types this mark cannot coexist with.
	#[must_use]
	pub fn excludes(mut self, names: &[&str]) -> Self {
		self.excludes = names.iter().map(|&name| name.into()).collect();
		self
	}

	/// Declare mark types this mark excludes if they are registered. Unlike
	/// [`MarkSpec::excludes`], a missing name is not an error.
	#[must_use]
	pub fn excludes_registered(mut self, names: &[&str]) -> Self {
		self.excludes_registered = names.iter().map(|&name| name.into()).collect();
		self
	}

	/// Replace the default attributes.
	#[must_use]
	pub fn attrs(mut self, attrs: Attrs) -> Self {
		self.attrs = attrs;
		self
	}
}

/// Declares an inline embed: an atomic inline object such as a mention, an
/// inline image, or a hard line break.
#[derive(Clone, Debug)]
pub struct EmbedSpec {
	/// Unique name, e.g. `mention`.
	pub name: Arc<str>,
	/// Default attributes.
	pub attrs: Attrs,
}

impl EmbedSpec {
	/// An embed with no default attributes.
	#[must_use]
	pub fn new(name: &str) -> Self {
		Self {
			name: name.into(),
			attrs: Attrs::new(),
		}
	}

	/// Replace the default attributes.
	#[must_use]
	pub fn attrs(mut self, attrs: Attrs) -> Self {
		self.attrs = attrs;
		self
	}
}

/// Attributes one extension adds to types another registers, like TipTap's
/// global attributes: text alignment on paragraphs and headings, or a
/// colour on the `textStyle` mark.
#[derive(Clone, Debug)]
struct SharedAttrs {
	/// The block or mark type names that receive the attributes. Names the
	/// schema lacks are skipped.
	types: Vec<Arc<str>>,
	/// The attributes, with their defaults.
	attrs: Attrs,
}

impl SharedAttrs {
	fn new(types: &[&str], attrs: Attrs) -> Self {
		Self {
			types: types.iter().map(|&name| name.into()).collect(),
			attrs,
		}
	}

	/// Add the attributes to `target` if `name` is one of the types,
	/// keeping defaults the type already declares.
	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());
			}
		}
	}
}

/// Resolved content rule of a [`BlockType`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContentKind {
	/// Inline text.
	Inline,
	/// Child blocks of the listed types.
	Blocks(Vec<BlockTypeId>),
	/// No content.
	Leaf,
}

/// A resolved block type.
#[derive(Clone, Debug)]
pub struct BlockType {
	/// The type's id.
	pub id: BlockTypeId,
	/// The type's name.
	pub name: Arc<str>,
	/// What the block may contain.
	pub content: ContentKind,
	/// Default attributes.
	pub attrs: Attrs,
}

/// A resolved mark type.
#[derive(Clone, Debug)]
pub struct MarkType {
	/// The type's id. Marks in a set are ordered by id.
	pub id: MarkTypeId,
	/// The type's name.
	pub name: Arc<str>,
	/// Whether typing at the end of the mark extends it.
	pub inclusive: bool,
	/// Mark types removed when this mark is added, always including itself.
	pub excludes: Vec<MarkTypeId>,
	/// Default attributes.
	pub attrs: Attrs,
}

/// A resolved inline embed type.
#[derive(Clone, Debug)]
pub struct EmbedType {
	/// The type's id.
	pub id: EmbedTypeId,
	/// The type's name.
	pub name: Arc<str>,
	/// Default attributes.
	pub attrs: Attrs,
}

/// Errors raised while building a [`Schema`].
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SchemaError {
	/// Two specs of the same kind share a name.
	#[error("duplicate {kind} type `{name}`")]
	Duplicate {
		/// `block`, `mark`, or `embed`.
		kind: &'static str,
		/// The duplicated name.
		name: Arc<str>,
	},
	/// A content rule or exclusion names something that does not exist.
	#[error("`{owner}` refers to unknown {kind} or group `{name}`")]
	Unknown {
		/// The spec containing the reference.
		owner: Arc<str>,
		/// `block` or `mark`.
		kind: &'static str,
		/// The unknown name.
		name: Arc<str>,
	},
	/// The root allows no inline-content block, so text cannot be typed.
	#[error("the root content must allow at least one text block")]
	NoTextBlock,
	/// More than 65 536 types of one kind were registered.
	#[error("too many {0} types")]
	TooMany(&'static str),
}

/// Collects specs and resolves them into a [`Schema`].
#[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 {
	/// An empty builder whose root accepts the `block` group.
	#[must_use]
	pub fn new() -> Self {
		Self {
			root: vec!["block".into()],
			..Self::default()
		}
	}

	/// Register a block type.
	#[must_use]
	pub fn block(mut self, spec: BlockSpec) -> Self {
		self.blocks.push(spec);
		self
	}

	/// Register a mark type. Registration order defines mark ordering.
	#[must_use]
	pub fn mark(mut self, spec: MarkSpec) -> Self {
		self.marks.push(spec);
		self
	}

	/// Register an inline embed type.
	#[must_use]
	pub fn embed(mut self, spec: EmbedSpec) -> Self {
		self.embeds.push(spec);
		self
	}

	/// Set the block types or groups allowed at the document root.
	#[must_use]
	pub fn root(mut self, children: &[&str]) -> Self {
		self.root = children.iter().map(|&child| child.into()).collect();
		self
	}

	/// Add `attrs` to the block types named in `types`, whichever extension
	/// registers them and in whatever order. Types the schema lacks are
	/// skipped, and a default the type declares itself wins.
	#[must_use]
	pub fn block_attrs(mut self, types: &[&str], attrs: Attrs) -> Self {
		self.block_attrs.push(SharedAttrs::new(types, attrs));
		self
	}

	/// Add `attrs` to the mark types named in `types`, as
	/// [`SchemaBuilder::block_attrs`] does for blocks.
	#[must_use]
	pub fn mark_attrs(mut self, types: &[&str], attrs: Attrs) -> Self {
		self.mark_attrs.push(SharedAttrs::new(types, attrs));
		self
	}

	/// Fold the shared attributes into the specs they name.
	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);
			}
		}
	}

	/// Resolve every name and validate the schema.
	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)
}

/// Expands child names, which may be type names or group names, into ids.
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,
	}
}

/// A resolved, immutable schema shared by every document that uses it.
#[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 {
	/// Start building a schema.
	#[must_use]
	pub fn builder() -> SchemaBuilder {
		SchemaBuilder::new()
	}

	/// The resolved block type for `id`.
	///
	/// # Panics
	///
	/// Panics if `id` came from a different schema with fewer block types.
	#[must_use]
	pub fn block(&self, id: BlockTypeId) -> &BlockType {
		&self.blocks[id.index()]
	}

	/// The resolved mark type for `id`.
	///
	/// # Panics
	///
	/// Panics if `id` came from a different schema with fewer mark types.
	#[must_use]
	pub fn mark(&self, id: MarkTypeId) -> &MarkType {
		&self.marks[id.index()]
	}

	/// The resolved embed type for `id`.
	///
	/// # Panics
	///
	/// Panics if `id` came from a different schema with fewer embed types.
	#[must_use]
	pub fn embed(&self, id: EmbedTypeId) -> &EmbedType {
		&self.embeds[id.index()]
	}

	/// Look up a block type by name.
	#[must_use]
	pub fn block_type(&self, name: &str) -> Option<BlockTypeId> {
		self.block_names.get(name).copied().map(BlockTypeId)
	}

	/// Look up a mark type by name.
	#[must_use]
	pub fn mark_type(&self, name: &str) -> Option<MarkTypeId> {
		self.mark_names.get(name).copied().map(MarkTypeId)
	}

	/// Look up an embed type by name.
	#[must_use]
	pub fn embed_type(&self, name: &str) -> Option<EmbedTypeId> {
		self.embed_names.get(name).copied().map(EmbedTypeId)
	}

	/// All block types, indexed by [`BlockTypeId::index`].
	#[must_use]
	pub fn blocks(&self) -> &[BlockType] {
		&self.blocks
	}

	/// All mark types, indexed by [`MarkTypeId::index`].
	#[must_use]
	pub fn marks(&self) -> &[MarkType] {
		&self.marks
	}

	/// Block types allowed at the document root.
	#[must_use]
	pub fn root_children(&self) -> &[BlockTypeId] {
		&self.root
	}

	/// The text block created for new lines and empty documents: the first
	/// root-allowed block with inline content.
	#[must_use]
	pub fn default_text_block(&self) -> BlockTypeId {
		self.default_text_block
	}

	/// Whether `child` may appear directly inside `parent` (`None` is the
	/// document root).
	#[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));
	}
}