UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

109 lines (108 loc) 2.63 kB
import { tick } from '../../../json-crdt-patch/clock'; import { AbstractRga } from '../rga/AbstractRga'; import { next } from 'sonic-forest/lib/util'; /** * @ignore * @category CRDT Node */ export class StrChunk { id; span; del; data; len; p; l; r; p2; l2; r2; s; constructor(id, span, str) { this.id = id; this.span = span; this.len = str ? span : 0; this.del = !str; this.p = undefined; this.l = undefined; this.r = undefined; this.p2 = undefined; this.l2 = undefined; this.r2 = undefined; this.s = undefined; this.data = str; } merge(str) { this.data += str; this.span = this.data.length; } split(ticks) { if (!this.del) { const chunk = new StrChunk(tick(this.id, ticks), this.span - ticks, this.data.slice(ticks)); this.data = this.data.slice(0, ticks); this.span = ticks; return chunk; } const chunk = new StrChunk(tick(this.id, ticks), this.span - ticks, ''); this.span = ticks; return chunk; } delete() { this.del = true; this.data = ''; } clone() { const chunk = new StrChunk(this.id, this.span, this.data); return chunk; } view() { return this.data; } } /** * Represents the `str` type in JSON CRDT. The `str` type is a RGA (Replicated * Growable Array) of UTF-16 code units. * * @category CRDT Node */ export class StrNode extends AbstractRga { // ----------------------------------------------------------------- JsonNode /** @ignore */ children() { } /** @ignore */ child() { return undefined; } /** @ignore */ container() { return undefined; } /** @ignore */ _view = ''; view() { if (this._view) return this._view; let str = ''; for (let chunk = this.first(); chunk; chunk = next(chunk)) // TODO: Check if this optimization improves performance: if (!chunk.del) str += chunk.data; str += chunk.data; return (this._view = str); } /** @ignore */ api = undefined; name() { return 'str'; } // -------------------------------------------------------------- AbstractRga /** @ignore */ createChunk(id, str) { return new StrChunk(id, str ? str.length : 0, str || ''); } /** @ignore */ onChange() { this._view = ''; } toStringName() { return this.name(); } }