143Build a collaborative rich-text editor with remote cursors and offline synchronization
Problem
The core of a collaborative editor is a data structure that lets several people edit the same text at the same time, even offline, and always end up with the same document. Implement a text CRDT (a Replicated Growable Array, RGA):
createReplica(siteId) returns:
insert(index, text): insert at a visible index; returns the operations to broadcast (one per character).delete(index, length): delete visible characters; returns the operations to broadcast.apply(ops): apply remote operations. Operations may arrive in any order, more than once, and later (after being offline). Applying must be idempotent, and an operation whose dependency has not arrived yet must wait until it does.getText(): the current visible text.anchorAt(index)andindexOf(anchor): a remote cursor's position that stays attached to the same place in the text as others edit before it.
Convergence: any replicas that have applied the same set of operations, in any order, have the same getText().
(Rich-text formatting is built on top of this as marks over character ranges; the follow-up questions discuss it.)
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Press Run or ⌘ Enter to execute your code.
Step-by-step
Use a Lamport clock: each replica keeps a counter; a local insert uses counter + 1; seeing a remote id with a higher counter moves the clock forward. An id is [counter, siteId], and ids are totally ordered by counter, then site id. No two characters ever share an id.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.