-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
2419 lines (2342 loc) · 78.6 KB
/
App.js
File metadata and controls
2419 lines (2342 loc) · 78.6 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useRef } from 'react'
import {
SafeAreaView,
StatusBar,
StyleSheet,
AppState,
Platform,
Alert,
TouchableOpacity,
Image,
View,
TextInput,
TouchableWithoutFeedback,
Keyboard,
FlatList,
Text,
ScrollView,
ActionSheetIOS,
ActivityIndicator,
Dimensions,
} from 'react-native'
import MapView from './kakaomap'
import Geolocation from 'react-native-geolocation-service'
import { check, request, openSettings, PERMISSIONS, RESULTS } from 'react-native-permissions'
import Animated from 'react-native-reanimated'
import BottomSheet from 'reanimated-bottom-sheet'
import Preference from 'react-native-preference'
import { DatePicker } from '@davidgovea/react-native-wheel-datepicker'
import Modal from 'react-native-modal'
import 'react-native-gesture-handler'
import { launchImageLibrary, launchCamera } from 'react-native-image-picker'
import storage from '@react-native-firebase/storage'
import firestore from '@react-native-firebase/firestore'
import ImageZoom from 'react-native-image-pan-zoom'
import Video from 'react-native-video'
import { RadioButton } from 'react-native-paper'
import { CalendarProvider, ExpandableCalendar, AgendaList, LocaleConfig } from 'react-native-calendars'
import { login, logout, getProfile as getKakaoProfile, unlink, getAccessToken } from '@react-native-seoul/kakao-login'
import DropDownPicker from 'react-native-dropdown-picker'
const kakaoGeocodeUrl = 'https://dapi.kakao.com/v2/local/search/keyword.json'
const kakaoRestApiKey = '6e1402fdd53ff5da2517db3fb6f6b7b4'
LocaleConfig.locales['kr'] = {
monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
dayNames: ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],
dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
today: '오늘',
}
LocaleConfig.defaultLocale = 'kr'
const APP = () => {
const appState = useRef(AppState.currentState)
const [location, setLocation] = useState({
latitude: 37.48496,
longitude: 127.03447,
zoomLevel: 0,
})
const [myLocation, setMyLocation] = useState({
latitude: 37.48496,
longitude: 127.03447,
zoomLevel: 0,
})
const [place, setPlace] = useState([])
const isTracking = useRef(false)
const [searchText, setSearchText] = useState('')
const [isSearch, setIsSearch] = useState(false)
const [userDatas, setUserDatas] = useState({})
const [markerDatas, setMarkerDatas] = useState([])
const [currentAlbum, setCurrentAlbum] = useState('기본앨범')
const [currentAlbumChecked, setCurrentAlbumChecked] = useState('기본앨범')
const [searchPlace, setSearchPlace] = useState({})
const [titleText, setTitleText] = useState('')
const [isMarkerDateModal, setIsMarkerDateModal] = useState(false)
const [pickerDate, setPickerDate] = useState(new Date().toISOString().substring(0, 10))
const [markerDate, setMarkerDate] = useState(new Date().toISOString().substring(0, 10))
const [detailText, setDetailText] = useState('')
const [currentFile, setCurrentFile] = useState(null)
const [loading, setLoading] = useState(false)
const [videoLoading, setVideoLoading] = useState(false)
const [isImgModal, setIsImgModal] = useState(false)
const [isVideoModal, setIsVideoModal] = useState(false)
const player = useRef(null)
const [fileResponseList, setFileResponseList] = useState([])
const [listOpen, setListOpen] = useState(false)
const [isList, setIsList] = useState(false)
const [selectPoiTag, setSelectPoiTag] = useState('')
const [isFilterModal, setIsFilterModal] = useState(false)
const [sortChecked, setSortChecked] = useState('latest')
const [sortValue, setSortValue] = useState('latest')
const [dateChecked, setDateChecked] = useState('all')
const [dateValue, setDateValue] = useState('all')
const isCheckingPermissions = useRef(false)
const [applyStartDate, setApplyStartDate] = useState(new Date().toISOString().substring(0, 10))
const [startDate, setStartDate] = useState(new Date().toISOString().substring(0, 10))
const [startPicker, setStartPicker] = useState(new Date().toISOString().substring(0, 10))
const [applyEndDate, setApplyEndDate] = useState(new Date().toISOString().substring(0, 10))
const [endDate, setEndDate] = useState(new Date().toISOString().substring(0, 10))
const [endPicker, setEndPicker] = useState(new Date().toISOString().substring(0, 10))
const [isFilterStartModal, setIsFilterStartModal] = useState(false)
const [isFilterEndModal, setIsFilterEndModal] = useState(false)
const [filterCnt, setFilterCnt] = useState(0)
const [isCalendarModal, setIsCalendarModal] = useState(false)
const today = new Date().toISOString().split('T')[0]
const [agendaData, setAgendaData] = useState([])
const [calendarMarked, setCalendarMarked] = useState({})
const [isLoginModal, setIsLoginModal] = useState(false)
const [kakaoResult, setKakaoResult] = useState('')
const [isProfileModal, setIsProfileModal] = useState(false)
const [isAlbumModal, setIsAlbumModal] = useState(false)
const [isAlbumCreateModal, setIsAlbumCreateModal] = useState(false)
const [albumText, setAlbumText] = useState('')
const [isShareFriendModal, setIsShareFriendModal] = useState(false)
const [friendIdText, setFriendIdText] = useState('')
const [friendNameText, setFriendNameText] = useState('')
const isCorrectId = useRef(true)
const [shareDatas, setShareDatas] = useState({})
const [pickerOpen, setPickerOpen] = useState(false)
const [pickerValue, setPickerValue] = useState('나의 앨범')
const [pickerItems, setPickerItems] = useState([{ label: '나의 앨범', value: '나의 앨범' }])
const [isDefaultAlbum, setIsDefaultAlbum] = useState(true)
const markerCollenction = firestore().collection('users')
const sheetRef = useRef(null)
const placeListSheetRef = useRef(null)
useEffect(async () => {
AppState.addEventListener('change', handleAppStateChange)
_requestPermission()
await getProfile()
await _shareDataDownload()
return () => {
AppState.removeEventListener('change', handleAppStateChange)
}
}, [])
useEffect(() => {
let marked = {}
markerDatas.map(value => {
marked = { ...marked, [value?.time]: { marked: true, dotColor: '#50cebb' } }
})
setCalendarMarked(marked)
}, [markerDatas])
const signInWithKakao = async () => {
try {
const token = await login()
console.log('token : ', JSON.stringify(token))
getProfile()
} catch (err) {
console.error('login err', err)
}
}
const signOutWithKakao = async () => {
setLoading(true)
try {
const message = await logout()
console.log('message : ', JSON.stringify(message))
setKakaoResult('')
setUserDatas({})
Preference.clear('shareData')
setPickerValue('나의 앨범')
setIsDefaultAlbum(true)
setPickerItems([{ label: '나의 앨범', value: '나의 앨범' }])
setShareDatas({})
setCurrentAlbum('기본앨범')
setCurrentAlbumChecked('기본앨범')
setMarkerDatas([])
setLoading(false)
} catch (err) {
console.error('signOut error', err)
setLoading(false)
}
}
const getProfile = async () => {
setLoading(true)
try {
const profile = await getKakaoProfile()
console.log('profile : ', JSON.parse(JSON.stringify(profile)))
setKakaoResult(JSON.parse(JSON.stringify(profile)))
const id = JSON.parse(JSON.stringify(profile))?.id.toString()
const data = await markerCollenction.doc(id).get()
if (data?._data === undefined) {
await markerCollenction.doc(id).set({ 기본앨범: { markerData: [], createdAt: new Date() } })
}
_downloadMarker(id)
setIsLoginModal(false)
setLoading(false)
} catch (err) {
console.error('profile error', err)
setIsLoginModal(true)
setLoading(false)
}
}
const handleAppStateChange = nextAppState => {
if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
if (isCheckingPermissions.current) {
_getCurrentLocation()
}
isCheckingPermissions.current = false
}
if (appState.current.match(/inactive|active/) && nextAppState === 'background') {
}
appState.current = nextAppState
}
const _checkPermission = async () => {
await check(Platform.select({ ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE, android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION }))
.then(result => {
if (result === RESULTS.GRANTED || result === RESULTS.LIMITED) {
return Promise.resolve({ isGranted: true })
} else {
return Promise.reject({
result: result,
})
}
})
.catch(error => {
return Promise.reject({
result: error,
})
})
}
const _requestLocation = async () => {
await request(Platform.select({ ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE, android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION }))
.then(result => {
if (result === RESULTS.GRANTED) {
return Promise.resolve({ isGranted: true })
} else {
return Promise.reject({
result: result,
})
}
})
.catch(error => {
return Promise.reject({
result: error,
})
})
}
const _requestPermission = async () => {
await _checkPermission()
.then(response => {
isTracking.current = true
_getCurrentLocation()
})
.catch(error => {
return _requestLocation()
.then(response => {
isTracking.current = true
_getCurrentLocation()
})
.catch(denyError => {
isTracking.current = false
_getDefaultLocation()
})
})
}
const _confirmPermission = async () => {
return _checkPermission()
.then(response => {
return Promise.resolve(true)
})
.catch(error => {
const title = '위치권한 필요'
const message = '위치권한 동의'
const buttons = [
{
text: '허용 안함',
onPress: () => {
_getDefaultLocation()
return Promise.reject(true)
},
style: 'cancel',
},
{
text: '설정 이동',
onPress: () => {
isCheckingPermissions.current = true
openSettings()
return Promise.reject(false)
},
},
]
Alert.alert(title, message, buttons)
})
}
const _getDefaultLocation = () => {
const latitude = 37.48496
const longitude = 127.03447
const current = {
latitude: latitude,
longitude: longitude,
}
setLocation(current)
}
const _getCurrentLocation = () => {
Geolocation.getCurrentPosition(
position => {
const { latitude, longitude } = position.coords
const current = {
latitude: latitude,
longitude: longitude,
}
setLocation(current)
setMyLocation(current)
},
error => {
_confirmPermission()
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 10000,
},
)
return
}
const _onPressList = () => {
setListOpen(true)
placeListSheetRef.current.snapTo(1)
}
const _onPressCurrentLocation = () => {
_getCurrentLocation()
}
const _onMapDragEnded = event => {
const { latitude, longitude } = event.coordinate
const current = {
latitude: latitude,
longitude: longitude,
}
setLocation(current)
}
const _onMarkerSelect = event => {
Keyboard.dismiss()
placeListSheetRef.current.snapTo(2)
setIsSearch(false)
const current = {
latitude: event.coordinate.latitude,
longitude: event.coordinate.longitude,
}
const selectMarker = markerDatas.find(v => v.tag === event.tag.toString())
const placeData = {
id: selectMarker.tag,
place_name: selectMarker.title,
address_name: selectMarker.info.address,
isSave: selectMarker.save,
time: selectMarker.time,
detail: selectMarker.detail,
fileUrlList: selectMarker.fileUrlList,
}
setLocation(current)
setSearchPlace(placeData)
setMarkerDate(selectMarker.time)
setPickerDate(selectMarker.time)
setTitleText(selectMarker.title)
setDetailText(selectMarker.detail)
setFileResponseList(selectMarker.fileUrlList)
sheetRef.current.snapTo(1)
}
const _onMapTouch = event => {
Keyboard.dismiss()
setIsSearch(false)
setFileResponseList([])
sheetRef.current.snapTo(2)
placeListSheetRef.current.snapTo(2)
setMarkerDatas(markerDatas.filter(v => v.save === true))
}
const _onChangeText = async text => {
setSearchText(text)
if (text === '') {
return
}
const placeList = await getAddressByKeyword(text)
setPlace(placeList)
if (placeList?.length > 0) {
setIsSearch(true)
} else {
setIsSearch(false)
}
}
const _onChangeTitle = text => {
setTitleText(text)
}
const _onChangeDetail = text => {
setDetailText(text)
}
const _onSearch = async () => {
Keyboard.dismiss()
setFileResponseList([])
sheetRef.current.snapTo(2)
placeListSheetRef.current.snapTo(2)
if (searchText === '') {
return
}
const placeList = await getAddressByKeyword(searchText)
setPlace(placeList)
if (placeList?.length > 0) {
setIsSearch(true)
} else {
setIsSearch(false)
}
}
const getAddressByKeyword = async keyword => {
let option = {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'KakaoAK ' + kakaoRestApiKey,
},
}
return await fetch(
kakaoGeocodeUrl + '?page=1&size=10&sort=accuracy&x=' + myLocation.longitude + '&y=' + myLocation.latitude + '&query=' + keyword,
option,
)
.then(response => {
if (response.status == 200) {
return response.json()
} else {
console.log('errorerrorerrorerrorerror : ', response)
}
})
.then(responseJson => {
return responseJson?.documents || []
})
.catch(error => {
console.log('error : ', error)
})
}
const _renderItem = ({ item, index }) => {
return (
<View style={styles.searchContainer}>
<TouchableOpacity style={styles.searchItem} onPress={() => _addMarker(item)}>
<Text style={styles.place}>{item.place_name}</Text>
<Text style={styles.address}>{item.address_name}</Text>
</TouchableOpacity>
</View>
)
}
const _addMarker = item => {
setIsSearch(false)
Keyboard.dismiss()
setSearchPlace(item)
const prevMarkers = [...markerDatas]
const placeMarker = {
tag: item.id,
title: item.place_name,
info: { address: item.address_name },
latitude: Number(item.y),
longitude: Number(item.x),
markerImage: 'marker',
markerSelectImage: 'markerSel',
search: true,
save: false,
time: new Date().toISOString().substring(0, 10),
detail: '',
fileUrlList: [],
}
setMarkerDatas(
prevMarkers.concat(placeMarker).reduce((result = [], value) => {
if (!result.includes(value) && result.filter(item => item['tag'] === value['tag']).length <= 0) {
result.push(value)
}
return result
}, []),
)
const current = {
latitude: Number(item.y),
longitude: Number(item.x),
}
setLocation(current)
if (prevMarkers.length !== markerDatas.length) {
sheetRef.current.snapTo(1)
}
}
const _changeAlbum = key => {
setCurrentAlbum(key)
setMarkerDatas(pickerValue === '나의 앨범' ? userDatas[key]?.markerData : shareDatas?.albumData[key]?.markerData || [])
}
const _shareDataDownload = async () => {
setLoading(true)
try {
const shareData = Preference.get('shareData')
console.log('shareData : ', shareData)
if (shareData !== undefined) {
await _friendInvite(shareData?.friendId, shareData?.friendName)
}
setLoading(false)
} catch (error) {
setLoading(false)
console.log(error.message)
}
}
const _downloadMarker = async (id, key = currentAlbum) => {
setLoading(true)
try {
const data = await markerCollenction.doc(id).get()
console.log('data?._data :', data?._data)
const sortValue = Object.fromEntries(
Object.entries(data?._data).sort((a, b) => {
return a[1].createdAt.toDate() > b[1].createdAt.toDate() ? 1 : a[1].createdAt.toDate() === b[1].createdAt.toDate() ? 0 : -1
}),
)
setUserDatas(sortValue)
setMarkerDatas(data?._data[key]?.markerData || [])
setLoading(false)
} catch (error) {
setLoading(false)
console.log(error.message)
}
}
const _uploadMarker = async markers => {
const id = (kakaoResult?.id).toString()
try {
await markerCollenction.doc(id).update({ [currentAlbum]: { markerData: markers, createdAt: userDatas[currentAlbum].createdAt } })
} catch (error) {
console.log(error.message)
}
}
const _uploadFileList = async () => {
let imageUrl = ''
let videoUrl = ''
try {
const result = await Promise.all(
fileResponseList.map(async item => {
if (item.uri.includes('firebasestorage')) {
return item
} else {
if (item.type.includes('image')) {
const reference = storage().ref(`/image/${item.fileName}`) // 업로드할 경로 지정
await reference.putFile(item.uri)
imageUrl = await reference.getDownloadURL()
console.log('imageUrl', imageUrl)
const itemImage = { type: item.type, fileName: item.fileName, uri: imageUrl }
return itemImage
} else {
const reference = storage().ref(`/video/${item.fileName}`) // 업로드할 경로 지정
await reference.putFile(item.uri)
videoUrl = await reference.getDownloadURL()
console.log('videoUrl', videoUrl)
const itemVideo = { type: item.type, fileName: item.fileName, uri: videoUrl }
return itemVideo
}
}
}),
)
return result
} catch (error) {
console.log('errororroro : ', error)
}
}
const markerSave = async () => {
setLoading(true)
let fileList = []
if (fileResponseList.length > 0) {
fileList = await _uploadFileList()
}
let marker = markerDatas.filter(v => v.tag === searchPlace.id)[0]
marker = {
...marker,
title: titleText,
search: false,
save: true,
time: markerDate,
detail: detailText,
fileUrlList: fileList,
}
let others = markerDatas.filter(v => v.tag !== searchPlace.id)
setMarkerDatas([...others, marker])
await _uploadMarker([...others, marker])
await _downloadMarker((kakaoResult?.id).toString())
setFileResponseList([])
sheetRef.current.snapTo(2)
setLoading(false)
}
const markerModify = async () => {
setLoading(true)
let fileList = []
if (fileResponseList.length > 0) {
fileList = await _uploadFileList()
}
let marker = markerDatas.filter(v => v.tag === searchPlace.id)[0]
marker = { ...marker, title: titleText, time: markerDate, detail: detailText, fileUrlList: fileList }
let others = markerDatas.filter(v => v.tag !== searchPlace.id)
setMarkerDatas([...others, marker])
await _uploadMarker([...others, marker])
await _downloadMarker((kakaoResult?.id).toString())
setFileResponseList([])
sheetRef.current.snapTo(2)
setLoading(false)
}
const markerDelete = async () => {
setLoading(true)
const deleteMarkers = markerDatas
.filter(v => v.tag !== searchPlace.id)
.reduce((result = [], value) => {
result.push({
...value,
search: false,
})
return result
}, [])
setMarkerDatas(deleteMarkers)
await _uploadMarker(deleteMarkers)
await _downloadMarker((kakaoResult?.id).toString())
setFileResponseList([])
sheetRef.current.snapTo(2)
setLoading(false)
}
const _preView = item => {
if (item.type.includes('image')) {
return (
<Image
style={styles.preivew}
source={{ uri: item.uri }}
onLoadStart={() => setLoading(true)}
onLoadEnd={() => setLoading(false)}
onError={error => {
console.log('error : ', error)
setLoading(false)
}}
/>
)
} else {
return (
<Video
source={{ uri: item.uri }}
ref={player}
paused={true}
style={styles.preivew}
resizeMode={'stretch'}
onLoadStart={() => {
setVideoLoading(true)
}}
onLoad={() => {
setVideoLoading(false)
player?.current?.seek(0) // 로드가 완료되었을떄 첫 프레임이 썸네일처럼 보임
}}
onError={error => {
console.log('error : ', error)
setVideoLoading(false)
}}
/>
)
}
}
const _modalOpen = () => {
ActionSheetIOS.showActionSheetWithOptions(
{
options: ['사진 촬영하기', '동영상 촬영하기', '앨범에서 선택하기', '취소'],
cancelButtonIndex: 3,
},
buttonIndex => {
if (buttonIndex === 0) {
_onImageCamera()
} else if (buttonIndex === 1) {
_onVideoCamera()
} else if (buttonIndex === 2) {
_onSelectImage()
}
},
)
}
const _onImageCamera = async () => {
setLoading(true)
const options = {
mediaType: 'photo',
presentationStyle: 'fullScreen',
includeExtra: true,
maxWidth: 1024,
maxHeight: 1024,
}
const result = await launchCamera(options)
console.log(result)
setLoading(false)
if (result?.assets === undefined) return
if (currentFile !== null) {
const modify = fileResponseList.reduce((list = [], value) => {
if (value.fileName === currentFile.fileName) {
list.push({
...value,
type: result?.assets[0]?.type,
fileName: result?.assets[0]?.fileName,
uri: result?.assets[0]?.uri,
})
} else {
list.push({
...value,
})
}
return list
}, [])
setFileResponseList(modify)
} else {
setFileResponseList(
fileResponseList.concat({
type: result?.assets[0]?.type,
fileName: result?.assets[0]?.fileName,
uri: result?.assets[0]?.uri,
}),
)
}
setCurrentFile(null)
}
const _onVideoCamera = async () => {
setLoading(true)
const options = {
mediaType: 'video',
presentationStyle: 'fullScreen',
includeExtra: true,
videoQuality: 'medium',
}
const result = await launchCamera(options)
console.log(result)
setLoading(false)
if (result?.assets === undefined) return
if (currentFile !== null) {
const modify = fileResponseList.reduce((list = [], value) => {
if (value.fileName === currentFile.fileName) {
list.push({
...value,
type: result?.assets[0]?.type,
fileName: result?.assets[0]?.fileName,
uri: result?.assets[0]?.uri,
})
} else {
list.push({
...value,
})
}
return list
}, [])
setFileResponseList(modify)
} else {
setFileResponseList(
fileResponseList.concat({
type: result?.assets[0]?.type,
fileName: result?.assets[0]?.fileName,
uri: result?.assets[0]?.uri,
}),
)
}
setCurrentFile(null)
}
const _onSelectImage = async () => {
setLoading(true)
const options = {
mediaType: 'mixed',
presentationStyle: 'fullScreen',
includeExtra: true,
maxWidth: 1024,
maxHeight: 1024,
}
const result = await launchImageLibrary(options)
console.log(result)
setLoading(false)
if (result?.assets === undefined) return
if (currentFile !== null) {
const modify = fileResponseList.reduce((list = [], value) => {
if (value.fileName === currentFile.fileName) {
list.push({
...value,
type: result?.assets[0]?.type,
fileName: result?.assets[0]?.fileName,
uri: result?.assets[0]?.uri,
})
} else {
list.push({
...value,
})
}
return list
}, [])
setFileResponseList(modify)
} else {
setFileResponseList(
fileResponseList.concat({
type: result?.assets[0]?.type,
fileName: result?.assets[0]?.fileName,
uri: result?.assets[0]?.uri,
}),
)
}
setCurrentFile(null)
}
const _renderHeader = () => {
return loading || videoLoading ? null : (
<View style={styles.header}>
<View style={styles.panelHeader}>
<View style={styles.panelHandle} />
</View>
<View style={styles.modifyContainer}>
<TouchableOpacity
onPress={() => {
searchPlace?.isSave ? markerModify() : markerSave()
Keyboard.dismiss()
}}
style={styles.modify}>
<Text style={styles.modifyText}>{searchPlace?.isSave ? '수정' : '저장'}</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
markerDelete()
Keyboard.dismiss()
}}
style={styles.delete}>
<Text style={styles.modifyText}>삭제</Text>
</TouchableOpacity>
</View>
</View>
)
}
const _loadingView = () => (
<View style={styles.loadingView}>
<ActivityIndicator size={'large'} color="red" />
</View>
)
const _fileView = () => {
return (
<ScrollView horizontal={true}>
{fileResponseList?.length > 0
? fileResponseList.map(item => {
return (
<TouchableOpacity
onPress={() => {
if (item.type.includes('image')) {
setCurrentFile(item)
setIsImgModal(true)
} else {
setCurrentFile(item)
setIsVideoModal(true)
}
}}
style={styles.fileView}
key={item.fileName}>
{_preView(item)}
</TouchableOpacity>
)
})
: null}
<TouchableOpacity onPress={() => _modalOpen()}>
<View style={styles.fileAddView}>
<Text style={styles.plusText}>+</Text>
</View>
</TouchableOpacity>
</ScrollView>
)
}
const _renderContent = () => {
return (
<ScrollView style={styles.bottomContent}>
<TextInput
style={styles.titleText}
onChangeText={_onChangeTitle}
autoCapitalize={'none'}
autoCorrect={false}
textAlignVertical={'center'}
textAlign={'center'}
underlineColorAndroid={'transparent'}
keyboardType={'default'}
keyboardAppearance={'default'}
value={titleText}
onFocus={() => sheetRef.current.snapTo(0)}
/>
<View style={styles.addressView}>
<Text>장소</Text>
<View style={styles.addressViewContainer}>
<Image style={styles.markerImage} source={require('./images/marker.png')} />
<Text style={styles.addressText}>{searchPlace?.address_name}</Text>
</View>
</View>
<View style={styles.dateView}>
<Text>방문일자</Text>
<TouchableOpacity
onPress={() => {
setIsMarkerDateModal(true)
}}
style={styles.dateViewContainer}>
<Text>{markerDate}</Text>
</TouchableOpacity>
</View>
<TextInput
style={styles.detail}
onFocus={() => sheetRef.current.snapTo(0)}
multiline={true}
placeholder={'추억을 기록해보세요.'}
placeholderTextColor={'black'}
onChangeText={_onChangeDetail}
value={detailText}
autoCapitalize={'none'}
autoCorrect={false}
keyboardType={'default'}
keyboardAppearance={'default'}
textAlignVertical={'center'}
/>
<View style={styles.fileViewContainer}>{_fileView()}</View>
{loading || videoLoading ? _loadingView() : null}
</ScrollView>
)
}
const _listRenderHeader = () => {
return (
<View style={styles.header}>
<View style={styles.panelHeader}>
<View style={styles.panelHandle} />
</View>
<View style={styles.listContainer}>
<View style={styles.listView}>
<Text style={styles.listText}>장소 모아보기 </Text>
<Text style={styles.listText}>({filterCnt})</Text>
</View>
<TouchableOpacity style={styles.listView} onPress={() => setIsFilterModal(true)}>
<Image
style={styles.listFilterImage}
source={sortValue !== 'latest' || dateValue !== 'all' ? require('./images/applyFilter.png') : require('./images/filter.png')}
/>
<Text style={sortValue !== 'latest' || dateValue !== 'all' ? styles.listApplyText : styles.listText}> 필터</Text>
</TouchableOpacity>
</View>
</View>
)
}
const _noDataView = () => {
return (
<View style={styles.noData}>
<Text>저장된 장소가 없습니다.</Text>
</View>
)
}
const _listRenderContent = () => {
let values = []
values = [...markerDatas]
if (dateValue === 'set') {
values = values.filter(v => new Date(v.time) >= new Date(applyStartDate) && new Date(v.time) <= new Date(applyEndDate))
}
if (sortValue === 'latest') {
values.sort((a, b) => {
if (new Date(a.time) < new Date(b.time)) return 1
else if (new Date(a.time) === new Date(b.time)) return 0
else return -1
})
} else {
values.sort((a, b) => {
if (new Date(a.time) > new Date(b.time)) return 1
else if (new Date(a.time) === new Date(b.time)) return 0
else return -1
})
}
setFilterCnt(values.filter(v => v.save === true).length)