-
Notifications
You must be signed in to change notification settings - Fork 11
/
TextPrompt.ts
56 lines (52 loc) · 1.79 KB
/
TextPrompt.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
import { Reducer } from 'redux';
import { produce } from 'immer';
// == state ========================================================================================
export interface State {
isVisible: boolean;
position: { x: number; y: number };
text: string;
placeholder: string;
checkValid?: ( ( text: string ) => string | null ) | null;
callback?: ( ( text: string ) => void ) | null;
}
export const initialState: Readonly<State> = {
isVisible: false,
position: { x: 0, y: 0 },
text: '',
placeholder: ''
};
// == action =======================================================================================
export type Action = {
type: 'TextPrompt/Open';
position: { x: number; y: number };
defaultText?: string;
placeholder?: string;
checkValid?: ( ( text: string ) => string | null );
callback: ( ( text: string ) => void );
} | {
type: 'TextPrompt/SetText';
text: string;
} | {
type: 'TextPrompt/Close';
};
// == reducer ======================================================================================
export const reducer: Reducer<State, Action> = ( state = initialState, action ) => {
return produce( state, ( newState: State ) => {
if ( action.type === 'TextPrompt/Open' ) {
newState.isVisible = true;
newState.position = action.position;
newState.text = action.defaultText || '';
newState.placeholder = action.placeholder || '';
newState.checkValid = action.checkValid;
newState.callback = action.callback;
} else if ( action.type === 'TextPrompt/SetText' ) {
newState.text = action.text;
} else if ( action.type === 'TextPrompt/Close' ) {
newState.isVisible = false;
newState.text = '';
newState.placeholder = '';
newState.checkValid = null;
newState.callback = null;
}
} );
};