All files / src/entities/history/model slice.ts

94.73% Statements 18/19
62.5% Branches 5/8
83.33% Functions 5/6
94.11% Lines 16/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 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        33x           33x         1x       1x 1x       1x 1x     1x 1x     2x 2x 2x 2x               1x         33x 33x  
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
import type { HistoryEntry, HistoryState } from '@/shared/types';
import { NAMES } from '@/shared/constants';
 
const initialState: HistoryState = {
	stack: [],
	currentIndex: -1,
	isPreview: false,
};
 
const slice = createSlice({
	name: NAMES.HISTORY,
	initialState,
	reducers: {
		pushState(state, action: PayloadAction<HistoryEntry>) {
			state.stack = [
				...state.stack.slice(0, state.currentIndex + 1),
				action.payload,
			];
			state.currentIndex = state.stack.length - 1;
			state.isPreview = false;
		},
 
		undo(state) {
			Eif (state.currentIndex > 0) state.currentIndex--;
			state.isPreview = true;
		},
		redo(state) {
			Eif (state.currentIndex < state.stack.length - 1) state.currentIndex++;
			state.isPreview = true;
		},
		jumpTo(state, action: PayloadAction<number>) {
			const i = action.payload;
			Eif (i >= 0 && i < state.stack.length) {
				state.currentIndex = i;
				state.isPreview = true;
			}
		},
		setPreview(state, action: PayloadAction<boolean>) {
			state.isPreview = action.payload;
		},
 
		resetHistory() {
			return initialState;
		},
	},
});
 
export const { pushState, undo, redo, jumpTo, resetHistory, setPreview } = slice.actions;
export const historyReducer = slice.reducer;