canvist_core 0.2.0

Platform-agnostic editing engine for canvist: editor state, commands, selection motion, keymaps, input rules, and history
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
//! The editor state: a document plus everything editing needs around it.

use std::sync::Arc;

use canvist_model::Attrs;
use canvist_model::Bias;
use canvist_model::BlockId;
use canvist_model::BlockTree;
use canvist_model::Commit;
use canvist_model::Document;
use canvist_model::InlineText;
use canvist_model::MarkSet;
use canvist_model::Point;
use canvist_model::Schema;
use canvist_model::Selection;
use canvist_model::Step;

use crate::Affinity;
use crate::CommandResult;
use crate::Dictation;
use crate::EditKind;
use crate::EditorError;
use crate::EditorTransaction;
use crate::Origin;
use crate::Update;
use crate::position;
use crate::transaction;
use crate::transaction::Effects;
use crate::transaction::Override;

/// The text an input method editor is still composing (its preedit).
///
/// Preedit text lives in the document like ordinary text, so layout and
/// painting need no special case; the composition only remembers its range
/// so the next preedit update can replace it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Composition {
	/// The text block holding the preedit.
	pub block: BlockId,
	/// Where the preedit starts.
	pub start: u32,
	/// Where the preedit ends.
	pub end: u32,
}

impl Composition {
	/// An empty composition at `point`.
	#[must_use]
	pub const fn at(point: Point) -> Self {
		Self {
			block: point.block,
			start: point.offset,
			end: point.offset,
		}
	}

	/// Where the preedit starts.
	#[must_use]
	pub const fn start_point(self) -> Point {
		Point::new(self.block, self.start)
	}

	/// Where the preedit ends.
	#[must_use]
	pub const fn end_point(self) -> Point {
		Point::new(self.block, self.end)
	}

	/// Map the composition through `commit`, dropping it if its text was
	/// deleted or split across blocks.
	fn map(self, commit: &Commit) -> Option<Self> {
		let start = commit.map(self.start_point(), Bias::After);
		let end = commit.map(self.end_point(), Bias::Before);
		let collapsed = self.start == self.end;
		let end_point = if collapsed { start.point } else { end.point };
		let moved_apart =
			start.point.block != end_point.block || end_point.offset < start.point.offset;

		if start.deleted || end.deleted || moved_apart {
			return None;
		}

		Some(Self {
			block: start.point.block,
			start: start.point.offset,
			end: end_point.offset,
		})
	}
}

/// Everything in an [`EditorState`] besides the document.
#[derive(Clone, Debug)]
struct Transient {
	selection: Selection,
	stored_marks: Option<MarkSet>,
	composition: Option<Composition>,
	dictation: Dictation,
	goal: Option<f32>,
	affinity: Affinity,
	settings: Attrs,
}

/// A document, its selection, and the transient state commands consult.
///
/// Every change goes through one path: [`EditorState::change`] for local
/// commands and [`EditorState::apply_steps`] for undo, redo, and remote steps.
/// Both end in the same private `apply`, which maps or sets the selection,
/// maps the composition, clears stale stored marks, and keeps the document
/// non-empty. That single path is what keeps the state consistent.
#[derive(Clone, Debug)]
pub struct EditorState {
	doc: Document,
	selection: Selection,
	stored_marks: Option<MarkSet>,
	composition: Option<Composition>,
	dictation: Dictation,
	goal: Option<f32>,
	affinity: Affinity,
	settings: Attrs,
}

impl EditorState {
	/// Wrap `doc`, placing a caret at the start of its first text block.
	/// An empty document gets one empty block of the schema's default type.
	pub fn new(doc: Document) -> Result<Self, EditorError> {
		let selection = position::start_selection(&doc);
		let mut state = Self {
			doc,
			selection,
			stored_marks: None,
			composition: None,
			dictation: Dictation::default(),
			goal: None,
			affinity: Affinity::Downstream,
			settings: Attrs::new(),
		};

		if state.doc.children(None).is_empty() {
			state.ensure_block()?;
			state.selection = position::start_selection(&state.doc);
		}

		Ok(state)
	}

