-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUser.js
369 lines (328 loc) · 11.1 KB
/
User.js
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, FlatList, SafeAreaView, TextInput, KeyboardAvoidingView, Keyboard} from 'react-native';
import { useQuery, useMutation, useSubscription, useApolloClient } from '@apollo/react-hooks';
import { ColorWheel } from 'react-native-color-wheel';
import colorsys from 'colorsys';
import { listUsers } from '../../gql/queries';
import { createUser, updateUser, deleteUser } from '../../gql/mutations';
import { onCreateUser, onUpdateUser, onDeleteUser } from '../../gql/subscriptions';
import { noop, getHeight, getWidth, COLORS } from '../../utils';
const NUM_COLUMNS = 1;
const INITIAL_COLOR = '#ffffff';
const styles = StyleSheet.create({
center: {
justifyContent: 'center',
alignItems: 'center',
},
container: {
flex: 1,
}
});
// #region USER_FORM
const userFormStyles = StyleSheet.create({
textInput: {
width: getWidth(),
height: 40,
borderTopWidth: 1,
borderBottomWidth: 1,
},
formContainer: {
marginBottom: 10,
},
submitBtn: {
width: getWidth() * 0.8,
alignSelf: 'center',
backgroundColor: COLORS.BLUE,
height: 40,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 5,
},
colorwheelContainer: {
width: getWidth(),
height: getHeight() * 0.4,
marginBottom: 30,
},
colorwheelThumb: {
height: 15,
width: 15,
borderRadius: 15,
},
})
function UserForm({ initUser, closeForm }) {
const isUpdate = !!initUser.name; // if name is truthy, its an update
const [name, setName] = useState(initUser.name || '');
const [age, setAge] = useState(String(initUser.age || ''));
const [color, setColor] = useState(initUser.color || INITIAL_COLOR);
const [createUserFn] = useMutation(createUser);
const [updateUserFn] = useMutation(updateUser);
const onColorChangeComplete = color => {
let hexColor = INITIAL_COLOR;
try {
hexColor = colorsys.hsv2Hex(color.h, color.s, color.v);
} catch (err) {
console.error('onColorChangeComplete error::', err);
}
setColor(hexColor);
};
const doCreateUser = async () => {
if (!name) {
alert('Must input name!')
return;
}
try {
const { data } = await createUserFn({
variables: {
input: {
name: name.trim(),
age: age === '0' ? parseInt(age) : parseInt(age || 0) || null,
favColor: color,
}
}
});
console.log(data);
alert(`Successfully created user ${name}!`);
} catch (err) {
console.error(err);
alert(err.message || 'Error creating user');
}
}
const doUpdateUser = async () => {
try {
const { data } = await updateUserFn({
variables: {
id: initUser.id,
input: {
name: name.trim(),
age: age === '0' ? parseInt(age) : parseInt(age || 0) || null,
favColor: color,
}
}
});
console.log('update user data', data);
alert(`Successfully updated user ${name}!`);
} catch (err) {
console.error(err);
alert(err.message || 'Error occurred updating user');
}
}
return (
<SafeAreaView style={styles.container}>
{/* This btn helps dismiss the keyboard when pressing anywhere */}
<TouchableOpacity activeOpacity={1} onPress={Keyboard.dismiss} style={styles.container}>
<KeyboardAvoidingView style={styles.container} behavior="padding" enabled>
<TouchableOpacity style={{ margin: 20 }} onPress={closeForm}>
<Text style={{ color: COLORS.BLUE }}>Go Back</Text>
</TouchableOpacity>
<View style={userFormStyles.formContainer}>
<Text>Name <Text style={{ color: 'red' }}>*</Text></Text>
<TextInput value={name} style={userFormStyles.textInput} placeholder="Sgt. Slaughter *" onChangeText={text => setName(text)} />
</View>
<View style={userFormStyles.formContainer}>
<Text>Age</Text>
<TextInput value={age} keyboardType="number-pad" style={userFormStyles.textInput} placeholder="26" onChangeText={text => setAge(text)} />
</View>
<Text>Color is {color}</Text>
<View style={userFormStyles.colorwheelContainer}>
<ColorWheel
initialColor={color}
// onColorChange={color => console.log({color})}
onColorChangeComplete={onColorChangeComplete}
thumbStyle={userFormStyles.colorwheelThumb}
/>
</View>
<TouchableOpacity style={userFormStyles.submitBtn} onPress={isUpdate ? doUpdateUser : doCreateUser}>
<Text style={{ color: 'white' }}>{isUpdate ? 'Update User' : 'Create User'}</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</TouchableOpacity>
</SafeAreaView>
)
}
// #endregion USER_FORM
// #region USER
const userStyles = StyleSheet.create({
addUserBtn: {
position: 'absolute',
right: getWidth() * .15,
backgroundColor: COLORS.BLUE,
width: getWidth() * .3,
padding: 10,
borderRadius: 4
},
centerFlex: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
header: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 20,
marginLeft: 20,
marginBottom: 10,
width: getWidth(),
},
});
function handleUserOnData({ client, subscriptionData:{ data } }, refetch) {
/** Commented out to show logic could possibly do but we'll just refetch
* in which case we're really better off polling!!
*/
// const res = client.readQuery({
// query: listUsers
// });
// const [key] = Object.keys(data);
// switch (key) {
// case 'onCreateUser':
// console.log('onCreateUser', data);
// res.listUsers.filter(user => user.id !== data.onCreateUser.id).concat(data.onCreateUser);
// break;
// case 'onUpdateUser':
// console.log('onUpdateUser', data);
// res.listUsers.filter(user => user.id !== data.onUpdateUser.id).concat(data.onUpdateUser);
// break;
// case 'onDeleteUser':
// console.warn('onDeleteUser subscriptions returns null... Possible bug??');
// break;
// default:
// break;
// }
// client.writeQuery({
// query: listUsers,
// data: res,
// });
refetch();
}
function renderListEmpty() {
return (
<View style={userStyles.centerFlex}>
<Text>No Users</Text>
</View>
);
}
// go to the UserForm screen which uses initUser to determine whether its a create or update
function doUpdateUser(user, setRenderFormObj) {
setRenderFormObj({ isRenderForm: true, initUser: { id: user.id, name: user.name, color: user.favColor, age: user.age } });
}
async function doDeleteUser(user, deleteUserFn) {
try {
const {data} = await deleteUserFn({
variables: {
id: user.id,
}
});
console.log('delete user data', data);
alert(`Successfully deleted user ${user.name}!`);
} catch (err) {
console.error(err);
alert(err.message || 'Error occurred deleting User');
}
}
function renderUser({ item: user }, setRenderFormObj, deleteUserFn) {
return <UserCard user={user} doUpdate={() => doUpdateUser(user, setRenderFormObj)} doDelete={() => doDeleteUser(user, deleteUserFn)} />;
}
function renderLoading() {
return (
<View style={userStyles.centerFlex}>
<Text>Loading...</Text>
</View>
);
}
function renderError() {
return (
<View style={userStyles.centerFlex}>
<Text style={{color:'red'}}>{JSON.stringify(error, null, 5)}</Text>
</View>
);
}
function User() {
const [renderFormObj, setRenderFormObj] = useState({ isRenderForm: false, initUser: {} });
const {data, loading, refetch, error} = useQuery(listUsers, {fetchPolicy:'cache-and-network'});
const [deleteUserFn] = useMutation(deleteUser);
useSubscription(onCreateUser, { onSubscriptionData: data => handleUserOnData(data, refetch) });
useSubscription(onUpdateUser, { onSubscriptionData: data => handleUserOnData(data, refetch) });
useSubscription(onDeleteUser, { onSubscriptionData: data => handleUserOnData(data, refetch) });
function closeForm() {
setRenderFormObj({ isRenderForm: false, initUser: {} });
}
function openForm() {
setRenderFormObj({ isRenderForm: true, initUser: {} });
}
if (renderFormObj.isRenderForm) return <UserForm closeForm={closeForm} initUser={renderFormObj.initUser} />;
if (loading) return renderLoading();
if (error) return renderError();
const users = data ? data.listUsers : [];
if (!users.length) return renderListEmpty();
return (
<SafeAreaView style={[styles.container]}>
<View style={[userStyles.header]}>
<Text style={{fontSize:28, fontWeight:'bold'}}>{`${users.length} Users`}</Text>
<TouchableOpacity onPress={openForm} style={[styles.center, userStyles.addUserBtn]}>
<Text style={{color:'white'}}>Add User</Text>
</TouchableOpacity>
</View>
<FlatList
data={users}
renderItem={renderArg => renderUser(renderArg, setRenderFormObj, deleteUserFn)}
keyExtractor={user => user.id}
onRefresh={refetch}
refreshing={loading}
numColumns={NUM_COLUMNS}
contentContainerStyle={{ paddingBottom:50 }}
/>
</SafeAreaView>
)
}
// #endregion USER
// #region USER_CARD
const CARD_MARGIN = 20;
const CARD_HEIGHT_PERCENTAGE = .5; // how big card is out of screen height
const cardStyles = StyleSheet.create({
container: {
width: (getWidth() / NUM_COLUMNS) - (CARD_MARGIN * 2),
height: getHeight() * CARD_HEIGHT_PERCENTAGE,
margin: CARD_MARGIN,
borderWidth: 1,
borderColor: 'rgba(0,0,0,.03)'
},
header: {
fontSize:20,
fontWeight:'bold',
},
btnContainer: {
flexDirection: 'row',
}
});
function UserCard({
user={},
doUpdate=noop,
doDelete=noop,
}) {
const width = (getWidth() / NUM_COLUMNS) - (CARD_MARGIN * 2);
const height = getHeight();
return (
<View style={[cardStyles.container]}>
{/* Header */}
<View style={[styles.center, { backgroundColor: 'rgba(0,0,0,.03)', height: height * CARD_HEIGHT_PERCENTAGE * 0.25 }]}>
<Text style={cardStyles.header}>{`${user.name} - ${user.age === 0 ? 0 : user.age ? user.age : '∞'}`}</Text>
</View>
{/* Color Block */}
<View style={[styles.center, {backgroundColor:user.favColor, height: height * CARD_HEIGHT_PERCENTAGE * 0.6}]}>
<Text>{user.favColor}</Text>
</View>
{/* Action Btn Block */}
<View style={[cardStyles.btnContainer]}>
{/* Update Btn */}
<TouchableOpacity onPress={doUpdate} style={[styles.center, { borderColor: COLORS.BLUE, borderRadius:4, borderWidth:1, width: (width / 2)-1, height: height * CARD_HEIGHT_PERCENTAGE * 0.15 }]}>
<Text style={{ color:COLORS.BLUE }}>Update</Text>
</TouchableOpacity>
{/* Delete Btn */}
<TouchableOpacity onPress={doDelete} style={[styles.center, { borderColor: COLORS.RED, borderRadius:4, borderWidth:1, width: (width / 2)-1, height: height * CARD_HEIGHT_PERCENTAGE * 0.15 }]}>
<Text style={{ color:COLORS.RED }}>Delete</Text>
</TouchableOpacity>
</View>
</View>
)
}
// #endregion USER_CARD
export default User;