canvist_headless 0.2.2

The canvist document model without a UI: load, transform, export, and collaborate on rich-text documents on a server
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
//! Extensions registered by name, for bindings.
//!
//! Schema items are compiled in (architecture Decision 7), so a binding
//! carries every StarterKit extension, plus every other extension with the
//! `extras` feature, and its host language chooses which ones an engine
//! registers. The names are the extension names in the metadata.

use canvist_core::BaseKeymap;
use canvist_core::EditorBuilder;
use canvist_core::EditorError;
use canvist_core::UndoInputRule;
use canvist_extensions::Blockquote;
use canvist_extensions::Bold;
use canvist_extensions::BulletList;
use canvist_extensions::Code;
use canvist_extensions::CodeBlock;
use canvist_extensions::Document;
use canvist_extensions::HardBreak;
use canvist_extensions::Heading;
use canvist_extensions::History;
use canvist_extensions::HorizontalRule;
use canvist_extensions::Italic;
use canvist_extensions::Link;
use canvist_extensions::ListItem;
use canvist_extensions::OrderedList;
use canvist_extensions::Paragraph;
use canvist_extensions::Strike;
use canvist_extensions::TaskList;
use canvist_extensions::TrailingNode;
use canvist_extensions::Underline;

use crate::Engine;
use crate::HeadlessError;

/// Extensions every engine has: the root, paragraphs, the standard keys,
/// and Backspace undoing an input rule.
const ALWAYS: [&str; 4] = ["doc", "paragraph", "baseKeymap", "undoInputRule"];

/// StarterKit extensions an engine may register.
const STARTER_KIT: [&str; 17] = [
	"heading",
	"blockquote",
	"codeBlock",
	"hardBreak",
	"horizontalRule",
	"bulletList",
	"orderedList",
	"listItem",
	"taskList",
	"bold",
	"italic",
	"underline",
	"strike",
	"code",
	"link",
	"history",
	"trailingNode",
];

/// Extensions beyond the StarterKit, compiled with the `extras` feature.
#[cfg(feature = "extras")]
const EXTRA: [&str; 34] = [
	"subscript",
	"superscript",
	"highlight",
	"textStyle",
	"color",
	"backgroundColor",
	"fontFamily",
	"fontSize",
	"lineHeight",
	"textAlign",
	"typography",
	"characterCount",
	"placeholder",
	"mention",
	"hashtag",
	"emoji",
	"image",
	"youtube",
	"twitch",
	"audio",
	"file",
	"details",
	"callout",
	"mathematics",
	"table",
	"findAndReplace",
	"tableOfContents",
	"comments",
	"dragHandle",
	"clearFormatting",
	"ink",
	"kinetic",
	"markdownReveal",
	"conditional",
];

#[cfg(not(feature = "extras"))]
const EXTRA: [&str; 0] = [];

/// Marks inline code excludes when they are registered, as the StarterKit
/// does.
const EXCLUDED_BY_CODE: [&str; 8] = [
	"bold",
	"italic",
	"underline",
	"strike",
	"link",
	"subscript",
	"superscript",
	"highlight",
];

/// A validated set of extension names.
#[derive(Clone, Debug)]
struct Extensions {
	names: Vec<&'static str>,
}

impl Extensions {
	/// Check `names` against the extensions this build has.
	fn parse(names: &[String]) -> Result<Self, EditorError> {
		for name in names {
			let name = name.as_str();

			if !(ALWAYS.contains(&name) || STARTER_KIT.contains(&name) || EXTRA.contains(&name)) {
				return Err(EditorError::UnknownName(name.to_owned()));
			}
		}

		// Register in one fixed order, whatever order the names came in.
		// Marks nest and serialize in registration order, so without this
		// the same names build different schemas: Dart's alphabetical
		// `Extensions.all` would write `<mark><sub>` where TypeScript writes
		// `<sub><mark>`. Taking the known names in order, rather than
		// sorting the given ones, keeps a sort out of every binary.
		let mut found = Vec::new();

		for known in STARTER_KIT.iter().chain(EXTRA.iter()) {
			if names.iter().any(|name| name == known) {
				found.push(*known);
			}
		}

		Ok(Self { names: found })
	}

	fn has(&self, name: &str) -> bool {
		self.names.contains(&name)
	}

	/// Register the extensions on `builder`.
	fn register(&self, builder: &mut EditorBuilder) {
		builder.add(Document);
		builder.add(Paragraph);
		builder.add(BaseKeymap);
		builder.add(UndoInputRule);

		for name in &self.names {
			self.register_one(builder, name);
		}

		let lists = self.has("bulletList") || self.has("orderedList");

		if lists && !self.has("listItem") {
			builder.add(ListItem);
		}
	}

	fn register_one(&self, builder: &mut EditorBuilder, name: &str) {
		match name {
			"heading" => {
				builder.add(Heading::default());
			}
			"blockquote" => {
				builder.add(Blockquote);
			}
			"codeBlock" => {
				builder.add(CodeBlock);
			}
			"hardBreak" => {
				builder.add(HardBreak);
			}
			"horizontalRule" => {
				builder.add(HorizontalRule);
			}
			"bulletList" => {
				builder.add(BulletList);
			}
			"orderedList" => {
				builder.add(OrderedList);
			}
			"listItem" => {
				builder.add(ListItem);
			}
			"taskList" => {
				builder.add(TaskList);
			}
			"bold" => {
				builder.add(Bold);
			}
			"italic" => {
				builder.add(Italic);
			}
			"underline" => {
				builder.add(Underline);
			}
			"strike" => {
				builder.add(Strike);
			}
			"link" => {
				builder.add(Link::default());
			}
			"history" => {
				builder.add(History);
			}
			"trailingNode" => {
				builder.add(TrailingNode);
			}
			"code" => {
				let excludes = EXCLUDED_BY_CODE
					.into_iter()
					.filter(|mark| self.has(mark))
					.collect();
				builder.add(Code { excludes });
			}
			_ => register_extra(builder, name),
		}
	}
}

