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
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
//! A document with an editor around it, driven by explicit calls.

use std::time::Duration;

use canvist_core::Command;
use canvist_core::CommandResult;
use canvist_core::Editor;
use canvist_core::EditorState;
use canvist_core::Env;
use canvist_core::KeyPress;
use canvist_core::LineNavigator;
use canvist_core::Update;
use canvist_core::commands;
use canvist_core::parse_binding;
use canvist_core::value_to_json;
use canvist_model::Attrs;
#[cfg(feature = "journal")]
use canvist_model::Commit;
use canvist_model::Document;
use canvist_model::Point;
use canvist_model::Selection;
use canvist_model::Value;
use serde_json::Value as Json;

use crate::Format;
use crate::HeadlessError;
use crate::Position;
use crate::Snapshot;
use crate::format;
use crate::position;

/// One document and the editor that changes it, with no layout and no UI.
///
/// Selections are explicit: set one with [`Doc::select`],
/// [`Doc::select_range`], or [`Doc::select_all`], then run commands. Every
/// call is one undo step. A `Doc` is `Send`, so it can move between threads
/// or live behind a `Mutex` in a server.
///
/// ```
/// use canvist_headless::Engine;
/// use canvist_headless::Format;
/// use canvist_headless::Position;
///
/// let engine = Engine::starter_kit();
/// let kit = engine.handles();
/// let mut doc = engine.parse(Format::Markdown, "Hello world")?;
///
/// doc.select_range(&Position::new([0], 6), &Position::new([0], 11))?;
/// doc.run(&kit.italic.toggle())?;
///
/// assert_eq!(doc.export(Format::Markdown), "Hello *world*");
/// # Ok::<(), canvist_headless::HeadlessError>(())
/// ```
pub struct Doc {
	pub(crate) editor: Editor,
	/// The time of the last call. Calls without a host clock advance it by
	/// one second, so each is its own undo step and results never depend on
	/// the wall clock; [`Doc::edit`] moves it to the host's time.
	pub(crate) clock: Duration,
	/// Every commit that changed the document since the host last took
	/// them, while [`Doc::record_commits`] is on.
	#[cfg(feature = "journal")]
	journal: Option<Vec<Commit>>,
	#[cfg(feature = "collab")]
	pub(crate) shared: Option<canvist_collab::Binding>,
	/// Which local changes join the shared history's previous undo step,
	/// by the rule the editor's own history follows.
	#[cfg(feature = "collab")]
	pub(crate) grouping: canvist_core::UndoGrouping,
}

impl std::fmt::Debug for Doc {
	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		formatter
			.debug_struct("Doc")
			.field("editor", &self.editor)
			.finish_non_exhaustive()
	}
}

impl Doc {
	pub(crate) fn new(editor: Editor) -> Self {
		Self {
			editor,
			clock: Duration::ZERO,
			#[cfg(feature = "journal")]
			journal: None,
			#[cfg(feature = "collab")]
			shared: None,
			#[cfg(feature = "collab")]
			grouping: canvist_core::UndoGrouping::default(),
		}
	}

	/// The editor, for typed queries such as
	/// `kit.bold.is_active(doc.editor().state())`.
	#[must_use]
	pub fn editor(&self) -> &Editor {
		&self.editor
	}

	/// The editor state: document, selection, and stored marks.
	#[must_use]
	pub fn state(&self) -> &EditorState {
		self.editor.state()
	}

	/// The model document.
	#[must_use]
	pub fn document(&self) -> &Document {
		self.editor.state().doc()
	}

	/// The document as `format`.
	#[must_use]
	pub fn export(&self, format: Format) -> String {
		format::write(self.document(), format)
	}

	/// The document as ProseMirror and TipTap JSON, with block ids in
	/// `attrs.id`.
	#[must_use]
	pub fn to_json(&self) -> Json {
		self.document().to_json()
	}

	/// The content and selection, to [`Engine::restore`](crate::Engine::restore)
	/// later or elsewhere.
	#[must_use]
	pub fn snapshot(&self) -> Snapshot {
		Snapshot::new(self.to_json(), self.selected_range())
	}

	/// The selection.
	#[must_use]
	pub fn selection(&self) -> Selection {
		self.editor.state().selection()
	}

