json-joy
Version:
Collection of libraries for building collaborative editing apps.
61 lines • 1.65 kB
JavaScript
import { JsonPatch } from './JsonPatch';
import { toPath } from '@jsonjoy.com/json-pointer/lib/util';
export class JsonPatchStore {
model;
path;
base;
patcher;
pfx;
constructor(model, path = [], base) {
this.model = model;
this.path = path;
this.base = base;
this.pfx = path.length ? path.join() : '';
const api = model.api;
this.patcher = new JsonPatch(model, path, base);
this.subscribe = (listener) => api.onChange.listen(listener);
}
update = (change) => {
const ops = Array.isArray(change) ? change : [change];
this.patcher.apply(ops);
};
add = (path, value) => {
const op = { op: 'add', path, value };
this.update([op]);
return op;
};
replace = (path, value) => {
const op = { op: 'replace', path, value };
this.update([op]);
return op;
};
remove = (path) => {
const op = { op: 'remove', path };
this.update([op]);
return op;
};
del = (path) => {
try {
return this.remove(path);
}
catch {
return;
}
};
get = (path = '') => this.patcher.get(path);
bind(path) {
return new JsonPatchStore(this.model, this.path.concat(toPath(path)), this.base);
}
api() {
try {
return this.model.api.find(this.path);
}
catch {
return;
}
}
// ---------------------------------------------------------------- SyncStore
subscribe;
getSnapshot = () => this.get();
}
//# sourceMappingURL=JsonPatchStore.js.map