UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

59 lines (58 loc) 1.55 kB
import { JsonPatch } from './JsonPatch'; import { toPath } from '@jsonjoy.com/json-pointer/lib/util'; export class JsonPatchStore { model; path; patcher; pfx; constructor(model, path = []) { this.model = model; this.path = path; this.pfx = path.length ? path.join() : ''; const api = model.api; this.patcher = new JsonPatch(model, path); 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))); } api() { try { return this.model.api.find(this.path); } catch { return; } } // ---------------------------------------------------------------- SyncStore subscribe; getSnapshot = () => this.get(); }