Skip to main content

tilo_resource/
text.rs

1//! Collaborative plain text: a SQL buffer, a report note, a commit message,
2//! a source file.
3//!
4//! [`PlainText`] is a resource whose state is one string, stored as an
5//! Automerge text object, and whose edits are [`TextEdit`] splices — the
6//! characters typed, not the whole text — so two people typing in the same
7//! text merge character by character, and typing a word is one undo step.
8//!
9//! On its own a record's text lives under the root key [`TEXT_KEY`]. Inside
10//! another resource it is a child ([`crate::child`]): the parent's action
11//! carries one [`TextEdit`] and finds the text object it applies under with
12//! [`TextEdit::apply_under`].
13
14use automerge::transaction::Transactable;
15use automerge::{ObjId, ObjType, ROOT, ReadDoc, Value};
16use serde::{Deserialize, Serialize};
17use tilo_actions::{ActionError, ActionParam, ParamType};
18
19use crate::model::{Doc, ModelError};
20use crate::resource::{ActionDecl, Resource, SearchEntry};
21
22/// The root key a record's own [`PlainText`] is stored under.
23pub const TEXT_KEY: &str = "text";
24
25/// The mark naming who wrote a run of text: the author of the action that
26/// inserted it. Members' views highlight what each person wrote.
27pub const AUTHOR_MARK: &str = "author";
28
29/// Mark `inserted`, just written at the document text index `at` of the text
30/// object `obj`, as written by the author of the action applying now, or,
31/// outside an action, by the actor a record write is lent
32/// ([`crate::action::ResourceActorScope`]): a store writing an action's edits
33/// before it commits them as the action's change marks them as replaying the
34/// action does. Nothing is marked for an action with no invoker, or with no
35/// actor lent.
36pub fn mark_authored(
37    doc: &mut impl Transactable,
38    obj: &ObjId,
39    at: usize,
40    inserted: &str,
41) -> Result<(), automerge::AutomergeError> {
42    let Some(author) = crate::action::writing_author() else {
43        return Ok(());
44    };
45    tilo_automerge::mark_text_author(doc, obj, at, inserted, &author_mark(&author))
46}
47
48/// A new text holding `text`, marked as [`mark_authored`] marks a text a
49/// store writes, made with its mark at once: a `String` field of an item
50/// made whole ([`crate::Model::fresh`]).
51#[must_use]
52pub fn authored(encoding: automerge::TextEncoding, text: &str) -> automerge::hydrate::Text {
53    match crate::action::writing_author() {
54        Some(author) => tilo_automerge::authored_text(encoding, text, &author_mark(&author)),
55        None => automerge::hydrate::Text::new(encoding, text),
56    }
57}
58
59/// The value a text's author mark holds for `author`: the actor bytes their
60/// changes carry, as the text they are (a person's key, `agent:<id>`).
61#[must_use]
62pub fn author_mark(author: &tilo_action_policy::MemberId) -> String {
63    String::from_utf8_lossy(&author.actor_bytes()).into_owned()
64}
65
66/// The registry type id [`TextEdit`]s replay under.
67pub const TEXT_ACTION_TYPE: &str = "tilo.text";
68
69/// Plain text, edited a splice at a time.
70pub struct PlainText;
71
72/// One edit of plain text. Positions count characters (Unicode scalar
73/// values), whatever the document's own text encoding.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(tag = "action", rename_all = "kebab-case")]
76pub enum TextEdit {
77    /// Replace `delete` characters at `at` with `insert`: typing is a
78    /// splice that deletes nothing, Backspace one that inserts nothing.
79    Splice {
80        at: usize,
81        delete: usize,
82        insert: String,
83    },
84    /// Replace the whole text with `text`, written as the smallest splice
85    /// that turns what the document holds into it, so a member's
86    /// concurrent typing elsewhere survives.
87    ReplaceText { text: String },
88}
89
90impl PlainText {
91    pub fn read_under(doc: &Doc, obj: &ObjId) -> Result<String, ModelError> {
92        doc.text(obj)
93            .map_err(|error| ModelError::invalid(format!("not a text: {error}")))
94    }
95
96    /// The text object of a record's own text, if it has one.
97    pub fn root_text(doc: &Doc) -> Option<ObjId> {
98        match doc.get(ROOT, TEXT_KEY) {
99            Ok(Some((Value::Object(ObjType::Text), obj))) => Some(obj),
100            _ => None,
101        }
102    }
103}
104
105/// Copy the text object `from` onto the new text object `into`: its
106/// characters and its marks. A record's migration moves a whole value, and a
107/// text's formatting is part of what it is.
108pub fn copy_whole(
109    doc: &mut Doc,
110    from: &ObjId,
111    into: &ObjId,
112) -> Result<(), automerge::AutomergeError> {
113    let text = doc.text(from)?;
114    doc.splice_text(into, 0, 0, &text)?;
115    for mark in doc.marks(from)? {
116        doc.mark(into, mark, automerge::marks::ExpandMark::None)?;
117    }
118    Ok(())
119}
120
121/// Where `chars` characters into `text` falls in the document's own text
122/// index.
123fn index(doc: &Doc, text: &str, chars: usize) -> usize {
124    let prefix: &str = text
125        .char_indices()
126        .nth(chars)
127        .and_then(|(byte, _)| text.get(..byte))
128        .unwrap_or(text);
129    match doc.text_encoding() {
130        automerge::TextEncoding::Utf8CodeUnit => prefix.len(),
131        automerge::TextEncoding::Utf16CodeUnit => prefix.encode_utf16().count(),
132        _ => prefix.chars().count(),
133    }
134}
135
136pub use tilo_actions::{common_ends, common_text_ends};
137
138/// The smallest splice, in characters, that turns `before` into `after`:
139/// what the two share at their start and end is kept.
140#[must_use]
141pub fn splice_between(before: &str, after: &str) -> Option<TextEdit> {
142    tilo_actions::splice_between(before, after).map(|splice| TextEdit::Splice {
143        at: splice.at,
144        delete: splice.delete,
145        insert: splice.insert,
146    })
147}
148
149impl TextEdit {
150    /// Apply this edit to the text object `obj` of another resource.
151    ///
152    /// # Errors
153    /// Returns [`ActionError::Refused`] when `obj` is not a text object or
154    /// the splice reaches past the end of the text; nothing is written.
155    pub fn apply_under(&self, doc: &mut Doc, obj: &ObjId) -> Result<(), ActionError> {
156        let current = doc
157            .text(obj)
158            .map_err(|_| ActionError::Refused("the text is gone".into()))?;
159        self.apply_to(doc, obj, &current)
160    }
161
162    /// [`Self::apply_under`] when the caller already read `current`, the
163    /// text `obj` holds now: a large text is not read a second time.
164    ///
165    /// # Errors
166    /// As [`Self::apply_under`].
167    pub fn apply_to(&self, doc: &mut Doc, obj: &ObjId, current: &str) -> Result<(), ActionError> {
168        let (at, delete, insert) = match self {
169            Self::Splice { at, delete, insert } => (*at, *delete, insert.clone()),
170            Self::ReplaceText { text } => match splice_between(current, text) {
171                Some(Self::Splice { at, delete, insert }) => (at, delete, insert),
172                _ => return Ok(()),
173            },
174        };
175        let length = current.chars().count();
176        if at > length || delete > length.saturating_sub(at) {
177            return Err(ActionError::Refused(format!(
178                "the text has {length} characters; the edit reaches past its end"
179            )));
180        }
181        let start = index(doc, current, at);
182        let end = index(doc, current, at.saturating_add(delete));
183        let removed = isize::try_from(end.saturating_sub(start))
184            .map_err(|_| ActionError::Refused("the edit is too large".into()))?;
185        doc.splice_text(obj, start, removed, &insert)?;
186        mark_authored(doc, obj, start, &insert)?;
187        Ok(())
188    }
189}
190
191impl tilo_actions::Action for TextEdit {
192    /// A record's own text, created by the first edit.
193    fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
194        let obj = match PlainText::root_text(doc) {
195            Some(obj) => obj,
196            None => doc.put_object(ROOT, TEXT_KEY, ObjType::Text)?,
197        };
198        self.apply_under(doc, &obj)
199    }
200}
201
202impl Resource for PlainText {
203    const KIND: &'static str = "tilo.text";
204    const LABEL: &'static str = "Text";
205    const ACTION_TYPE: &'static str = TEXT_ACTION_TYPE;
206
207    type State = String;
208    type Action = TextEdit;
209
210    fn read(doc: &Doc) -> Result<String, ModelError> {
211        PlainText::root_text(doc)
212            .map_or_else(|| Ok(String::new()), |obj| Self::read_under(doc, &obj))
213    }
214
215    fn initialize(doc: &mut Doc) -> Result<(), ModelError> {
216        if PlainText::root_text(doc).is_none() {
217            doc.put_object(ROOT, TEXT_KEY, ObjType::Text)
218                .map_err(|error| ModelError::invalid(error.to_string()))?;
219        }
220        Ok(())
221    }
222
223    /// Typing a word is one undo step: an insertion right where the last one
224    /// ended continues it until a space ends the word, and deleting runs the
225    /// same way, backwards (Backspace) or forwards (Delete).
226    fn coalesces(previous: &TextEdit, next: &TextEdit) -> bool {
227        let (
228            TextEdit::Splice {
229                at: before_at,
230                delete: before_delete,
231                insert: before_insert,
232            },
233            TextEdit::Splice { at, delete, insert },
234        ) = (previous, next)
235        else {
236            return false;
237        };
238        match (
239            *before_delete,
240            *delete,
241            before_insert.is_empty(),
242            insert.is_empty(),
243        ) {
244            (0, 0, false, false) => {
245                *at == before_at.saturating_add(before_insert.chars().count())
246                    && !before_insert.ends_with(char::is_whitespace)
247            }
248            (1.., 1.., true, true) => at.saturating_add(*delete) == *before_at || at == before_at,
249            _ => false,
250        }
251    }
252
253    fn declarations() -> Vec<ActionDecl<Self>> {
254        vec![
255            ActionDecl::new(
256                "replace-text",
257                "Replace text",
258                vec![ActionParam::required(
259                    "text",
260                    ParamType::Text,
261                    "The whole new text",
262                )],
263                |args, _| {
264                    Ok(TextEdit::ReplaceText {
265                        text: args.text("text").unwrap_or_default().to_owned(),
266                    })
267                },
268            )
269            .describe("Replace the whole text; only what differs is written."),
270        ]
271    }
272
273    fn action_schema() -> Option<serde_json::Value> {
274        Some(serde_json::json!({
275            "oneOf": [
276                {
277                    "type": "object",
278                    "description": "Replace `delete` characters at `at` with `insert`",
279                    "properties": {
280                        "action": {"const": "splice"},
281                        "at": {"type": "integer", "minimum": 0},
282                        "delete": {"type": "integer", "minimum": 0},
283                        "insert": {"type": "string"}
284                    },
285                    "required": ["action", "at", "delete", "insert"],
286                    "additionalProperties": false
287                },
288                {
289                    "type": "object",
290                    "description": "Replace the whole text",
291                    "properties": {
292                        "action": {"const": "replace-text"},
293                        "text": {"type": "string"}
294                    },
295                    "required": ["action", "text"],
296                    "additionalProperties": false
297                }
298            ]
299        }))
300    }
301
302    fn search(state: &String) -> Vec<SearchEntry> {
303        let title = state.lines().next().unwrap_or_default().trim();
304        if title.is_empty() {
305            return Vec::new();
306        }
307        vec![SearchEntry::new(title, state.clone())]
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314    use crate::Replica;
315    use tilo_automerge::ApplyIncoming;
316
317    fn spliced(text: &str, edit: &TextEdit) -> String {
318        let mut doc = Doc::new();
319        let obj = doc.put_object(ROOT, "body", ObjType::Text).unwrap();
320        doc.splice_text(&obj, 0, 0, text).unwrap();
321        edit.apply_under(&mut doc, &obj).unwrap();
322        doc.text(&obj).unwrap()
323    }
324
325    tilo_test_env::scenario! {
326        fn text_is_spliced_by_character_and_merges_concurrent_typing;
327
328        phase each_authors_typing_is_marked_with_its_author;
329        {
330            use automerge::marks::Mark;
331            let typed_by = |doc: &mut Doc, who: &str, edit: TextEdit| {
332                let encoded = tilo_actions::EncodedAction::encode(TEXT_ACTION_TYPE, &edit).unwrap();
333                let context = tilo_actions::ActionContext::for_resource("text", "tilo.text", "Text")
334                    .with_invoker(tilo_actions::ActionInvoker::person(who));
335                tilo_actions::apply_local_with_context(doc, &edit, encoded, None, context).unwrap();
336            };
337            let mut doc = Doc::new();
338            typed_by(
339                &mut doc,
340                "alice",
341                TextEdit::Splice {
342                    at: 0,
343                    delete: 0,
344                    insert: "héllo".into(),
345                },
346            );
347            typed_by(
348                &mut doc,
349                "bob",
350                TextEdit::Splice {
351                    at: 5,
352                    delete: 0,
353                    insert: " wörld".into(),
354                },
355            );
356            let obj = PlainText::root_text(&doc).unwrap();
357            let text = doc.text(&obj).unwrap();
358            assert_eq!(text, "héllo wörld");
359            let runs: Vec<(String, String)> = doc
360                .marks(&obj)
361                .unwrap()
362                .into_iter()
363                .filter(|mark: &Mark| mark.name() == AUTHOR_MARK)
364                .map(|mark| {
365                    let run: String = text
366                        .chars()
367                        .skip(mark.start)
368                        .take(mark.end.saturating_sub(mark.start))
369                        .collect();
370                    (mark.value().as_str().unwrap_or_default().to_owned(), run)
371                })
372                .collect();
373            assert_eq!(
374                runs,
375                vec![
376                    ("alice".to_owned(), "héllo".to_owned()),
377                    ("bob".to_owned(), " wörld".to_owned()),
378                ],
379                "each person's typing carries the actor their changes are named by"
380            );
381
382            let mut plain = Doc::new();
383            let obj = plain.put_object(ROOT, "body", ObjType::Text).unwrap();
384            TextEdit::Splice {
385                at: 0,
386                delete: 0,
387                insert: "x".into(),
388            }
389            .apply_under(&mut plain, &obj)
390            .unwrap();
391            assert!(plain.marks(&obj).unwrap().is_empty());
392        }
393
394        phase a_text_made_whole_is_marked_as_a_store_marks_it;
395        {
396            use crate::model::{Fresh, Model};
397            let _writer = crate::action::ResourceActorScope::enter(
398                tilo_action_policy::MemberId::agent("helper", "ada"),
399            );
400            let actor = automerge::ActorId::from(b"writer".as_slice());
401            for text in ["", "héllo wörld"] {
402                let mut made = Doc::new().with_actor(actor.clone());
403                let Fresh::Value(value) = text.to_owned().fresh(made.text_encoding()) else {
404                    panic!("a text is made with its map");
405                };
406                made.batch_create_object(ROOT, "title", &value, false)
407                    .unwrap();
408                // As a store writes it: the text, then its writer's mark.
409                let mut stored = Doc::new().with_actor(actor.clone());
410                let obj = stored.put_object(ROOT, "title", ObjType::Text).unwrap();
411                stored.splice_text(&obj, 0, 0, text).unwrap();
412                mark_authored(&mut stored, &obj, 0, text).unwrap();
413                assert_eq!(
414                    stored.marks(&obj).unwrap().len(),
415                    usize::from(!text.is_empty()),
416                    "{text:?} is the helper's"
417                );
418                assert_eq!(made.save(), stored.save(), "{text:?}");
419            }
420        }
421
422        phase a_copied_text_keeps_its_words_and_its_marks;
423        {
424            use automerge::marks::{ExpandMark, Mark};
425            let mut doc = Doc::new();
426            let from = doc.put_object(ROOT, "from", ObjType::Text).unwrap();
427            doc.splice_text(&from, 0, 0, "hello world").unwrap();
428            doc.mark(
429                &from,
430                Mark::new("strong".to_owned(), true, 0, 5),
431                ExpandMark::After,
432            )
433            .unwrap();
434            let into = doc.put_object(ROOT, "into", ObjType::Text).unwrap();
435            copy_whole(&mut doc, &from, &into).unwrap();
436            assert_eq!(doc.text(&into).unwrap(), "hello world");
437            let marks: Vec<(String, usize, usize)> = doc
438                .marks(&into)
439                .unwrap()
440                .into_iter()
441                .map(|mark| (mark.name().to_owned(), mark.start, mark.end))
442                .collect();
443            assert_eq!(marks, vec![("strong".to_owned(), 0, 5)]);
444        }
445
446        phase a_splice_counts_characters_not_bytes;
447        {
448            let edit = TextEdit::Splice {
449                at: 2,
450                delete: 1,
451                insert: "ö".into(),
452            };
453            assert_eq!(spliced("naïve", &edit), "naöve");
454        }
455
456        phase a_splice_past_the_end_is_refused_and_writes_nothing;
457        {
458            let mut doc = Doc::new();
459            let obj = doc.put_object(ROOT, "body", ObjType::Text).unwrap();
460            doc.splice_text(&obj, 0, 0, "abc").unwrap();
461            let edit = TextEdit::Splice {
462                at: 2,
463                delete: 5,
464                insert: String::new(),
465            };
466            assert!(matches!(
467                edit.apply_under(&mut doc, &obj),
468                Err(ActionError::Refused(_))
469            ));
470            assert_eq!(doc.text(&obj).unwrap(), "abc");
471        }
472
473        phase replacing_the_text_keeps_a_members_concurrent_typing;
474        {
475            let mut ours = Doc::new();
476            let obj = ours.put_object(ROOT, "body", ObjType::Text).unwrap();
477            ours.splice_text(&obj, 0, 0, "select 1").unwrap();
478            let mut theirs = ours.fork();
479            theirs.splice_text(&obj, 8, 0, ";").unwrap();
480            TextEdit::ReplaceText {
481                text: "SELECT 1".into(),
482            }
483            .apply_under(&mut ours, &obj)
484            .unwrap();
485            ours.merge_incoming(&mut theirs).unwrap();
486            assert_eq!(ours.text(&obj).unwrap(), "SELECT 1;");
487        }
488
489        phase the_smallest_splice_keeps_what_both_texts_share;
490        {
491            assert_eq!(
492                splice_between("hello world", "hello brave world"),
493                Some(TextEdit::Splice {
494                    at: 6,
495                    delete: 0,
496                    insert: "brave ".into()
497                })
498            );
499            assert_eq!(
500                splice_between("aaa", "aa"),
501                Some(TextEdit::Splice {
502                    at: 2,
503                    delete: 1,
504                    insert: String::new()
505                })
506            );
507            assert_eq!(splice_between("same", "same"), None);
508        }
509
510        phase byte_ends_land_where_character_ends_do;
511        {
512            let atoms = [
513                "", "a", "é", "e\u{301}", "😀", "😁", "\u{100}", "\u{101}", "\n",
514            ];
515            for a in atoms {
516                for b in atoms {
517                    for c in atoms {
518                        for d in atoms {
519                            let (left, right) = (format!("{a}{b}{c}"), format!("{a}{d}{c}"));
520                            let chars = |text: &str| text.chars().collect::<Vec<_>>();
521                            let (prefix, suffix) = common_ends(&chars(&left), &chars(&right));
522                            let (start, end) = common_text_ends(&left, &right);
523                            let (head, _) = left.split_at(start);
524                            let (_, tail) = left.split_at(left.len().saturating_sub(end));
525                            assert_eq!(
526                                (head.chars().count(), tail.chars().count()),
527                                (prefix, suffix),
528                                "{left:?} -> {right:?}"
529                            );
530                        }
531                    }
532                }
533            }
534        }
535
536        phase typing_a_word_coalesces_until_a_space;
537        {
538            let typed = |at: usize, insert: &str| TextEdit::Splice {
539                at,
540                delete: 0,
541                insert: insert.into(),
542            };
543            assert!(PlainText::coalesces(&typed(0, "h"), &typed(1, "i")));
544            assert!(!PlainText::coalesces(&typed(0, "h"), &typed(3, "i")));
545            assert!(!PlainText::coalesces(&typed(0, " "), &typed(1, "i")));
546            let deleted = |at: usize| TextEdit::Splice {
547                at,
548                delete: 1,
549                insert: String::new(),
550            };
551            assert!(PlainText::coalesces(&deleted(4), &deleted(3)));
552            assert!(!PlainText::coalesces(&typed(4, "x"), &deleted(4)));
553        }
554
555        phase a_record_of_its_own_text_replays_its_edits;
556        {
557            let mut replica = Replica::<PlainText>::new().in_app("so.tilo.model", "Model");
558            replica
559                .apply(
560                    crate::Invoke::<PlainText>::apply(&TextEdit::Splice {
561                        at: 0,
562                        delete: 0,
563                        insert: "draft".into(),
564                    })
565                    .unwrap(),
566                )
567                .unwrap();
568            assert_eq!(replica.state().unwrap().as_str(), "draft");
569        }
570    }
571}