	/// Settings extensions keep per editor, such as a character limit or a
	/// placeholder, changed by commands with
	/// [`EditorTransaction::set_setting`]. They are not part of the
	/// document, its history, or collaboration, and an absent setting means
	/// the extension's configured default.
	#[must_use]
	pub fn settings(&self) -> &Attrs {
		&self.settings
	}

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

	/// The document's schema.
	#[must_use]
	pub fn schema(&self) -> &Arc<Schema> {
		self.doc.schema()
	}

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

	/// Marks queued for the next typed text, set by toggling a mark at a
	/// collapsed caret.
	#[must_use]
	pub fn stored_marks(&self) -> Option<&MarkSet> {
		self.stored_marks.as_ref()
	}

	/// The active IME composition, if any.
	#[must_use]
	pub fn composition(&self) -> Option<Composition> {
		self.composition
	}

	/// Dictation: segments waiting to be inserted, and text inserted a
	/// moment ago.
	#[must_use]
	pub fn dictation(&self) -> &Dictation {
		&self.dictation
	}

	pub(crate) fn dictation_mut(&mut self) -> &mut Dictation {
		&mut self.dictation
	}

	/// The horizontal position vertical caret motion tries to keep.
	#[must_use]
	pub fn goal(&self) -> Option<f32> {
		self.goal
	}

	/// Which visual line the caret belongs to at a soft wrap.
	#[must_use]
	pub fn affinity(&self) -> Affinity {
		self.affinity
	}

	/// Release the document.
	#[must_use]
	pub fn into_doc(self) -> Document {
		self.doc
	}

