index.ts 2.0 KB
Newer Older
L
LeoKu 已提交
1 2
import { type InjectionKey } from 'vue'
import { type Store, createStore, useStore as baseUseStore } from 'vuex'
L
LeoKu 已提交
3 4

import { WrapperShape } from '@/enums'
L
LeoKu 已提交
5
import { type AvatarOption } from '@/types'
L
LeoKu 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
import { getRandomAvatarOption } from '@/utils'
import { SCREEN } from '@/utils/constant'

import {
  REDO,
  SET_AVATAR_OPTION,
  SET_SIDER_STATUS,
  UNDO,
} from './mutation-type'

export interface State {
  history: {
    past: AvatarOption[]
    present: AvatarOption
    future: AvatarOption[]
  }
  isSiderCollapsed: boolean
}

export default createStore<State>({
  strict: true,

  state: {
    history: {
      past: [],
      present: getRandomAvatarOption({ wrapperShape: WrapperShape.Squircle }),
      future: [],
    },
    isSiderCollapsed: window.innerWidth <= SCREEN.lg,
  },

  mutations: {
    [SET_AVATAR_OPTION](state, data: AvatarOption) {
      state.history = {
        past: [...state.history.past, state.history.present],
        present: data,
        future: [],
      }
    },

    [UNDO](state) {
      if (state.history.past.length > 0) {
        const previous = state.history.past[state.history.past.length - 1]
        const newPast = state.history.past.slice(
          0,
          state.history.past.length - 1
        )
        state.history = {
          past: newPast,
          present: previous,
          future: [state.history.present, ...state.history.future],
        }
      }
    },

    [REDO](state) {
      if (state.history.future.length > 0) {
        const next = state.history.future[0]
        const newFuture = state.history.future.slice(1)
        state.history = {
          past: [...state.history.past, state.history.present],
          present: next,
          future: newFuture,
        }
      }
    },

    [SET_SIDER_STATUS](state, collapsed) {
      if (collapsed !== state.isSiderCollapsed) {
        state.isSiderCollapsed = collapsed
      }
    },
  },
})

export const storeKey: InjectionKey<Store<State>> = Symbol()

export function useStore() {
  return baseUseStore(storeKey)
}