collaborative-editor
Version:
JSON CRDT str node bindings to any generic plain text editor.
72 lines • 2.6 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MemoryEditor2 = exports.MemoryEditor1 = exports.MemoryEditor0 = void 0;
class MemoryEditor0 {
constructor() {
this.__str = '';
this.__cursorStart = -1;
this.__cursorEnd = -1;
this.__cursorDirection = 0;
this.__onchange = () => {
var _a;
(_a = this.onchange) === null || _a === void 0 ? void 0 : _a.call(this);
};
this.__onselection = () => {
var _a;
(_a = this.onselection) === null || _a === void 0 ? void 0 : _a.call(this);
};
}
get() {
return this.__str;
}
set(str) {
this.__str = str;
if (this.__cursorStart > 0)
this.__cursorStart = str.length;
if (this.__cursorEnd > 0)
this.__cursorEnd = str.length;
}
}
exports.MemoryEditor0 = MemoryEditor0;
class MemoryEditor1 extends MemoryEditor0 {
getLength() {
return this.__str.length;
}
set() {
throw new Error('.set() should not be needed');
}
ins(position, text) {
this.__str = this.__str.slice(0, position) + text + this.__str.slice(position);
if (this.__cursorStart > 0 && this.__cursorStart >= position)
this.__cursorStart += text.length;
if (this.__cursorEnd > 0 && this.__cursorEnd >= position)
this.__cursorEnd += text.length;
}
del(position, length) {
this.__str = this.__str.slice(0, position) + this.__str.slice(position + length);
if (this.__cursorStart > 0 && this.__cursorStart >= position)
this.__cursorStart -= Math.min(length, this.__cursorStart - position);
if (this.__cursorEnd > 0 && this.__cursorEnd >= position)
this.__cursorEnd -= Math.min(length, this.__cursorEnd - position);
}
}
exports.MemoryEditor1 = MemoryEditor1;
class MemoryEditor2 extends MemoryEditor1 {
getSelection() {
if (this.__cursorStart < 0)
return null;
if (this.__cursorEnd < 0)
return null;
return [this.__cursorStart, this.__cursorEnd, this.__cursorDirection];
}
setSelection(start, end, direction) {
const length = this.__str.length;
if (start > end)
[start, end] = [end, start];
this.__cursorStart = Math.max(0, Math.min(length, start));
this.__cursorEnd = Math.max(0, Math.min(length, end));
this.__cursorDirection = direction;
}
}
exports.MemoryEditor2 = MemoryEditor2;
//# sourceMappingURL=MemoryEditor.js.map