-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElementEditScreen.tsx
More file actions
452 lines (428 loc) · 12 KB
/
ElementEditScreen.tsx
File metadata and controls
452 lines (428 loc) · 12 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import type {NativeStackScreenProps} from '@react-navigation/native-stack';
import {useState} from 'react';
import {
ActivityIndicator,
Image,
KeyboardAvoidingView,
Platform,
Pressable,
ScrollView,
StyleSheet,
Switch,
Text,
TextInput,
View,
} from 'react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import EmojiPicker from 'rn-emoji-keyboard';
import {
type ElementDetailQuery,
type ElementInput,
useElementDetailQuery,
useUpdateElementMutation,
} from '../graphql/__generated__/types';
import type {RootStackParamList} from '../navigation/types';
import {usePhotoUploader} from '../photos/photoUpload';
type Props = NativeStackScreenProps<RootStackParamList, 'ElementEdit'>;
type Element = ElementDetailQuery['element'];
// Requires an http(s) scheme and at least a host. We avoid the URL constructor
// since React Native's implementation is incomplete and inconsistent.
const URL_PATTERN = /^https?:\/\/[^\s/$.?#][^\s]*$/i;
function isValidUrl(value: string): boolean {
return URL_PATTERN.test(value);
}
export function ElementEditScreen({route, navigation}: Props) {
const {elementId} = route.params;
const {data, loading} = useElementDetailQuery({variables: {id: elementId}});
const element = data?.element;
return (
<View style={styles.screen}>
{element ? (
<EditForm element={element} onDone={() => navigation.goBack()} />
) : (
<View style={styles.loadingPane}>
{loading ? <ActivityIndicator /> : null}
</View>
)}
</View>
);
}
/**
* The form initializes its fields from the loaded element, so it's rendered
* only once the element is available. We round-trip every field the mutation
* requires — including the ones we don't expose (uri, icon, location, schedule,
* labels, trips) — so saving an edit doesn't clear them.
*/
function EditForm({element, onDone}: {element: Element; onDone: () => void}) {
const safeAreaInsets = useSafeAreaInsets();
const [name, setName] = useState(element.name);
const [uri, setUri] = useState(element.uri);
const [icon, setIcon] = useState(element.icon);
const [description, setDescription] = useState(element.description);
const [completed, setCompleted] = useState(element.completed);
// The complete desired set of photos, in display order. Initialized from the
// element and mutated as the user adds/removes; sent as photoIds on save.
const [photos, setPhotos] = useState<{id: string; thumbnail: string}[]>(() =>
element.photos.map(photo => ({id: photo.id, thumbnail: photo.thumbnail})),
);
const [pickerOpen, setPickerOpen] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [updateElement, {loading: saving}] = useUpdateElementMutation();
const {pickAndUpload, uploading} = usePhotoUploader();
const trimmedUri = uri.trim();
const uriValid = isValidUrl(trimmedUri);
const uriError =
trimmedUri.length > 0 && !uriValid ? 'Enter a valid URL.' : null;
const canSave =
name.trim().length > 0 &&
(trimmedUri.length === 0 || uriValid) &&
!saving &&
!uploading;
async function onAddPhoto() {
setErrorMessage(null);
try {
const photo = await pickAndUpload();
if (photo) {
setPhotos(prev => [
...prev,
{id: photo.id, thumbnail: photo.thumbnail},
]);
}
} catch {
setErrorMessage('Could not add photo. Please try again.');
}
}
function onRemovePhoto(id: string) {
setPhotos(prev => prev.filter(photo => photo.id !== id));
}
async function onSave() {
setErrorMessage(null);
const input: ElementInput = {
id: element.id,
name: name.trim(),
uri: trimmedUri,
icon,
description,
completed,
// Complete desired set of photo ids, in order: reorders/removes/adds.
photoIds: photos.map(photo => photo.id),
// Preserved as-is — not editable here, but required by the mutation.
labels: element.labels,
tripIds: element.trips.map(trip => trip.id),
location: element.location
? {
address: element.location.address,
latitude: element.location.latitude,
longitude: element.location.longitude,
placeId: element.location.placeId,
}
: undefined,
schedule: element.schedule
? {
allDay: element.schedule.allDay,
startDate: element.schedule.startDate,
endDate: element.schedule.endDate,
startTime: element.schedule.startTime,
endTime: element.schedule.endTime,
startTz: element.schedule.startTz,
endTz: element.schedule.endTz,
}
: undefined,
};
try {
await updateElement({variables: {input}});
onDone();
} catch {
setErrorMessage('Could not save changes. Please try again.');
}
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
style={styles.flex}>
<View style={[styles.header, {paddingTop: safeAreaInsets.top + 8}]}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Cancel editing"
hitSlop={10}
onPress={onDone}
disabled={saving}
style={styles.headerButton}>
<Text style={styles.headerButtonText}>Cancel</Text>
</Pressable>
<Text style={styles.headerTitle} numberOfLines={1}>
Edit element
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Save changes"
hitSlop={10}
onPress={onSave}
disabled={!canSave}
style={styles.headerButton}>
{saving ? (
<ActivityIndicator />
) : (
<Text
style={[
styles.headerButtonText,
styles.saveText,
!canSave && styles.saveTextDisabled,
]}>
Save
</Text>
)}
</Pressable>
</View>
<ScrollView
contentContainerStyle={[
styles.scrollContent,
{paddingBottom: safeAreaInsets.bottom + 24},
]}
keyboardShouldPersistTaps="handled">
<Field label="Name">
<TextInput
style={styles.input}
value={name}
onChangeText={setName}
placeholder="Name"
editable={!saving}
/>
</Field>
<Field label="Icon">
<Pressable
accessibilityRole="button"
accessibilityLabel="Choose icon"
disabled={saving}
onPress={() => setPickerOpen(true)}
style={styles.iconButton}>
{icon ? (
<Text style={styles.iconButtonValue}>{icon}</Text>
) : (
<Text style={styles.iconButtonPlaceholder}>+</Text>
)}
</Pressable>
</Field>
<Field label="URL">
<TextInput
style={styles.input}
value={uri}
onChangeText={setUri}
placeholder="https://example.com"
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
editable={!saving}
/>
{uriError ? <Text style={styles.error}>{uriError}</Text> : null}
</Field>
<View style={styles.switchRow}>
<Text style={styles.fieldLabel}>Completed</Text>
<Switch
value={completed}
onValueChange={setCompleted}
disabled={saving}
/>
</View>
<Field label="Photos">
<View style={styles.photoGrid}>
{photos.map(photo => (
<View key={photo.id} style={styles.photoThumbWrap}>
<Image
source={{uri: photo.thumbnail}}
style={styles.photoThumb}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Remove photo"
hitSlop={8}
disabled={saving || uploading}
onPress={() => onRemovePhoto(photo.id)}
style={styles.photoRemove}>
<Text style={styles.photoRemoveIcon}>×</Text>
</Pressable>
</View>
))}
<Pressable
accessibilityRole="button"
accessibilityLabel="Add photo"
disabled={saving || uploading}
onPress={onAddPhoto}
style={styles.photoAdd}>
{uploading ? (
<ActivityIndicator />
) : (
<Text style={styles.photoAddIcon}>+</Text>
)}
</Pressable>
</View>
</Field>
<Field label="Description">
<TextInput
style={[styles.input, styles.multiline]}
value={description}
onChangeText={setDescription}
placeholder="Description"
multiline
textAlignVertical="top"
editable={!saving}
/>
</Field>
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
</ScrollView>
<EmojiPicker
open={pickerOpen}
onClose={() => setPickerOpen(false)}
onEmojiSelected={emoji => setIcon(emoji.emoji)}
/>
</KeyboardAvoidingView>
);
}
function Field({label, children}: {label: string; children: React.ReactNode}) {
return (
<View style={styles.field}>
<Text style={styles.fieldLabel}>{label}</Text>
{children}
</View>
);
}
const styles = StyleSheet.create({
flex: {flex: 1},
screen: {
flex: 1,
backgroundColor: '#ffffff',
},
loadingPane: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
header: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 16,
paddingBottom: 12,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#ddd',
},
headerButton: {
minWidth: 56,
justifyContent: 'center',
},
headerButtonText: {
fontSize: 16,
color: '#222',
},
headerTitle: {
flex: 1,
fontSize: 16,
fontWeight: '600',
color: '#111',
textAlign: 'center',
},
saveText: {
color: '#0a7ea4',
fontWeight: '600',
textAlign: 'right',
},
saveTextDisabled: {
opacity: 0.4,
},
scrollContent: {
padding: 16,
gap: 20,
},
field: {
gap: 6,
},
fieldLabel: {
fontSize: 12,
fontWeight: '700',
color: '#888',
textTransform: 'uppercase',
letterSpacing: 0.5,
},
input: {
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 12,
fontSize: 16,
color: '#111',
},
iconButton: {
width: 64,
height: 64,
borderRadius: 8,
borderWidth: 1,
borderColor: '#ccc',
alignItems: 'center',
justifyContent: 'center',
},
iconButtonValue: {
fontSize: 32,
},
iconButtonPlaceholder: {
fontSize: 28,
color: '#aaa',
},
multiline: {
minHeight: 120,
},
photoGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 10,
},
photoThumbWrap: {
width: 80,
height: 80,
},
photoThumb: {
width: 80,
height: 80,
borderRadius: 8,
backgroundColor: '#eee',
},
photoRemove: {
position: 'absolute',
top: -6,
right: -6,
width: 22,
height: 22,
borderRadius: 11,
backgroundColor: '#222',
alignItems: 'center',
justifyContent: 'center',
},
photoRemoveIcon: {
color: '#fff',
fontSize: 16,
lineHeight: 18,
fontWeight: '600',
},
photoAdd: {
width: 80,
height: 80,
borderRadius: 8,
borderWidth: 1,
borderColor: '#ccc',
borderStyle: 'dashed',
alignItems: 'center',
justifyContent: 'center',
},
photoAddIcon: {
fontSize: 28,
color: '#aaa',
},
switchRow: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
error: {
color: '#c00',
fontSize: 14,
},
});