	/// The anchor and head of a text selection or caret as [`Position`]s,
	/// or `None` for a block selection.
	#[must_use]
	pub fn selected_range(&self) -> Option<(Position, Position)> {
		let Selection::Text { anchor, head } = self.selection() else {
			return None;
		};

		Some((self.position(anchor)?, self.position(head)?))
	}

	/// The model point `position` names.
	pub fn point(&self, position: &Position) -> Result<Point, HeadlessError> {
		position::resolve(self.document(), position)
	}

	/// The position of a model point, or `None` when it is not in this
	/// document.
	#[must_use]
	pub fn position(&self, point: Point) -> Option<Position> {
		position::locate(self.document(), point)
	}

	/// Replace the selection. Points outside the document are repaired to
	/// the nearest valid ones.
	pub fn select(&mut self, selection: Selection) -> Result<(), HeadlessError> {
		let mut env = self.env();
		let mut update = self.editor.select(selection, &mut env)?;
		self.finish(&mut update).map(drop)
	}

	/// Select from `anchor` to `head`; equal positions make a caret.
	pub fn select_range(
		&mut self,
		anchor: &Position,
		head: &Position,
	) -> Result<(), HeadlessError> {
		let anchor = self.point(anchor)?;
		let head = self.point(head)?;
		self.select(Selection::text(anchor, head))
	}

	/// Select the whole document.
	pub fn select_all(&mut self) -> Result<(), HeadlessError> {
		self.run(&canvist_core::command(commands::select_all))
			.map(drop)
	}

	/// Run `command`, usually from a typed handle such as
	/// `kit.bold.toggle()`. Returns whether it applied.
	pub fn run(&mut self, command: &Command) -> Result<bool, HeadlessError> {
		let mut env = self.env();
		let mut update = self.editor.run(command, &mut env)?;
		self.finish(&mut update)
	}

	/// Whether `command` would apply. Nothing changes.
	pub fn can(&mut self, command: &Command) -> Result<bool, HeadlessError> {
		let mut env = self.env();
		Ok(self.editor.can(command, &mut env)?)
	}

	/// Run `commands` as one change and one undo step, or not at all: if
	/// any does not apply, everything rolls back. Returns whether they
	/// applied.
	pub fn chain(&mut self, commands: &[Command]) -> Result<bool, HeadlessError> {
		let mut env = self.env();
		let chain = commands.iter().fold(self.editor.chain(), |chain, command| {
			chain.then(command.clone())
		});
		let mut update = chain.run(&mut env)?;
		self.finish(&mut update)
	}

	/// Run the command an extension registered as `name`, such as
	/// `toggleBold` or `setHeading` with `{ "level": 2 }`. `args` is a JSON
	/// object, or `null` for none. This is the path for bindings and
	/// scripts; Rust code uses typed handles.
	pub fn run_named(&mut self, name: &str, args: &Json) -> Result<bool, HeadlessError> {
		let command = self.command_named(name, args)?;

		#[cfg(feature = "collab")]
		if let Some(redo) = self.shared_history_command(name) {
			return Ok(self.history_step(redo)?.is_some());
		}

		self.run(&command)
	}

	/// The command an extension registered as `name`, with `args` (a JSON
	/// object, or `null` for none) checked against its metadata, for hosts
	/// that run it through [`Doc::edit`].
	pub fn command_named(&self, name: &str, args: &Json) -> Result<Command, HeadlessError> {
		Ok(self.editor.command_named(name, &attrs(name, args)?)?)
	}

	/// Whether the named command would apply. Nothing changes.
	pub fn can_named(&mut self, name: &str, args: &Json) -> Result<bool, HeadlessError> {
		let command = self.command_named(name, args)?;
		self.can(&command)
	}

	/// Answer the query an extension registered as `name`, such as `isBold`
	/// or `headingLevel`.
	pub fn query(&self, name: &str, args: &Json) -> Result<Json, HeadlessError> {
		let value = self.editor.query(name, &attrs(name, args)?)?;
		Ok(value_to_json(&value))
	}

	/// Insert `text` at the selection, replacing it, without running input
	/// rules: `"## "` stays text. Inserting `""` deletes the selection.
	pub fn insert_text(&mut self, text: &str) -> Result<bool, HeadlessError> {
		if text.is_empty() {
			return self.delete_selection();
		}

		let text = text.to_owned();
		let command = canvist_core::command(move |state| commands::insert_text(state, &text));
		self.run(&command)
	}

