import { createSlice, createAsyncThunk } from '@reduxjs/toolkit' import { getBoardById, setBoard, addBoard } from 'api' import type { BoardData } from 'api' import type { StoreState } from 'store' export * from 'api/board' export { BoardType, BoardTypeDesc } from 'api' export interface BoardState { list: BoardData[] currentIndex: number } const initialState: BoardState = { list: [{ shapes: [], id: -1, bgImage: null }], currentIndex: 0 } const replaceState = (state: BoardState, { payload }: { payload: BoardData }) => { state.list = [payload] state.currentIndex = 0 } const pushState = (state: BoardState, { payload }: { payload: BoardData }) => { const current = state.list[state.currentIndex] const newList = state.list.slice(0, state.currentIndex + 1) newList.push({ ...payload, id: current.id, }) state.list = newList state.currentIndex += 1 } const boardSlice = createSlice({ name: 'board', initialState, reducers: { forward(state, { payload = 1 }: { payload: number }) { let move = state.currentIndex + payload state.currentIndex = move > state.list.length - 1 ? state.list.length - 1 : move console.log('forward') }, backoff(state, { payload = 1 }: { payload: number }) { let move = state.currentIndex - payload state.currentIndex = move < 0 ? 0 : move return state }, push: pushState, replace: replaceState, destory(state) { replaceState(state, { payload: initialState.list[0] }) } }, extraReducers(builder) { builder .addCase(insertBoard.fulfilled, (state, action) => { const current = state.list[state.currentIndex] state.list = state.list.map(data => ({ ...data, bgImage: data.bgImage === current.bgImage ? action.payload.bgImage : data.bgImage, id: action.payload.id })) }) .addCase(fetchBoard.fulfilled, replaceState) } }) export const boardName = boardSlice.name export const boardReducer = boardSlice.reducer export const currentBoard = (state: StoreState) => state.board.list[state.board.currentIndex] export const boardStatus = (state: StoreState) => { const len = state.board.list.length const index = state.board.currentIndex return { canBack: index !== 0, canForward: index < len - 1, top: index === len - 1 } } export const copyBoard = (boardData: BoardData): BoardData => { return JSON.parse(JSON.stringify(boardData)) } export const fetchBoard = createAsyncThunk('fetch/board', getBoardById) export const insertBoard = createAsyncThunk('insert/board', addBoard) export const updateBoard = createAsyncThunk('update/board', setBoard)