json-joy
Version:
Collection of libraries for building collaborative editing apps.
82 lines (81 loc) • 2.6 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpStrDel = void 0;
const AbstractOp_1 = require("./AbstractOp");
const json_pointer_1 = require("@jsonjoy.com/json-pointer");
const constants_1 = require("../constants");
/**
* @category JSON Patch Extended
*/
class OpStrDel extends AbstractOp_1.AbstractOp {
constructor(path, pos, str, len) {
super(path);
this.pos = pos;
this.str = str;
this.len = len;
}
op() {
return 'str_del';
}
code() {
return constants_1.OPCODE.str_del;
}
deleteLength() {
return typeof this.str === 'string' ? this.str.length : this.len;
}
apply(doc) {
const { val, key, obj } = (0, json_pointer_1.find)(doc, this.path);
if (typeof val !== 'string')
throw new Error('NOT_A_STRING');
const length = val.length;
const pos = Math.min(this.pos, val.length);
const start = Math.min(pos, length);
const deletionLength = this.str !== undefined ? this.str.length : this.len;
const end = Math.min(pos + deletionLength, length);
const before = val.slice(0, start);
const after = val.substr(end);
const result = before + after;
if (obj)
obj[key] = result;
else
doc = result;
return { doc, old: val };
}
toJson(parent) {
if (typeof this.str === 'string') {
return {
op: 'str_del',
path: (0, json_pointer_1.formatJsonPointer)(this.path),
pos: this.pos,
str: this.str,
};
}
return {
op: 'str_del',
path: (0, json_pointer_1.formatJsonPointer)(this.path),
pos: this.pos,
len: this.len,
};
}
toCompact(parent, verbose) {
const opcode = verbose ? 'str_del' : constants_1.OPCODE.str_del;
return typeof this.str === 'string'
? [opcode, this.path, this.pos, this.str]
: [opcode, this.path, this.pos, 0, this.len];
}
encode(encoder, parent) {
const hasStr = typeof this.str === 'string';
encoder.encodeArrayHeader(hasStr ? 4 : 5);
encoder.writer.u8(constants_1.OPCODE.str_del);
encoder.encodeArray(this.path);
encoder.encodeNumber(this.pos);
if (hasStr) {
encoder.encodeString(this.str);
}
else {
encoder.writer.u8(0);
encoder.encodeNumber(this.len);
}
}
}
exports.OpStrDel = OpStrDel;