json-joy
Version:
Collection of libraries for building collaborative editing apps.
57 lines (56 loc) • 1.74 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonPatchStore = void 0;
const JsonPatch_1 = require("./JsonPatch");
const util_1 = require("@jsonjoy.com/json-pointer/lib/util");
class JsonPatchStore {
constructor(model, path = []) {
this.model = model;
this.path = path;
this.update = (change) => {
const ops = Array.isArray(change) ? change : [change];
this.patcher.apply(ops);
};
this.add = (path, value) => {
const op = { op: 'add', path, value };
this.update([op]);
return op;
};
this.replace = (path, value) => {
const op = { op: 'replace', path, value };
this.update([op]);
return op;
};
this.remove = (path) => {
const op = { op: 'remove', path };
this.update([op]);
return op;
};
this.del = (path) => {
try {
return this.remove(path);
}
catch {
return;
}
};
this.get = (path = '') => this.patcher.get(path);
this.getSnapshot = () => this.get();
this.pfx = path.length ? path.join() : '';
const api = model.api;
this.patcher = new JsonPatch_1.JsonPatch(model, path);
this.subscribe = (listener) => api.onChange.listen(listener);
}
bind(path) {
return new JsonPatchStore(this.model, this.path.concat((0, util_1.toPath)(path)));
}
api() {
try {
return this.model.api.find(this.path);
}
catch {
return;
}
}
}
exports.JsonPatchStore = JsonPatchStore;