	/// Run `build` inside a transaction and apply the result.
	///
	/// `build` returns `Ok(true)` to commit, or `Ok(false)` when the command
	/// turns out not to apply; the transaction is then rolled back and the
	/// result is `Ok(None)`. An error also rolls back every step.
	pub fn change(
		&mut self,
		kind: EditKind,
		build: impl FnOnce(&mut EditorTransaction<'_>) -> Result<bool, EditorError>,
	) -> CommandResult {
		let mut build = Some(build);

		self.change_with(kind, &mut |transaction| {
			build.take().map_or(Ok(false), |build| build(transaction))
		})
	}

	/// [`EditorState::change`] without the generic closure, so every command
	/// shares one copy of the transaction logic instead of one each: in
	/// WebAssembly that is tens of KB.
	fn change_with(
		&mut self,
		kind: EditKind,
		build: &mut dyn FnMut(&mut EditorTransaction<'_>) -> Result<bool, EditorError>,
	) -> CommandResult {
		let mut transaction = EditorTransaction::new(self.doc.transaction(), self.selection, kind);
		let outcome = build(&mut transaction);
		let (inner, effects) = transaction.finish();

		match outcome {
			Ok(true) => {
				let commit = inner.commit();
				self.apply(commit, effects).map(Some)
			}
			Ok(false) => {
				inner.rollback()?;
				Ok(None)
			}
			Err(error) => {
				inner.rollback()?;
				Err(error)
			}
		}
	}

	/// Apply steps produced elsewhere: undo, redo, or a collaborator.
	///
	/// `selection`, if given, replaces the mapped selection afterwards, which
	/// is how undo restores the selection from before the undone change. On
	/// error, nothing changes.
	pub fn apply_steps(
		&mut self,
		steps: impl IntoIterator<Item = Step>,
		kind: EditKind,
		origin: Origin,
		selection: Option<Selection>,
	) -> Result<Update, EditorError> {
		let commit = self.doc.apply_steps(steps)?;
		let mut effects = Effects::new(kind, origin);
		effects.selection = selection;
		self.apply(commit, effects)
	}

	/// Let `change` edit the document directly and fold the commit it
	/// returns into the state, as [`EditorState::apply_steps`] does for steps.
	///
	/// This is for code that must own the edit itself, such as a
	/// collaboration binding integrating a Yjs update into the document it
	/// tracks. `change` must return the commit of exactly the steps it
	/// applied, and must leave the document unchanged when it fails.
	pub fn apply_external<E: From<EditorError>>(
		&mut self,
		kind: EditKind,
		origin: Origin,
		change: impl FnOnce(&mut Document) -> Result<Commit, E>,
	) -> Result<Update, E> {
		let commit = change(&mut self.doc)?;
		Ok(self.apply(commit, Effects::new(kind, origin))?)
	}

	/// Whether `run` would apply, without changing anything: every step it
	/// takes is rolled back through a model savepoint, which also restores
	/// the document version and block revisions, so layout caches stay warm.
	pub fn dry_run(
		&mut self,
		run: impl FnOnce(&mut Self) -> CommandResult,
	) -> Result<bool, EditorError> {
		let saved = self.transient();
		let savepoint = self.doc.savepoint();
		let outcome = run(self);
		self.doc.rollback_to(savepoint)?;
		self.restore(saved);
		outcome.map(|update| update.is_some())
	}

	/// Run `run` all or nothing: if it does not apply, or fails, every change
	/// it made is rolled back exactly.
	pub fn atomic(&mut self, run: impl FnOnce(&mut Self) -> CommandResult) -> CommandResult {
		let saved = self.transient();
		let savepoint = self.doc.savepoint();
		let outcome = run(self);

		if let Ok(Some(update)) = outcome {
			self.doc.release(savepoint);

			return Ok(Some(update));
		}

		self.doc.rollback_to(savepoint)?;
		self.restore(saved);
		outcome
	}

	/// The state besides the document.
	fn transient(&self) -> Transient {
		Transient {
			selection: self.selection,
			stored_marks: self.stored_marks.clone(),
			composition: self.composition,
			dictation: self.dictation.clone(),
			goal: self.goal,
			affinity: self.affinity,
			settings: self.settings.clone(),
		}
	}

	fn restore(&mut self, saved: Transient) {
		self.selection = saved.selection;
		self.stored_marks = saved.stored_marks;
		self.composition = saved.composition;
		self.dictation = saved.dictation;
		self.goal = saved.goal;
		self.affinity = saved.affinity;
		self.settings = saved.settings;
	}

	/// The one place where a commit becomes the new state.
	fn apply(&mut self, commit: Commit, effects: Effects) -> Result<Update, EditorError> {
		let selection_before = self.selection;
		let mut commit = commit;

		if let Some(extra) = self.ensure_block()? {
			commit = transaction::compose(commit, extra);
		}

		let selection = effects
			.selection
			.unwrap_or_else(|| commit.map_selection(selection_before));
		self.selection = position::valid_selection(&self.doc, selection);

		self.composition = match effects.composition {
			Override::Set(composition) => composition,
			Override::Default => {
				self.composition
					.and_then(|composition| composition.map(&commit))
			}
		};

		self.dictation.map(&commit);

		for (key, value) in effects.settings.iter() {
			self.settings.set(key, value.clone());
		}

		let unchanged = commit.is_empty() && self.selection == selection_before;

		self.stored_marks = match effects.stored_marks {
			Override::Set(marks) => marks,

			Override::Default if unchanged => self.stored_marks.take(),
			Override::Default => None,
		};

		// A collaborator's edit that leaves the caret where it was keeps it on
		// its visual line and column; any other change starts afresh.
		let keeps_line = effects.origin == Origin::Remote && self.selection == selection_before;

		if !keeps_line {
			self.goal = effects.goal;
			self.affinity = effects.affinity.unwrap_or_default();
		}

		Ok(Update {
			commit,
			selection_before,
			selection: self.selection,
			kind: effects.kind,
			origin: effects.origin,
		})
	}

	/// Insert an empty default text block if the document has no blocks, so
	/// the selection always has somewhere to be.
	fn ensure_block(&mut self) -> Result<Option<Commit>, EditorError> {
		if !self.doc.children(None).is_empty() {
			return Ok(None);
		}

		let kind = self.doc.schema().default_text_block();
		let mut transaction = self.doc.transaction();
		let id = transaction.allocate_id()?;
		let block = BlockTree::text(id, kind, InlineText::new());
		transaction.insert_blocks(None, 0, vec![block])?;
		Ok(Some(transaction.commit()))
	}
}