index.ts 1.8 KB
Newer Older
1
import { defineStore } from 'pinia'
L
LeoKu 已提交
2 3

import { WrapperShape } from '@/enums'
L
LeoKu 已提交
4
import type { AvatarOption } from '@/types'
L
LeoKu 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
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
}

24 25 26 27 28 29 30 31 32 33 34 35 36 37
export const useStore = defineStore('store', {
  state: () =>
    ({
      history: {
        past: [],
        present: getRandomAvatarOption({ wrapperShape: WrapperShape.Squircle }),
        future: [],
      },
      isSiderCollapsed: window.innerWidth <= SCREEN.lg,
    } as State),
  actions: {
    [SET_AVATAR_OPTION](data: AvatarOption) {
      this.history = {
        past: [...this.history.past, this.history.present],
L
LeoKu 已提交
38 39 40 41 42
        present: data,
        future: [],
      }
    },

43 44 45 46 47
    [UNDO]() {
      if (this.history.past.length > 0) {
        const previous = this.history.past[this.history.past.length - 1]
        const newPast = this.history.past.slice(0, this.history.past.length - 1)
        this.history = {
L
LeoKu 已提交
48 49
          past: newPast,
          present: previous,
50
          future: [this.history.present, ...this.history.future],
L
LeoKu 已提交
51 52 53 54
        }
      }
    },

55 56 57 58 59 60
    [REDO]() {
      if (this.history.future.length > 0) {
        const next = this.history.future[0]
        const newFuture = this.history.future.slice(1)
        this.history = {
          past: [...this.history.past, this.history.present],
L
LeoKu 已提交
61 62 63 64 65 66
          present: next,
          future: newFuture,
        }
      }
    },

67 68 69
    [SET_SIDER_STATUS](collapsed: boolean) {
      if (collapsed !== this.isSiderCollapsed) {
        this.isSiderCollapsed = collapsed
L
LeoKu 已提交
70 71 72 73
      }
    },
  },
})