Skip to content

Commit

Permalink
refactor: optimization of state codes
Browse files Browse the repository at this point in the history
  • Loading branch information
Jocs committed Feb 17, 2024
1 parent cd2c250 commit daf8ea2
Showing 1 changed file with 30 additions and 25 deletions.
55 changes: 30 additions & 25 deletions packages/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ class JSONState {
return json1.type.transform(op, otherOp, type);
}

public operationCache: JSONOpList[] = [];
private isGoing: boolean = false;
private _operationCache: JSONOpList[] = [];

private _isGoing = false;

private state: TState[] = [];

constructor(public muya: Muya, stateOrMarkdown: TState[] | string) {
Expand Down Expand Up @@ -75,15 +77,15 @@ class JSONState {
insertOperation(path: Path, state: TState) {
const operation = json1.insertOp(path, state as unknown as Doc)!;

this.operationCache.push(operation);
this._operationCache.push(operation);

this._emitStateChange();
}

removeOperation(path: Path) {
const operation = json1.removeOp(path)!;

this.operationCache.push(operation);
this._operationCache.push(operation);

this._emitStateChange();
}
Expand All @@ -92,38 +94,19 @@ class JSONState {
editOperation(path: Path, diff: TDiff[]) {
const operation = json1.editOp(path, 'text-unicode', diff)!;

this.operationCache.push(operation);
this._operationCache.push(operation);

this._emitStateChange();
}

replaceOperation(path: Path, oldValue: Doc, newValue: Doc) {
const operation = json1.replaceOp(path, oldValue, newValue)!;

this.operationCache.push(operation);
this._operationCache.push(operation);

this._emitStateChange();
}

private _emitStateChange() {
if (!this.isGoing) {
this.isGoing = true;
requestAnimationFrame(() => {
const op = this.operationCache.reduce(json1.type.compose);
this.apply(op);
// TODO: remove doc in future
const doc = this.getState();
this.muya.eventCenter.emit('json-change', {
op,
source: 'user',
doc,
});
this.operationCache = [];
this.isGoing = false;
});
}
}

dispatch(op: JSONOpList, source = 'user' /* user, api */) {
this.apply(op);
// TODO: remove doc in future
Expand All @@ -146,6 +129,28 @@ class JSONState {

return mdGenerator.generate(state);
}

private _emitStateChange() {
if (this._isGoing) {
return;
}

this._isGoing = true;

requestAnimationFrame(() => {
const op = this._operationCache.reduce(json1.type.compose);
this.apply(op);
// TODO: remove doc in future
const doc = this.getState();
this.muya.eventCenter.emit('json-change', {
op,
source: 'user',
doc,
});
this._operationCache = [];
this._isGoing = false;
});
}
}

export default JSONState;

0 comments on commit daf8ea2

Please sign in to comment.