-
Notifications
You must be signed in to change notification settings - Fork 11
/
History.ts
60 lines (55 loc) · 1.68 KB
/
History.ts
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
52
53
54
55
56
57
58
59
60
import { HistoryCommand } from '../history/HistoryCommand';
import { Reducer } from 'redux';
import { produce } from 'immer';
// == state ========================================================================================
interface HistoryEntry {
commands: HistoryCommand[];
description: string;
}
export interface State {
entries: HistoryEntry[];
index: number;
cantUndoThis: number;
}
export const initialState: Readonly<State> = {
entries: [],
index: 0,
cantUndoThis: 0
};
// == action =======================================================================================
export type Action = {
type: 'History/Push';
commands: HistoryCommand[];
description: string;
} | {
type: 'History/Drop';
} | {
type: 'History/Undo';
} | {
type: 'History/Redo';
} | {
type: 'History/SetCantUndoThis';
cantUndoThis: number;
};
// == reducer ======================================================================================
export const reducer: Reducer<State, Action> = ( state = initialState, action ) => {
return produce( state, ( newState: State ) => {
if ( action.type === 'History/Push' ) {
newState.entries.splice( state.index );
newState.entries.push( {
commands: action.commands,
description: action.description
} );
newState.index ++;
} else if ( action.type === 'History/Drop' ) {
newState.entries.splice( 0 );
newState.index = 0;
} else if ( action.type === 'History/Undo' ) {
newState.index --;
} else if ( action.type === 'History/Redo' ) {
newState.index ++;
} else if ( action.type === 'History/SetCantUndoThis' ) {
newState.cantUndoThis = action.cantUndoThis;
}
} );
};