	/// Delete the selected text or blocks, joining the blocks at the ends of
	/// a text range. Returns whether there was a selection to delete.
	pub fn delete_selection(&mut self) -> Result<bool, HeadlessError> {
		self.run(&canvist_core::command(commands::delete_selection))
	}

	/// Type `text` one character at a time, as a keyboard would, so input
	/// rules apply: `"## "` turns the block into a heading. Returns whether
	/// anything changed.
	pub fn type_text(&mut self, text: &str) -> Result<bool, HeadlessError> {
		let mut changed = false;
		let mut buffer = [0; 4];

		for character in text.chars() {
			let mut env = self.env();
			let mut update = self
				.editor
				.insert_text(character.encode_utf8(&mut buffer), &mut env)?;
			changed |= self.finish(&mut update)?;
		}

		Ok(changed)
	}

	/// Press a key or chord, written as key bindings are: `Enter`,
	/// `Backspace`, `Mod-b`, `Shift-Tab`. `Mod` is Ctrl. Returns whether a
	/// bound command applied.
	pub fn press(&mut self, key: &str) -> Result<bool, HeadlessError> {
		let (key, modifiers) = parse_binding(key, self.editor.platform())?;

		#[cfg(feature = "collab")]
		if let Some(redo) = self.shared_history_key(KeyPress::new(&key, modifiers)) {
			return Ok(self.history_step(redo)?.is_some());
		}

		let mut env = self.env();
		let mut update = self
			.editor
			.handle_key(KeyPress::new(&key, modifiers), &mut env)?;
		self.finish(&mut update)
	}

	/// Paste `content` read as `format` over the selection, as a user
	/// pasting would: paste rules run, and text pasted into code stays
	/// literal.
	pub fn paste(&mut self, format: Format, content: &str) -> Result<bool, HeadlessError> {
		let mut env = self.env();
		let mut update = match format {
			Format::Text => self.editor.paste_text(content, &mut env)?,
			format => {
				let slice = format::read_slice(self.document().schema(), format, content)?;
				self.editor.paste(slice, &mut env)?
			}
		};
		self.finish(&mut update)
	}

	/// Undo the last call that changed the document. Returns whether there
	/// was anything to undo.
	pub fn undo(&mut self) -> Result<bool, HeadlessError> {
		Ok(self.history_step(false)?.is_some())
	}

	/// Redo the last undone call. Returns whether there was anything to
	/// redo.
	pub fn redo(&mut self) -> Result<bool, HeadlessError> {
		Ok(self.history_step(true)?.is_some())
	}

	/// Undo, or with `redo` redo, one step and return the update, for hosts
	/// that lay out again from it. A shared document undoes only this peer's
	/// own changes, through the shared history.
	pub fn history_step(&mut self, redo: bool) -> Result<Option<Update>, HeadlessError> {
		#[cfg(feature = "collab")]
		if self.shared.is_some() {
			return self.undo_shared(redo);
		}

		let mut env = self.env();
		let mut update = if redo {
			self.editor.redo(&mut env)?
		} else {
			self.editor.undo(&mut env)?
		};
		self.finish(&mut update)?;
		Ok(update)
	}

	/// Whether [`Doc::undo`] has anything to undo: this peer's own changes
	/// on a shared document, every change otherwise.
	#[must_use]
	pub fn can_undo(&self) -> bool {
		#[cfg(feature = "collab")]
		if let Some(binding) = &self.shared {
			return binding.can_undo();
		}

		self.editor.can_undo()
	}

	/// Whether [`Doc::redo`] has anything to redo.
	#[must_use]
	pub fn can_redo(&self) -> bool {
		#[cfg(feature = "collab")]
		if let Some(binding) = &self.shared {
			return binding.can_redo();
		}

		self.editor.can_redo()
	}

	/// Stop dictating: forget every dictated segment that is not final yet.
	/// Returns whether provisional text was showing. Report segments with
	/// [`Doc::edit`] and [`Editor::dictate`].
	pub fn stop_dictation(&mut self) -> bool {
		self.editor.stop_dictation()
	}