/// Register one of the extensions beyond the StarterKit.
#[cfg(feature = "extras")]
fn register_extra(builder: &mut EditorBuilder, name: &str) {
	use canvist_extensions::Audio;
	use canvist_extensions::BackgroundColor;
	use canvist_extensions::Callout;
	use canvist_extensions::CharacterCount;
	use canvist_extensions::ClearFormatting;
	use canvist_extensions::Color;
	use canvist_extensions::Comments;
	use canvist_extensions::Conditional;
	use canvist_extensions::Details;
	use canvist_extensions::DragHandle;
	use canvist_extensions::Emoji;
	use canvist_extensions::File;
	use canvist_extensions::FindAndReplace;
	use canvist_extensions::FontFamily;
	use canvist_extensions::FontSize;
	use canvist_extensions::Hashtag;
	use canvist_extensions::Highlight;
	use canvist_extensions::Image;
	use canvist_extensions::Ink;
	use canvist_extensions::Kinetic;
	use canvist_extensions::LineHeight;
	use canvist_extensions::MarkdownReveal;
	use canvist_extensions::Mathematics;
	use canvist_extensions::Mention;
	use canvist_extensions::Placeholder;
	use canvist_extensions::Subscript;
	use canvist_extensions::Superscript;
	use canvist_extensions::Table;
	use canvist_extensions::TableOfContents;
	use canvist_extensions::TextAlign;
	use canvist_extensions::TextStyle;
	use canvist_extensions::Twitch;
	use canvist_extensions::Typography;
	use canvist_extensions::Youtube;

	match name {
		"subscript" => {
			builder.add(Subscript);
		}
		"superscript" => {
			builder.add(Superscript);
		}
		"highlight" => {
			builder.add(Highlight::default());
		}
		"textStyle" => {
			builder.add(TextStyle);
		}
		"color" => {
			builder.add(Color);
		}
		"backgroundColor" => {
			builder.add(BackgroundColor);
		}
		"fontFamily" => {
			builder.add(FontFamily);
		}
		"fontSize" => {
			builder.add(FontSize);
		}
		"lineHeight" => {
			builder.add(LineHeight);
		}
		"textAlign" => {
			builder.add(TextAlign::default());
		}
		"typography" => {
			builder.add(Typography::default());
		}
		"characterCount" => {
			builder.add(CharacterCount::default());
		}
		"placeholder" => {
			builder.add(Placeholder::default());
		}
		"mention" => {
			builder.add(Mention::default());
		}
		"hashtag" => {
			builder.add(Hashtag);
		}
		"emoji" => {
			builder.add(Emoji);
		}
		"image" => {
			builder.add(Image);
		}
		"youtube" => {
			builder.add(Youtube);
		}
		"twitch" => {
			builder.add(Twitch);
		}
		"audio" => {
			builder.add(Audio);
		}
		"file" => {
			builder.add(File);
		}
		"details" => {
			builder.add(Details);
		}
		"callout" => {
			builder.add(Callout);
		}
		"mathematics" => {
			builder.add(Mathematics);
		}
		"table" => {
			builder.add(Table);
		}
		"findAndReplace" => {
			builder.add(FindAndReplace);
		}
		"tableOfContents" => {
			builder.add(TableOfContents);
		}
		"comments" => {
			builder.add(Comments);
		}
		"dragHandle" => {
			builder.add(DragHandle);
		}
		"clearFormatting" => {
			builder.add(ClearFormatting);
		}
		"ink" => {
			builder.add(Ink);
		}
		"kinetic" => {
			builder.add(Kinetic);
		}
		"markdownReveal" => {
			builder.add(MarkdownReveal);
		}
		"conditional" => {
			builder.add(Conditional);
		}
		_ => unreachable!("`Extensions::parse` admits only known names"),
	}
}

#[cfg(not(feature = "extras"))]
fn register_extra(_builder: &mut EditorBuilder, _name: &str) {
	unreachable!("`Extensions::parse` admits only known names");
}

impl Engine {
	/// An engine with the StarterKit extensions named in `names`, such as
	/// `["bold", "heading"]`, plus the document, paragraphs, and standard
	/// keys every engine has. Bindings use this to let their host language
	/// pick extensions; Rust code registers typed extensions with
	/// [`Engine::new`] instead.
	///
	/// ```
	/// use canvist_headless::Engine;
	///
	/// let engine = Engine::named(&["bold", "heading"])?;
	/// let doc = engine.parse(canvist_headless::Format::Markdown, "# Hi")?;
	/// assert_eq!(doc.export(canvist_headless::Format::Html), "<h1>Hi</h1>");
	/// # Ok::<(), canvist_headless::HeadlessError>(())
	/// ```
	pub fn named(names: &[impl AsRef<str>]) -> Result<Self, HeadlessError> {
		let names: Vec<String> = names.iter().map(|name| name.as_ref().to_owned()).collect();
		let extensions = Extensions::parse(&names).map_err(HeadlessError::Config)?;
		Self::new(move |builder| extensions.register(builder))
	}
}