Browse Source

feat(activity project-training): training page

master
farhantock 7 months ago
parent
commit
b3a1a11abf
  1. 306
      src/screens/activity/training/dialogFrom.js
  2. 88
      src/screens/activity/training/index.js

306
src/screens/activity/training/dialogFrom.js

@ -0,0 +1,306 @@
import React, { useState, useRef, useCallback, useMemo } from 'react';
import { TouchableRipple, Chip, Button, Text, Appbar, TextInput } from 'react-native-paper';
import { View, StyleSheet, ScrollView, PermissionsAndroid, Image, KeyboardAvoidingView } from 'react-native';
import { colors } from '../../../utils/color';
import { strings } from '../../../utils/i18n';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import { dummyDataTraining } from '../../../config/ApiConst'
import { StatusBar } from 'react-native';
import { launchCamera } from 'react-native-image-picker';
import { requestAccessStoragePermission } from '../../../utils/storage';
import { getCoords } from '../../../utils/geolocation';
import {
BottomSheetModal,
BottomSheetModalProvider,
BottomSheetView,
} from '@gorhom/bottom-sheet';
import RNFS from 'react-native-fs';
import ImageMarker, { Position, TextBackgroundType } from 'react-native-image-marker';
import moment from 'moment';
export default function DialogForm({ route, navigation }) {
const [images, setImages] = useState([]);
const [selectedItems, setSelectedItems] = useState([]);
const [selectedImageUri, setSelectedImageUri] = useState(null);
const [dataTraining, setDataTraining] = useState(dummyDataTraining)
const bottomSheetImage = useRef(null);
const handleCheckboxChange = (item) => {
const updatedDataTraining = dataTraining.map(dataItem => {
if (dataItem.label === item.label) {
return { ...dataItem, checked: !dataItem.checked };
}
return dataItem;
});
setDataTraining(updatedDataTraining);
};
const isItemSelected = (label) => {
return dataTraining.some(item => item.label === label && item.checked);
};
const handleSetImageUri = (uri, description) => {
const newImage = { uri: uri, description: description || "" };
setImages(prevImages => [...prevImages, newImage]);
}
const handleDeleteImage = (index) => {
const updatedImages = [...images];
updatedImages.splice(index, 1);
setImages(updatedImages);
};
const handleOpenSheetImage = useCallback((uri) => {
setSelectedImageUri(uri);
bottomSheetImage.current?.present();
}, []);
const handleTakePicture = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: strings('takePicture.cameraPermissionTitle'),
message: strings('takePicture.cameraPermissionMessage'),
buttonNeutral: strings('takePicture.cameraPermissionBtnNeutral'),
buttonNegative: strings('takePicture.cameraPermissionBtnCancel'),
buttonPositive: strings('takePicture.cameraPermissionBtnPositive'),
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
handleLaunchCamera()
} else {
}
} catch (err) {
console.warn(err);
}
};
const handleLaunchCamera = () => {
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
cameraType: 'front',
maxWidth: 768,
maxHeight: 1024,
saveToPhotos: false,
includeBase64: true
};
launchCamera(options, (response) => {
if (response.didCancel) {
} else if (response.error) {
} else if (response.customButton) {
} else {
if (response.assets && response.assets.length > 0) {
handleSetImageUri(response.assets[0].uri);
getCoords(loc => {
if (loc) {
let imageObject = {
"image_uri": response.assets[0].uri,
"image_blob": response.assets[0].base64,
"lat": loc.lat,
"lon": loc.lon
}
addOverlay(imageObject)
}
})
}
}
});
}
const addOverlay = async (imageObject) => {
try {
const timestamp = new Date().toLocaleString();
const location = { latitude: imageObject.lat, longitude: imageObject.lon };
const overlayText = `${timestamp}\nLatitude: ${location.latitude}\nLongitude: ${location.longitude}`;
if (imageObject.image_uri) {
const markedImage = await ImageMarker.markText({
backgroundImage: {
src: { uri: imageObject.image_uri }
},
watermarkTexts: [{
text: overlayText,
positionOptions: {
position: Position.bottomLeft,
},
style: {
color: '#ffffff',
fontSize: 8,
fontName: 'Arial',
textBackgroundStyle: {
padding: 10,
type: TextBackgroundType.none,
color: '#00000080'
}
},
}],
position: 'bottomLeft',
color: '#ffffff',
fontName: 'Arial-BoldMT',
fontSize: 16,
scale: 1,
});
await saveToTemporaryFolder(markedImage, imageObject);
}
} catch (error) {
console.error('Error adding overlay:', error);
}
}
const saveToTemporaryFolder = async (markedImage, imageObject) => {
try {
const tempPath = `file://${RNFS.TemporaryDirectoryPath}/training/${moment().format('YYYYMMDDHHmmss')}.jpg`;
if (!requestAccessStoragePermission()) {
return;
}
await RNFS.copyFile(markedImage, tempPath);
const imageBase64 = await RNFS.readFile(tempPath, 'base64');
storePhoto(imageObject.user_id, imageObject.drop_point_id, tempPath, imageBase64, imageObject.lat, imageObject.lon)
reloadPhotos();
} catch (error) {
console.error('Error saving image to temporary folder:', error);
}
}
const renderImages = useMemo(() => images.map((image, index) => (
<>
<View key={index} style={styles.imageBlock}>
<TouchableRipple onPress={() => { handleOpenSheetImage(image.uri) }}>
<View style={styles.imageContainer}>
<Image
source={{ uri: image.uri }}
style={styles.image}
resizeMode="cover"
/>
</View>
</TouchableRipple>
</View>
<Button icon="delete" style={{ borderRadius: 10, backgroundColor: colors.semiRed, marginHorizontal: 5, marginBottom: 10 }} textColor={colors.beanRed} mode="contained-tonal" onPress={() => handleDeleteImage(index)}>
{strings('global.delete')}
</Button>
</>
)), [images]);
return (
<>
<StatusBar backgroundColor={colors.blue} barStyle='light-content' translucent={true} />
<Appbar.Header mode='center-aligned' style={{ backgroundColor: colors.blue, elevation: 4 }}>
<Appbar.BackAction color={colors.pureWhite} onPress={() => { navigation.goBack() }} />
<Appbar.Content titleStyle={{ fontWeight: 'bold' }} color={colors.pureWhite} title={strings('activity.training')} />
</Appbar.Header>
<View style={styles.container}>
<Text variant="bodySmall" style={{ color: colors.black, fontSize: 16 }}>
Pilih Jenis Pelatihan
</Text>
<ScrollView style={styles.listData}>
<View>
{dataTraining.map(item => (
<>
<Chip
icon={() => (
<Icon name={isItemSelected(item.label) ? 'circle-slice-8' : 'circle-outline'} size={20} color={isItemSelected(item.label) ? colors.pureWhite : colors.blue} />
)} textStyle={{ color: isItemSelected(item.label) ? colors.pureWhite : colors.blue }} onPress={() => handleCheckboxChange(item)} style={{ backgroundColor: isItemSelected(item.label) ? colors.beanRed : colors.semiBlue, marginBottom: 5 }}>{item.label}</Chip >
</>
))}
</View>
<KeyboardAvoidingView style={{ flex: 1 }} behavior={'padding'}>
<TextInput
style={{ marginTop: 10 }}
dense={true}
underlineColor={colors.amethystSmoke}
activeOutlineColor={colors.blue}
label="Deskripsi"
mode="outlined"
multiline={true}
numberOfLines={4}
/>
</KeyboardAvoidingView>
{renderImages}
</ScrollView >
<View style={{ width: '100%', marginTop: 10, marginBottom: 5 }}>
<Button icon="camera-plus" style={{ borderRadius: 10, backgroundColor: colors.semiBlue, marginHorizontal: 5, }} textColor={colors.blue} mode="contained-tonal" onPress={handleTakePicture}>
{strings('global.addImage')}
</Button>
</View>
<View style={styles.buttonContainer}>
<Button mode="outlined" style={styles.button} textColor={colors.mistBlue} onPress={() => { navigation.goBack() }} >
Kembali
</Button>
<Button mode="contained" style={[styles.button, { backgroundColor: colors.blue }]} onPress={() => console.log('Handle Saved')}>
Simpan
</Button>
</View>
</View >
<BottomSheetModalProvider>
<BottomSheetModal
ref={bottomSheetImage}
index={0}
snapPoints={['50%']}
>
<BottomSheetView style={{ alignItems: 'center' }} >
<Image
source={{ uri: selectedImageUri }}
style={styles.imageDetail}
resizeMode="cover"
/>
</BottomSheetView>
</BottomSheetModal>
</BottomSheetModalProvider>
</>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginVertical: 10,
marginHorizontal: 10
},
listData: {
flex: 1,
marginTop: 10,
},
button: {
flex: 1,
margin: 5,
borderRadius: 5
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: 10,
paddingBottom: 20,
backgroundColor: colors.pureWhite,
},
imageBlock: {
marginTop: 10,
marginBottom: 10,
alignItems: 'center',
},
imageContainer: {
flexDirection: 'row',
alignItems: 'center',
},
image: {
width: 330,
height: 150,
borderRadius: 7
},
imageDetail: {
width: 330,
height: 300,
borderRadius: 7
}
});

