json-joy
Version:
Collection of libraries for building collaborative editing apps.
66 lines (65 loc) • 2.11 kB
JavaScript
import { WebUndo } from './WebUndo';
import { printTree } from 'tree-dump';
export class AnnalsController {
opts;
manager = new WebUndo();
constructor(opts) {
this.opts = opts;
}
captured = new WeakSet();
/** ------------------------------------------------- {@link UndoCollector} */
capture() {
const currentPatch = this.opts.txt.model.api.builder.patch;
this.captured.add(currentPatch);
}
undo() {
this.manager.undo();
}
redo() {
this.manager.redo();
}
/** -------------------------------------------------- {@link UiLifeCycles} */
start() {
const stopManager = this.manager.start();
const { opts, captured } = this;
const { txt } = opts;
txt.model.api.onFlush.listen((patch) => {
const isCaptured = captured.has(patch);
if (isCaptured) {
captured.delete(patch);
const item = [patch, this._undo];
this.manager.push(item);
}
});
return () => {
stopManager();
};
}
_undo = (doPatch) => {
const { log, et } = this.opts;
const patch = log.undo(doPatch);
et.dispatch('annals', {
action: 'undo',
batch: [patch],
});
// console.log('doPatch', doPatch + '');
// console.log('undoPatch', patch + '');
return [doPatch, this._redo];
};
_redo = (doPatch) => {
const { log, et } = this.opts;
const redoPatch = doPatch.rebase(log.end.clock.time);
et.dispatch('annals', {
action: 'redo',
batch: [redoPatch],
});
// console.log('doPatch', doPatch + '');
// console.log('redoPatch', redoPatch + '');
return [redoPatch, this._undo];
};
/** ----------------------------------------------------- {@link Printable} */
toString(tab) {
return ('annals' +
printTree(tab, [(tab) => 'undo: ' + this.manager.uStack.length, (tab) => 'redo: ' + this.manager.rStack.length]));
}
}