useHistory.ts 915 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { History } from 'stateshot'
  2. import {reactive, Ref, ref} from "vue";
  3. export const useHistory = <T>(initialState: T) => {
  4. const history = new History<T>({ initialState })
  5. const value = ref({...initialState}) as Ref<T>
  6. const state = ref({
  7. hasUndo: false,
  8. hasRedo: false
  9. })
  10. const setHistoryState = () => {
  11. state.value.hasUndo = history.hasUndo
  12. state.value.hasRedo = history.hasRedo
  13. }
  14. const undo = () => {
  15. history.undo()
  16. setHistoryState()
  17. value.value = history.get()
  18. }
  19. const redo = () => {
  20. history.redo()
  21. setHistoryState()
  22. value.value = history.get()
  23. }
  24. const push = () => {
  25. const pushStateStr = JSON.stringify(value.value)
  26. if (pushStateStr !== JSON.stringify(history.get())) {
  27. history.pushSync(JSON.parse(pushStateStr))
  28. setHistoryState()
  29. }
  30. }
  31. return reactive({
  32. push,
  33. redo,
  34. undo,
  35. value,
  36. state
  37. })
  38. }