Skip to content

Commit

Permalink
fix(undo): adding initial state in historyAtom (#828)
Browse files Browse the repository at this point in the history
* fix: adding initial state in historyAtom

* refactor: fix without modify AtomProto

* refactor: comma
  • Loading branch information
DmitriyBadeev authored Apr 28, 2024
1 parent c22b042 commit 4006e44
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 12 additions & 0 deletions packages/undo/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ test('withUndo', async () => {
;('👍') //?
})

test('withUndo without getting historyAtom before first change', async () => {
const a = atom(0).pipe(withUndo({ length: 5 }))
const ctx = createTestCtx()

a(ctx, 1)
assert.is(ctx.get(a), 1)
assert.is(ctx.get(a.isUndoAtom), true)
assert.is(ctx.get(a.isRedoAtom), false)
assert.equal(ctx.get(a.historyAtom), [0, 1])
;('👍') //?
})

test('limit', () => {
const a = atom(0).pipe(withUndo({ length: 5 }))
const ctx = createTestCtx()
Expand Down
12 changes: 10 additions & 2 deletions packages/undo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,18 @@ export const withUndo =
if (!anAtom.undo) {
const { name } = anAtom.__reatom

const historyAtom = (anAtom.historyAtom = atom<Array<AtomState<T>>>(
const historyAtom = anAtom.historyAtom = atom<Array<AtomState<T>>>(
[],
`${name}.Undo._historyAtom`,
).pipe(withInit((ctx) => [ctx.get(anAtom)])))
)

anAtom.pipe(
withInit((ctx, init) => {
const state = init(ctx)
historyAtom(ctx, [state])
return state
}),
)

const positionAtom = (anAtom.positionAtom = atom(0, `${name}._position`))

Expand Down

0 comments on commit 4006e44

Please sign in to comment.