-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppContext.tsx
More file actions
251 lines (208 loc) · 5.57 KB
/
Copy pathAppContext.tsx
File metadata and controls
251 lines (208 loc) · 5.57 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import {
createContext,
Dispatch,
ReactNode,
useContext,
useEffect,
useReducer,
} from 'react';
import { SESSION_KEY } from './const/session';
import { getStorage } from './store/storage';
import { getInternalEventBus } from './helpers/internalEventBus';
import { InternalEvents } from './const/internalEvents';
import { EventBus } from './helpers/createComponent/EventBus';
import { UITagsEnum, ProviderFactory } from './lib/sdkDapp';
const AsyncStorage = getStorage();
export type AppStateType = {
isInitialized: boolean;
address?: string;
encrypted?: string | object;
registeredDAppComponents: Record<UITagsEnum, object>;
};
const initialState: AppStateType = {
isInitialized: false,
address: '',
encrypted: '',
registeredDAppComponents: {} as Record<UITagsEnum, object>,
};
type ActionMap<M extends { [index: string]: any }> = {
[Key in keyof M]: M[Key] extends undefined
? {
type: Key;
}
: {
type: Key;
} & M[Key]; // Explicitly constrain Key to string and intersect with M[Key]
};
enum ActionType {
INITIALIZED = 'INITIALIZED',
REGISTER_DAPP_COMPONENT = 'REGISTER_DAPP_COMPONENT',
UNREGISTER_DAPP_COMPONENT = 'UNREGISTER_DAPP_COMPONENT',
UPDATE_SESSION = 'UPDATE_SESSION',
GENERATE = 'GENERATE',
CLEAR = 'CLEAR',
}
type ActionPayloadType = {
[ActionType.INITIALIZED]: never;
[ActionType.REGISTER_DAPP_COMPONENT]: {
componentType: UITagsEnum;
componentProps: object;
};
[ActionType.UNREGISTER_DAPP_COMPONENT]: {
componentType: UITagsEnum;
};
[ActionType.UPDATE_SESSION]: AppStateType;
[ActionType.GENERATE]: {
address: string;
encrypted: string | object;
accessToken: string;
};
[ActionType.CLEAR]: never;
};
export type Actions =
ActionMap<ActionPayloadType>[keyof ActionMap<ActionPayloadType>];
type ContextType = {
state: AppStateType;
dispatch: Dispatch<Actions>;
};
const AppContext = createContext<ContextType>({
state: initialState,
dispatch: () => null,
});
export const reducer = (
state: AppStateType,
action: Actions,
): typeof initialState => {
switch (action.type) {
case ActionType.INITIALIZED: {
return {
...state,
isInitialized: true,
};
}
case ActionType.REGISTER_DAPP_COMPONENT: {
const { componentType, componentProps } = action;
state.registeredDAppComponents[componentType] = componentProps;
return {
...state,
};
}
case ActionType.UNREGISTER_DAPP_COMPONENT: {
const { componentType } = action;
delete state.registeredDAppComponents[componentType];
return {
...state,
};
}
case ActionType.UPDATE_SESSION: {
const { ...session } = action;
return {
...state,
...session,
};
}
case ActionType.GENERATE: {
const { address, encrypted } = action;
return {
...state,
address,
encrypted,
};
}
case ActionType.CLEAR: {
AsyncStorage.clear();
return initialState;
}
default: {
throw new Error(`unhandled type ${(action as { type: string }).type}`);
}
}
};
let isAppInitialized = false;
export const Provider = ({ children }: React.PropsWithChildren) => {
const [state, dispatch] = useReducer(reducer, {
...initialState,
});
const getCurrentSession = async () => {
const sessionData = await AsyncStorage.getItem(SESSION_KEY);
const session = sessionData ? JSON.parse(sessionData) : initialState;
dispatch({
type: ActionType.UPDATE_SESSION,
...session,
});
};
useEffect(() => {
getCurrentSession();
}, []);
useEffect(() => {
AsyncStorage.setItem(SESSION_KEY, JSON.stringify(state));
}, [state]);
const onLogin = async () => {
try {
const provider = await ProviderFactory.create({
type: 'RN_DAppProvider',
});
provider.login();
} catch (err) {
console.error('Provider logged in error:', err);
}
};
useEffect(() => {
if (!isAppInitialized) {
return;
}
if (state.address && state.encrypted) {
onLogin();
}
}, [state.address, state.encrypted, state.isInitialized]);
useEffect(() => {
const unsubscribeDappInit = getInternalEventBus().subscribe(
InternalEvents.DAPP_INITIALIZED,
() => {
isAppInitialized = true;
},
);
const unsubscribeRegister = getInternalEventBus().subscribe(
InternalEvents.COMPONENT_REGISTERED,
(msg: { type: UITagsEnum; component: ReactNode; eventBus: EventBus }) => {
const { type, component, eventBus } = msg;
dispatch({
type: ActionType.REGISTER_DAPP_COMPONENT,
componentType: type,
componentProps: {
component,
eventBus,
},
});
},
);
const unsubscribeUnregister = getInternalEventBus().subscribe(
InternalEvents.UNREGISTER_DAPP_COMPONENT,
(msg: { type: UITagsEnum }) => {
const { type } = msg;
dispatch({
type: ActionType.UNREGISTER_DAPP_COMPONENT,
componentType: type,
});
},
);
return () => {
unsubscribeDappInit();
unsubscribeRegister();
unsubscribeUnregister();
};
}, []);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
export const useAppProvider = () => {
const context = useContext(AppContext);
if (context == null) {
throw new Error('useProvider must be used within a Provider');
}
const { state, dispatch } = context;
return { ...state, dispatch, actions: ActionType };
};