Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: proxyWithHistory #181

Merged
merged 1 commit into from
Jul 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,21 @@ const state = proxyWithComputed({
})
```

#### `proxyWithHistory` util

This is a utility function to create a proxy with snapshot history.

```js
const state = proxyWithHistory({ count: 0 })
console.log(state.value) // ---> { count: 0 }
state.value.count += 1
console.log(state.value) // ---> { count: 1 }
state.undo()
console.log(state.value) // ---> { count: 0 }
state.redo()
console.log(state.value) // ---> { count: 1 }
```

#### Recipes

Valtio is unopinionated about organizing state.
Expand Down
68 changes: 67 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createProxy as createProxyToCompare, isChanged } from 'proxy-compare'
import { proxy, subscribe, snapshot } from './vanilla'
import { proxy, subscribe, snapshot, ref } from './vanilla'
import type { DeepResolveType } from './vanilla'

/**
Expand Down Expand Up @@ -357,3 +357,69 @@ export const watch = (callback: WatchCallback): (() => void) => {

return wrappedCleanup
}

/**
* proxyWithHistory
*
* This creates a new proxy with history support.
* It includes following properties:
* - value: any value (does not have to be an object)
* - history: an array holding the history of snapshots
* - historyIndex: the history index to the current snapshot
* - canUndo: a function to return true if undo is available
* - undo: a function to go back hisotry
* - canRedo: a function to return true if redo is available
* - redo: a function to go forward history
* - saveHistory: a function to save history
*
* [Notes]
* Suspense/promise is not supported.
*
* @example
* import { proxyWithHistory } from 'valtio/utils'
* const state = proxyWithHistory({
* count: 1,
* })
*/
export const proxyWithHistory = <V>(initialValue: V) => {
const proxyObject = proxy({
value: initialValue,
history: ref({
wip: initialValue, // to avoid infinite loop
snapshots: [] as V[],
index: -1,
}),
canUndo: () => proxyObject.history.index > 0,
undo: () => {
if (proxyObject.canUndo()) {
proxyObject.value = proxyObject.history.wip =
proxyObject.history.snapshots[--proxyObject.history.index]
}
},
canRedo: () =>
proxyObject.history.index < proxyObject.history.snapshots.length - 1,
redo: () => {
if (proxyObject.canRedo()) {
proxyObject.value = proxyObject.history.wip =
proxyObject.history.snapshots[++proxyObject.history.index]
}
},
saveHistory: () => {
proxyObject.history.snapshots.splice(proxyObject.history.index + 1)
proxyObject.history.snapshots.push(snapshot(proxyObject).value as V)
++proxyObject.history.index
},
})
subscribe(proxyObject, (ops) => {
if (
ops.some(
(op) =>
op[1][0] === 'value' &&
(op[0] !== 'set' || op[2] !== proxyObject.history.wip)
)
) {
proxyObject.saveHistory()
}
})
return proxyObject
}
94 changes: 94 additions & 0 deletions tests/history.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import React, { StrictMode } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { useSnapshot } from '../src/index'
import { proxyWithHistory } from '../src/utils'

it('simple count', async () => {
const state = proxyWithHistory(0)

const Counter: React.FC = () => {
const snap = useSnapshot(state)
return (
<>
<div>count: {snap.value}</div>
<button onClick={() => ++state.value}>inc</button>
<button onClick={snap.undo}>undo</button>
<button onClick={snap.redo}>redo</button>
</>
)
}

const { getByText, findByText } = render(
<StrictMode>
<Counter />
</StrictMode>
)

await findByText('count: 0')

fireEvent.click(getByText('inc'))
await findByText('count: 1')

fireEvent.click(getByText('inc'))
await findByText('count: 2')

fireEvent.click(getByText('inc'))
await findByText('count: 3')

fireEvent.click(getByText('undo'))
await findByText('count: 2')

fireEvent.click(getByText('redo'))
await findByText('count: 3')

fireEvent.click(getByText('undo'))
await findByText('count: 2')

fireEvent.click(getByText('undo'))
await findByText('count: 1')
})

it('count in object', async () => {
const state = proxyWithHistory({ count: 0 })

const Counter: React.FC = () => {
const snap = useSnapshot(state)
return (
<>
<div>count: {snap.value.count}</div>
<button onClick={() => ++state.value.count}>inc</button>
<button onClick={snap.undo}>undo</button>
<button onClick={snap.redo}>redo</button>
</>
)
}

const { getByText, findByText } = render(
<StrictMode>
<Counter />
</StrictMode>
)

await findByText('count: 0')

fireEvent.click(getByText('inc'))
await findByText('count: 1')

fireEvent.click(getByText('inc'))
await findByText('count: 2')

fireEvent.click(getByText('inc'))
await findByText('count: 3')

fireEvent.click(getByText('undo'))
await findByText('count: 2')

fireEvent.click(getByText('redo'))
await findByText('count: 3')

fireEvent.click(getByText('undo'))
await findByText('count: 2')

fireEvent.click(getByText('undo'))
await findByText('count: 1')
})