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
//! [`Schema`] — the set of node and mark types a document may use — and the
//! [`SchemaBuilder`] used to declare one.
//!
//! The [`schema!`](crate::schema) macro is ergonomic sugar over this builder
//! (see [`schema_macro`](crate::schema_macro)); it expands to the same
//! `.node(..)` / `.mark(..)` / `.build()` calls.
use std::collections::HashMap;
use std::sync::Arc;
use crate::attrs::{AttrValue, Attrs};
use crate::content::{compile_content, ContentMatch};
use crate::error::{DocError, SchemaError};
use crate::fragment::Fragment;
use crate::html::{DomSpec, ParseRule};
use crate::mark::{Mark, MarkType, MarkTypeInner};
use crate::node::{Node, NodeType, NodeTypeInner};
/// Declaration of a single attribute: its default value, if any. An attribute
/// with no default is required at construction time.
#[derive(Debug, Clone, Default)]
pub struct AttrSpec {
/// Default value used when the attribute is omitted.
pub default: Option<AttrValue>,
}
/// Declaration of a node type.
#[derive(Debug, Clone, Default)]
pub struct NodeSpec {
/// Content expression for valid children (e.g. `"paragraph+"`). `None`
/// means a leaf node.
pub content: Option<String>,
/// Group(s) this node belongs to (space-separated), referenced from
/// other nodes' content expressions.
pub group: Option<String>,
/// Mark expression for allowed marks: `None` = allow all on inline nodes
/// and none on block nodes; `Some("_")` = allow all; `Some("")` = none;
/// `Some("strong em")` = only those.
pub marks: Option<String>,
/// Whether this node is inline (text is always inline regardless).
pub inline: bool,
/// Whether this node is an opaque atom even if it has content.
pub atom: bool,
/// Attribute declarations.
pub attrs: HashMap<String, AttrSpec>,
/// How to render a node of this type to an HTML element. `None` means
/// the node is transparent in HTML (only its content is serialized) —
/// the usual choice for the top/document node.
pub to_dom: Option<fn(&Node) -> DomSpec>,
/// Rules mapping HTML elements back to this node type when parsing.
pub parse_dom: Vec<ParseRule>,
}
/// Declaration of a mark type.
#[derive(Debug, Clone, Default)]
pub struct MarkSpec {
/// Group(s) this mark belongs to.
pub group: Option<String>,
/// Whether the mark is inclusive (the editor extends it when typing at
/// its boundary). Stored for adapters; not interpreted by `core` in v0.1.
pub inclusive: bool,
/// Attribute declarations.
pub attrs: HashMap<String, AttrSpec>,
/// How to render this mark to an HTML element wrapping the marked text.
pub to_dom: Option<fn(&Mark) -> DomSpec>,
/// Rules mapping HTML elements back to this mark type when parsing.
pub parse_dom: Vec<ParseRule>,
}
/// Builder for a [`Schema`]. Node and mark declaration order is preserved and
/// determines schema ids.
#[derive(Default)]
pub struct SchemaBuilder {
nodes: Vec<(String, NodeSpec)>,
marks: Vec<(String, MarkSpec)>,
top_node: Option<String>,
}
impl SchemaBuilder {
/// Start an empty builder.
pub fn new() -> Self {
Self::default()
}
/// Declare a node type. The type named `text` is the document's text
/// node and must be a leaf.
pub fn node(mut self, name: &str, spec: NodeSpec) -> Self {
self.nodes.push((name.to_string(), spec));
self
}
/// Declare a mark type.
pub fn mark(mut self, name: &str, spec: MarkSpec) -> Self {
self.marks.push((name.to_string(), spec));
self
}
/// Set the top (document) node type name. Defaults to `"doc"`.
pub fn top_node(mut self, name: &str) -> Self {
self.top_node = Some(name.to_string());
self
}
/// Validate and compile the schema.
pub fn build(self) -> Result<Schema, SchemaError> {
if self.nodes.is_empty() {
return Err(SchemaError::Empty);
}
// Assign ids; detect duplicates.
let mut node_index: HashMap<String, usize> = HashMap::new();
for (i, (name, _)) in self.nodes.iter().enumerate() {
if node_index.insert(name.clone(), i).is_some() {
return Err(SchemaError::DuplicateType(name.clone()));
}
}
let mut mark_index: HashMap<String, usize> = HashMap::new();
for (i, (name, _)) in self.marks.iter().enumerate() {
if mark_index.insert(name.clone(), i).is_some() {
return Err(SchemaError::DuplicateType(name.clone()));
}
}
let top_name = self.top_node.clone().unwrap_or_else(|| "doc".to_string());
if !node_index.contains_key(&top_name) {
return Err(SchemaError::UnknownTopNode(top_name));
}
// Group → node ids, for content-expression resolution.
let mut group_ids: HashMap<String, Vec<usize>> = HashMap::new();
for (i, (_, spec)) in self.nodes.iter().enumerate() {
if let Some(g) = &spec.group {
for grp in g.split_whitespace() {
group_ids.entry(grp.to_string()).or_default().push(i);
}
}
}
let name_to_id = node_index.clone();
let resolve = move |name: &str| -> Option<Vec<usize>> {
if let Some(&id) = name_to_id.get(name) {
Some(vec![id])
} else {
group_ids.get(name).cloned()
}
};
// Build node types.
let mut nodes: Vec<NodeType> = Vec::with_capacity(self.nodes.len());
let mut content_matches: Vec<ContentMatch> = Vec::with_capacity(self.nodes.len());
for (i, (name, spec)) in self.nodes.iter().enumerate() {
let expr = spec.content.clone().unwrap_or_default();
let cm = compile_content(name, &expr, &resolve)?;
// A node is a leaf when its content expression can match no
// child of any type (e.g. `text`, an empty expression, an image).
let is_leaf = (0..self.nodes.len()).all(|t| cm.match_type(t).is_none());
let groups = spec
.group
.as_ref()
.map(|g| g.split_whitespace().map(String::from).collect())
.unwrap_or_default();
nodes.push(NodeType(Arc::new(NodeTypeInner {
id: i,
name: name.clone(),
spec: spec.clone(),
groups,
is_text: name == "text",
content_is_empty: is_leaf,
})));
content_matches.push(cm);
}
let marks: Vec<MarkType> = self
.marks
.iter()
.enumerate()
.map(|(i, (name, spec))| {
MarkType(Arc::new(MarkTypeInner {
id: i,
name: name.clone(),
spec: spec.clone(),
}))
})
.collect();
let top = node_index[&top_name];
Ok(Schema(Arc::new(SchemaInner {
nodes,
node_index,
marks,
mark_index,
top,
content_matches,
})))
}
}
#[derive(Debug)]
pub(crate) struct SchemaInner {
nodes: Vec<NodeType>,
node_index: HashMap<String, usize>,
marks: Vec<MarkType>,
mark_index: HashMap<String, usize>,
top: usize,
content_matches: Vec<ContentMatch>,
}
/// An immutable, validated set of node and mark types. Cloning is O(1).
#[derive(Debug, Clone)]
pub struct Schema(pub(crate) Arc<SchemaInner>);
impl Schema {
/// Look up a node type by name.
pub fn node_type(&self, name: &str) -> Option<&NodeType> {
self.0.node_index.get(name).map(|&i| &self.0.nodes[i])
}
/// Look up a mark type by name.
pub fn mark_type(&self, name: &str) -> Option<&MarkType> {
self.0.mark_index.get(name).map(|&i| &self.0.marks[i])
}
/// The top (document) node type.
pub fn top_node_type(&self) -> &NodeType {
&self.0.nodes[self.0.top]
}
/// All node types, ordered by id.
pub fn node_types(&self) -> &[NodeType] {
&self.0.nodes
}
/// All mark types, ordered by id.
pub fn mark_types(&self) -> &[MarkType] {
&self.0.marks
}
pub(crate) fn content_match(&self, type_id: usize) -> &ContentMatch {
&self.0.content_matches[type_id]
}
/// Whether a node of type `sub` may be joined onto one of type `main`
/// (used by the replace algorithm). Same type, or sharing an acceptable
/// first child type.
pub(crate) fn types_compatible(&self, sub: &NodeType, main: &NodeType) -> bool {
sub == main
|| self
.content_match(sub.id())
.compatible(self.content_match(main.id()))
}
/// Whether `frag`'s children satisfy `parent`'s content expression.
pub(crate) fn fragment_valid(&self, parent: &NodeType, frag: &Fragment) -> bool {
self.content_valid(parent, frag.children())
}
fn fill_attrs(spec_attrs: &HashMap<String, AttrSpec>, mut given: Attrs) -> Attrs {
for (k, s) in spec_attrs {
if !given.contains_key(k) {
if let Some(d) = &s.default {
given.insert(k.clone(), d.clone());
}
}
}
given
}
/// Whether `children` (in order) satisfy `parent`'s content expression.
pub fn content_valid(&self, parent: &NodeType, children: &[Node]) -> bool {
let cm = self.content_match(parent.id());
cm.matches_complete(children.iter().map(|c| c.node_type().id()))
}
/// Build a validated element node.
///
/// Attributes are filled from spec defaults. Returns
/// [`DocError::UnknownNodeType`] for an unknown name or
/// [`DocError::InvalidContent`] if the children violate the schema.
pub fn node(
&self,
name: &str,
attrs: Attrs,
children: Vec<Node>,
marks: Vec<Mark>,
) -> Result<Node, DocError> {
let nt = self
.node_type(name)
.ok_or_else(|| DocError::UnknownNodeType(name.to_string()))?
.clone();
if !self.content_valid(&nt, &children) {
return Err(DocError::InvalidContent {
parent: name.to_string(),
});
}
let attrs = Self::fill_attrs(&nt.0.spec.attrs, attrs);
Ok(Node::new_element(
nt,
attrs,
crate::fragment::Fragment::from_nodes(children),
marks,
))
}
/// Build a node **without** validating its content — e.g. an empty
/// wrapper consumed by [`ReplaceAroundStep`](crate::ReplaceAroundStep).
/// The replace that consumes it still validates the resulting document,
/// so this cannot persist a schema-invalid tree.
pub fn create_node(
&self,
name: &str,
attrs: Attrs,
children: Vec<Node>,
marks: Vec<Mark>,
) -> Result<Node, DocError> {
let nt = self
.node_type(name)
.ok_or_else(|| DocError::UnknownNodeType(name.to_string()))?
.clone();
let attrs = Self::fill_attrs(&nt.0.spec.attrs, attrs);
Ok(Node::new_element(
nt,
attrs,
crate::fragment::Fragment::from_nodes(children),
marks,
))
}
/// Build a text node carrying `text` with the given marks.
pub fn text(&self, text: &str, marks: Vec<Mark>) -> Result<Node, DocError> {
let nt = self
.0
.nodes
.iter()
.find(|n| n.is_text())
.ok_or_else(|| DocError::UnknownNodeType("text".to_string()))?
.clone();
Ok(Node::new_text(nt, text.to_string(), marks))
}
}