	/// Change the document through the editor with an interactive host's
	/// clock and line navigator, and return the update so the host can lay
	/// out again.
	///
	/// Keys such as `ArrowUp` and `End` then move by visual lines, and typing
	/// groups into undo steps by real time. Like every other call, the update
	/// passes on to collaborators. `now` never runs backwards: a time before
	/// the last call's counts as that time.
	pub fn edit(
		&mut self,
		now: Duration,
		lines: &mut dyn LineNavigator,
		change: impl FnOnce(&mut Editor, &mut Env<'_>) -> CommandResult,
	) -> Result<Option<Update>, HeadlessError> {
		self.clock = self.clock.max(now);
		let mut env = Env::new(self.clock, lines);
		let mut update = change(&mut self.editor, &mut env)?;
		self.finish(&mut update)?;

		Ok(update)
	}

	/// Record every commit that changes the document from now on, for a host
	/// that keeps a layout of it: local calls, collaborators' updates, the
	/// shared history, and the repairs collaboration makes. Take them with
	/// [`Doc::take_commits`] and pass each to the layout in order.
	///
	/// Hosts that make every change through [`Doc::edit`] can apply the
	/// updates it returns instead, but a host that also lets other code run
	/// commands, or collaborates, sees only some changes that way.
	#[cfg(feature = "journal")]
	pub fn record_commits(&mut self) {
		self.journal.get_or_insert_with(Vec::new);
	}

	/// The commits recorded since the last call, oldest first. Empty unless
	/// [`Doc::record_commits`] is on.
	#[cfg(feature = "journal")]
	pub fn take_commits(&mut self) -> Vec<Commit> {
		self.journal
			.as_mut()
			.map(std::mem::take)
			.unwrap_or_default()
	}

	/// Note `update` in the journal when it changed the document.
	#[cfg(feature = "journal")]
	pub(crate) fn record(&mut self, update: &Update) {
		if let Some(journal) = &mut self.journal
			&& update.doc_changed()
		{
			journal.push(update.commit.clone());
		}
	}

	/// Without the journal there is nothing to note, and nothing to link
	/// into hosts that never record, such as the browser editor.
	#[cfg(not(feature = "journal"))]
	#[allow(clippy::unused_self, reason = "the journal feature records")]
	pub(crate) fn record(&mut self, _update: &Update) {}

	/// A fresh environment, one logical second after the last call.
	pub(crate) fn env(&mut self) -> Env<'static> {
		self.clock += Duration::from_secs(1);
		Env::headless(self.clock)
	}

	/// Pass a local update on to collaborators, and report whether there
	/// was one. A follow-up the shared state needed joins the update's
	/// commit, so hosts lay it out too.
	#[cfg_attr(
		not(feature = "collab"),
		allow(
			clippy::unnecessary_wraps,
			reason = "only shared documents pass updates on"
		)
	)]
	fn finish(&mut self, update: &mut Option<Update>) -> Result<bool, HeadlessError> {
		let Some(update) = update else {
			return Ok(false);
		};

		// Mirror first: a follow-up the shared state needed joins the
		// update's commit, and the journal records it with the rest.
		#[cfg(feature = "collab")]
		self.mirror_local(update)?;
		self.record(update);

		Ok(true)
	}
}

/// Command and query arguments from a JSON object.
fn attrs(name: &str, args: &Json) -> Result<Attrs, HeadlessError> {
	let invalid = |reason: &str| {
		HeadlessError::InvalidArgs {
			name: name.to_owned(),
			reason: reason.to_owned(),
		}
	};

	let fields = match args {
		Json::Null => return Ok(Attrs::new()),
		Json::Object(fields) => fields,
		_ => return Err(invalid("arguments must be an object")),
	};

	fields
		.iter()
		.map(|(key, value)| {
			value_of(value)
				.map(|value| (key.as_str(), value))
				.ok_or_else(|| {
					invalid(&format!(
						"`{key}` must be a string, number, boolean, null, array, or object"
					))
				})
		})
		.collect()
}

fn value_of(json: &Json) -> Option<Value> {
	Some(match json {
		Json::Null => Value::Null,
		Json::Bool(value) => Value::Bool(*value),
		Json::Number(number) => {
			match number.as_i64() {
				Some(int) => Value::from(int),
				None => Value::from(number.as_f64()?),
			}
		}
		Json::String(value) => Value::from(value.as_str()),
		Json::Array(values) => {
			Value::from(values.iter().map(value_of).collect::<Option<Vec<_>>>()?)
		}
		Json::Object(fields) => {
			let attrs = fields
				.iter()
				.map(|(key, value)| Some((key.as_str(), value_of(value)?)))
				.collect::<Option<Attrs>>()?;
			Value::from(attrs)
		}
	})
}