88
src/screens/activity/training/index.js

@ -0,0 +1,88 @@
import React, { useEffect, useCallback, useMemo, useState, useRef } from 'react';
import { Card, Text, TouchableRipple, Button, Appbar } from 'react-native-paper';
import { RefreshControl, StyleSheet, View, ScrollView, StatusBar } from 'react-native';
import { colors } from '../../../utils/color';
import Icon from 'react-native-vector-icons/AntDesign';
import { strings } from '../../../utils/i18n';
import moment from 'moment';
export default function TrainingActivityScreen({ route, navigation }) {
const data = [
{ id: 1, type: "Gada Pratama", position: "Manager", date: "Senin, 02-05-2024", startTime: "21:03", title: "Pengawalan", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tincidunt fringilla lobortis. Morbi suscipit massa mollis porttitor fringilla. Integer rutrum ipsum lorem, ut convallis nisl consequat nec. Proin vel elit vitae sapien convallis molestie. Donec id feugiat lectus. Aenean ut dui ut mi semper facilisis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nullam luctus convallis tellus, quis malesuada felis viverra mattis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Aliquam erat volutpat. Mauris eu posuere sapien. Aliquam in nisi at tortor faucibus interdum eget non quam. Aenean non elit ut leo malesuada porttitor.", visitor: "Farhan" },
{ id: 2, type: "Gada Utama", position: "Danru", date: "Selasa, 03-05-2024", startTime: "10:15", title: "Investigasi", description: "Morbi suscipit massa mollis porttitor fringilla. Integer rutrum ipsum lorem, ut convallis nisl consequat nec. Proin vel elit vitae sapien convallis molestie. Donec id feugiat lectus. Aenean ut dui ut mi semper facilisis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nullam luctus convallis tellus, quis malesuada felis viverra mattis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Aliquam erat volutpat. Mauris eu posuere sapien. Aliquam in nisi at tortor faucibus interdum eget non quam. Aenean non elit ut leo malesuada porttitor.", visitor: "Ibnu" },
{ id: 3, type: "Latihan Tongkat", position: "BKO Kepolisian", date: "Rabu, 04-05-2024", startTime: "15:20", title: "Sidang Pengadilan", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean non elit ut leo malesuada porttitor.", visitor: "Khaidir" },
];
return (
<View style={styles.container}>
<StatusBar backgroundColor={colors.blue} barStyle='light-content' translucent={true} />
<Appbar.Header mode='center-aligned' style={{ backgroundColor: colors.blue, elevation: 4 }}>
<Appbar.BackAction color={colors.pureWhite} onPress={() => { navigation.goBack() }} />
<Appbar.Content titleStyle={{ fontWeight: 'bold' }} color={colors.pureWhite} title={strings('activity.training')} />
</Appbar.Header>
<View style={{ width: '100%', marginTop: 10, marginBottom: 5 }}>
<Button icon="plus" style={{ borderRadius: 10, backgroundColor: colors.semiBlue, marginHorizontal: 5, }} textColor={colors.blue} mode="contained-tonal" onPress={() => { navigation.navigate('DialogFormTraining') }}>
{strings('activity.addTraining')}
</Button>
</View>
<ScrollView style={{ backgroundColor: colors.pureWhite }}>
{data.map((item) => (
<Card style={styles.card}>
<Card.Cover source={{ uri: 'https://picsum.photos/700' }} style={{ height: 130 }} resizeMode='cover' />
<Card.Content style={{ marginTop: 10 }}>
<Text variant="titleLarge" style={{ color: colors.black, fontWeight: '695' }}>Pelatihan</Text>
<View style={styles.row}>
<View style={{ backgroundColor: colors.semiBlue, borderRadius: 10, flexDirection: 'row', paddingHorizontal: 10, paddingVertical: 5 }}>
<Icon
source="check-circle"
size={20}
color={colors.blue}
/>
<Text variant="bodyMedium" style={{ color: colors.blue, textAlign: 'justify', paddingLeft: 5 }}>{item.type}</Text>
</View>
</View>
<View style={styles.row}>
<Text variant="bodyMedium" style={{ color: colors.black, fontWeight: '695' }}>Tanggal</Text>
<Text variant="bodyMedium" style={{ color: colors.amethystSmoke }}>{item.date}</Text>
</View>
<View style={styles.row}>
<Text variant="bodyMedium" style={{ color: colors.black, fontWeight: '695' }}>Waktu</Text>
<Text variant="bodyMedium" style={{ color: colors.amethystSmoke }}>{item.startTime}</Text>
</View>
<View style={styles.row}>
<Text variant="bodyMedium" style={{ color: colors.black, fontWeight: '695' }}>Deskripsi</Text>
</View>
<View style={styles.row}>
<Text variant="bodyMedium" style={{ color: colors.amethystSmoke, textAlign: 'justify' }}>{item.description}</Text>
</View>
</Card.Content>
</Card>
))}
</ScrollView>
</View >
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20,
backgroundColor: colors.pureWhite
},
card: {
flex: 1,
marginTop: 20,
marginHorizontal: 8,
marginVertical: 5,
backgroundColor: colors.pureWhite,
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 5,
},
shift: {
backgroundColor: colors.semiBlue,
borderRadius: 10,
padding: 5,
paddingHorizontal: 10
},
})
Loading…
Cancel
Save