diff --git a/src/history/factory.ts b/src/history/factory.ts index f818546456..5d7fc252a2 100644 --- a/src/history/factory.ts +++ b/src/history/factory.ts @@ -59,9 +59,9 @@ function revertChanges(revisions: readonly Revision[]) { * Apply the changes of the given HistoryChange to the state */ function applyChange(change: HistoryChange, target: "before" | "after") { - let val = change.root as any; - let key = change.path[change.path.length - 1]; - for (let pathIndex = 0; pathIndex < change.path.slice(0, -1).length; pathIndex++) { + let val = change.path[0]; + const key = change.path[change.path.length - 1]; + for (let pathIndex = 1; pathIndex < change.path.slice(0, -1).length; pathIndex++) { const p = change.path[pathIndex]; if (val[p] === undefined) { const nextPath = change.path[pathIndex + 1]; diff --git a/src/state_observer.ts b/src/state_observer.ts index b049830de9..9eb86bf91d 100644 --- a/src/state_observer.ts +++ b/src/state_observer.ts @@ -20,15 +20,16 @@ export class StateObserver { this.commands.push(command); } - addChange(...args: any[]) { + addChange(...args: [...HistoryChange["path"], any]) { const val: any = args.pop(); - const [root, ...path] = args as [any, string | number]; + const root = args[0]; let value = root as any; - let key = path[path.length - 1]; - for (let pathIndex = 0; pathIndex <= path.length - 2; pathIndex++) { - const p = path[pathIndex]; + let key = args[args.length - 1]; + const pathLength = args.length - 2; + for (let pathIndex = 1; pathIndex <= pathLength; pathIndex++) { + const p = args[pathIndex]; if (value[p] === undefined) { - const nextPath = path[pathIndex + 1]; + const nextPath = args[pathIndex + 1]; value[p] = createEmptyStructure(nextPath); } value = value[p]; @@ -37,8 +38,7 @@ export class StateObserver { return; } this.changes.push({ - root, - path, + path: args, before: value[key], after: val, }); diff --git a/src/types/history.ts b/src/types/history.ts index 591b7a0780..d66b235a6b 100644 --- a/src/types/history.ts +++ b/src/types/history.ts @@ -9,8 +9,7 @@ export interface CreateRevisionOptions { } export interface HistoryChange { - root: any; - path: (string | number)[]; + path: [any, ...(number | string)[]]; before: any; after: any; } diff --git a/tests/plugins/history.test.ts b/tests/plugins/history.test.ts index 30f35a399f..9e565159b0 100644 --- a/tests/plugins/history.test.ts +++ b/tests/plugins/history.test.ts @@ -145,6 +145,7 @@ describe("history", () => { A: {}, }; expect(() => { + // @ts-expect-error history.addChange(state, "A", "B", true, 5); }).toThrow(); }); @@ -155,6 +156,7 @@ describe("history", () => { A: {}, }; expect(() => { + // @ts-expect-error history.addChange(state, "A", "B", true, "C", 5); }).toThrow(); });