Commit 8f472708 authored by Malsha Rathnasiri's avatar Malsha Rathnasiri

change formatting

parent f739c893
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from "react";
import { FlatList, StyleSheet, TextInput, SectionList, Button, ActivityIndicator, View, Text, SafeAreaView } from 'react-native'; import {
import { AudioRecorder } from '../components/AudioRecorder'; FlatList,
import _ from 'lodash' StyleSheet,
TextInput,
SectionList,
import EditScreenInfo from '../components/EditScreenInfo'; Button,
ActivityIndicator,
View,
Text,
SafeAreaView,
} from "react-native";
import { AudioRecorder } from "../components/AudioRecorder";
import _ from "lodash";
import EditScreenInfo from "../components/EditScreenInfo";
// import { Text, View } from '../components/Themed'; // import { Text, View } from '../components/Themed';
import { RootTabScreenProps } from '../types'; import { RootTabScreenProps } from "../types";
import { addChats, create, getList, getOne } from '../api/api'; import { addChats, create, getList, getOne } from "../api/api";
import { BACKEND_ADDRESS } from '../api/constants'; import { BACKEND_ADDRESS } from "../api/constants";
import Ionicons from '@expo/vector-icons/Ionicons'; import Ionicons from "@expo/vector-icons/Ionicons";
import { CONVO_DEFAULT_ICON_COLOR, styles } from '../util/styles'; import { CONVO_DEFAULT_ICON_COLOR, styles } from "../util/styles";
import { StatusBar } from 'expo-status-bar'; import { StatusBar } from "expo-status-bar";
import Slider from '@react-native-community/slider'; import Slider from "@react-native-community/slider";
import { PlayMessage } from '../components/PlayMessage'; import { PlayMessage } from "../components/PlayMessage";
import { Toast, Input } from 'native-base'; import { Toast, Input } from "native-base";
import { ERROR_TOAST_PROPS } from '../util/util'; import { ERROR_TOAST_PROPS } from "../util/util";
import AsyncStorage from '@react-native-async-storage/async-storage'; import AsyncStorage from "@react-native-async-storage/async-storage";
export default function ChatScreen({ navigation }) { export default function ChatScreen({ navigation }) {
const currentTime = new Date();
const currentTime = new Date()
const defaultChatData = [
const defaultChatData = [{ id: 1, from_user: 2, to_user: 1, message: 'How many passengers?', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 1).valueOf() }, {
{ id: 2, from_user: 1, to_user: 2, message: 'Three', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 2).valueOf(), is_detected: true }, id: 1,
{ id: 3, from_user: 2, to_user: 1, message: 'Should i turn left or right here?', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 3).valueOf(), is_detected: false }, from_user: 2,
{ id: 4, from_user: 1, to_user: 2, message: 'Left', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 4).valueOf(), is_detected: true }, to_user: 1,
{ id: 5, from_user: 1, to_user: 2, message: 'Please hurry', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 5).valueOf() }, message: "How many passengers?",
{ id: 6, from_user: 2, to_user: 1, message: 'Ok', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 6).valueOf() }, timestamp: currentTime.setMinutes(currentTime.getMinutes() - 1).valueOf(),
},
{
id: 2,
from_user: 1,
to_user: 2,
message: "Three",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 2).valueOf(),
is_detected: true,
},
{
id: 3,
from_user: 2,
to_user: 1,
message: "Should i turn left or right here?",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 3).valueOf(),
is_detected: false,
},
{
id: 4,
from_user: 1,
to_user: 2,
message: "Left",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 4).valueOf(),
is_detected: true,
},
{
id: 5,
from_user: 1,
to_user: 2,
message: "Please hurry",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 5).valueOf(),
},
{
id: 6,
from_user: 2,
to_user: 1,
message: "Ok",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 6).valueOf(),
},
// { from_user: 1, to_user: 2, message: 'msg1', timestamp: currentTime.setDate(currentTime.getDate() - 1).valueOf() }, // { from_user: 1, to_user: 2, message: 'msg1', timestamp: currentTime.setDate(currentTime.getDate() - 1).valueOf() },
// { from_user: 1, to_user: 2, message: 'msg2', timestamp: currentTime.setDate(currentTime.getDate() - 2).valueOf() }, // { from_user: 1, to_user: 2, message: 'msg2', timestamp: currentTime.setDate(currentTime.getDate() - 2).valueOf() },
// { from_user: 2, to_user: 1, message: 'msg3', timestamp: currentTime.setDate(currentTime.getDate() - 3).valueOf() }, // { from_user: 2, to_user: 1, message: 'msg3', timestamp: currentTime.setDate(currentTime.getDate() - 3).valueOf() },
// { from_user: 1, to_user: 2, message: 'msg4', timestamp: currentTime.setDate(currentTime.getDate() - 4).valueOf() }, // { from_user: 1, to_user: 2, message: 'msg4', timestamp: currentTime.setDate(currentTime.getDate() - 4).valueOf() },
// { from_user: 2, to_user: 1, message: 'msg5', timestamp: currentTime.setDate(currentTime.getDate() - 5).valueOf() }, // { from_user: 2, to_user: 1, message: 'msg5', timestamp: currentTime.setDate(currentTime.getDate() - 5).valueOf() },
] ];
const [detectedText, setDetectedText] = useState("") const [detectedText, setDetectedText] = useState("");
const [playinId, setPlayingId] = useState(3) const [playinId, setPlayingId] = useState(3);
const [chatDetails, setChatDetails] = useState() const [chatDetails, setChatDetails] = useState();
const [chats, setChats] = useState([]) const [chats, setChats] = useState([]);
const [input, setInput] = useState('test') const [input, setInput] = useState("test");
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true);
const loadSampleChats = () => { const loadSampleChats = () => {
const chats_ = defaultChatData//res.results const chats_ = defaultChatData; //res.results
const sections = [...new Set(chats_.map(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0)))]; const sections = [
const sectionChats = sections.map(section => { ...new Set(
console.log({ section }) chats_.map((chat) => new Date(chat.timestamp).setHours(0, 0, 0, 0))
return ({ ),
title: section, data: chats_.filter(chat => { ];
console.log({ chat }) const sectionChats = sections.map((section) => {
return (new Date(chat.timestamp).setHours(0, 0, 0, 0).valueOf() == section) console.log({ section });
}).sort((a, b) => { return (a.timestamp - b.timestamp) }) return {
}) title: section,
data: chats_
.filter((chat) => {
console.log({ chat });
return (
new Date(chat.timestamp).setHours(0, 0, 0, 0).valueOf() == section
);
}) })
console.log({ chats_, sections, sectionChats }) .sort((a, b) => {
setChats(sectionChats) return a.timestamp - b.timestamp;
console.log({ chats }) }),
} };
});
console.log({ chats_, sections, sectionChats });
setChats(sectionChats);
useEffect(() => { if (chatDetails) { loadChats(); setLoading(false) } }, [chatDetails]) console.log({ chats });
};
useEffect(() => {
if (chatDetails) {
loadChats();
setLoading(false);
}
}, [chatDetails]);
// const ws = new WebSocket(`ws://${BACKEND_ADDRESS}/chatSocket/`) // const ws = new WebSocket(`ws://${BACKEND_ADDRESS}/chatSocket/`)
useEffect(() => { useEffect(() => {
loadChatDetails() loadChatDetails();
// startWebsocket() // startWebsocket()
// loadSampleChats() // loadSampleChats()
}, []) }, []);
// const startWebsocket = () => { // const startWebsocket = () => {
// ws.onopen = () => { // ws.onopen = () => {
...@@ -94,56 +155,76 @@ export default function ChatScreen({ navigation }) { ...@@ -94,56 +155,76 @@ export default function ChatScreen({ navigation }) {
// } // }
const loadChatDetails = async () => { const loadChatDetails = async () => {
await getOne('conversations', 1).then(res => { await getOne("conversations", 1)
return res.json() .then((res) => {
}).then(res => { return res.json();
console.log(res) })
AsyncStorage.getItem('user_id').then((user_id) => { .then((res) => {
console.log('chat details', user_id) console.log(res);
AsyncStorage.getItem("user_id").then((user_id) => {
console.log("chat details", user_id);
//change from user and to user depending on the current user //change from user and to user depending on the current user
if (res.from_user == user_id) { if (res.from_user == user_id) {
setChatDetails(res) setChatDetails(res);
} } else {
else { const n_res = {
const n_res = { ...res, from_user: res.to_user, to_user: res.from_user } ...res,
setChatDetails(n_res) from_user: res.to_user,
} to_user: res.from_user,
}) };
setChatDetails(n_res);
})
} }
});
});
};
const loadChats = async () => { const loadChats = async () => {
await getList('chats').then(res => { await getList("chats")
return res.json() .then((res) => {
}).then(res => { return res.json();
console.log("load chats")
const chats = res.results || []
const sections = [...new Set(chats.map(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0)))];
const sectionChats = sections.map(section => ({ title: section, data: chats.filter(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0) == section) }))
setChats(sectionChats)
}) })
.then((res) => {
setLoading(false) console.log("load chats");
} const chats = res.results || [];
const sections = [
...new Set(
chats.map((chat) => new Date(chat.timestamp).setHours(0, 0, 0, 0))
),
];
const sectionChats = sections.map((section) => ({
title: section,
data: chats.filter(
(chat) => new Date(chat.timestamp).setHours(0, 0, 0, 0) == section
),
}));
setChats(sectionChats);
});
setLoading(false);
};
const onSendPress = () => { const onSendPress = () => {
try { try {
addChats({message: input, from_user: chatDetails.from_user, to_user: chatDetails.to_user, conversation: chatDetails.id }).then(response => { addChats({
message: input,
from_user: chatDetails.from_user,
to_user: chatDetails.to_user,
conversation: chatDetails.id,
}).then((response) => {
// console.log(response) // console.log(response)
}) });
setLoading(true) setLoading(true);
setInput('') setInput("");
loadChats() loadChats();
} } catch (e) {
catch (e) { Toast.show({
Toast.show({ title: 'Error sending message. try again!', ...ERROR_TOAST_PROPS }) title: "Error sending message. try again!",
} ...ERROR_TOAST_PROPS,
});
} }
};
return ( return (
<View style={styles.container}> <View style={styles.container}>
...@@ -153,71 +234,116 @@ export default function ChatScreen({ navigation }) { ...@@ -153,71 +234,116 @@ export default function ChatScreen({ navigation }) {
<EditScreenInfo path="/screens/TabOneScreen.tsx" /> */} <EditScreenInfo path="/screens/TabOneScreen.tsx" /> */}
<View style={{ flex: 1, width: '100%' }}> <View style={{ flex: 1, width: "100%" }}>
<View style={{ display: 'flex', flex: 0.9, justifyContent: 'space-between' }}> <View
style={{
display: "flex",
flex: 0.8,
justifyContent: "space-between",
}}
>
<StatusBar /> <StatusBar />
{loading ? <ActivityIndicator /> : {loading ? (
<ActivityIndicator />
) : (
<SectionList <SectionList
refreshing={loading} refreshing={loading}
onRefresh={() => { onRefresh={() => {
// loadChatDetails() //remove // loadChatDetails() //remove
loadChats() loadChats();
}} }}
sections={chats} sections={chats}
keyExtractor={(item, index) => item + index} keyExtractor={(item, index) => item + index}
renderItem={({ item }) => { renderItem={({ item }) => {
// console.log({ item }) // console.log({ item })
const timeString = new Date(item.timestamp).toLocaleTimeString() const timeString = new Date(
const time = timeString.slice(-11, -6) + " " + timeString.slice(-2) item.timestamp
).toLocaleTimeString();
const time =
timeString.slice(-11, -6) + " " + timeString.slice(-2);
return ( return (
<View style={{ margin: 5, padding: 5 }}><Text <View style={{ margin: 5, padding: 5 }}>
style={[{ textAlign: chatDetails.from_user == item.from_user ? 'right' : 'left', backgroundColor: chatDetails.from_user == item.from_user ? 'lightgray' : '#FFDE03', borderRadius: 5, padding: 5 }, <Text
chatDetails.from_user == item.from_user ? { marginLeft: 'auto' } : { marginRight: 'auto' } style={[
{
textAlign:
chatDetails.from_user == item.from_user
? "right"
: "left",
backgroundColor:
chatDetails.from_user == item.from_user
? "lightgray"
: "#FFDE03",
borderRadius: 5,
padding: 5,
},
chatDetails.from_user == item.from_user
? { marginLeft: "auto" }
: { marginRight: "auto" },
]} ]}
key={item.timestamp}>{item.message}</Text> key={item.timestamp}
<View style={{ flex: 1, flexDirection: chatDetails.from_user == item.from_user ? 'row-reverse' : 'row', textAlign: chatDetails.from_user == item.from_user ? 'right' : 'left' }}> >
<Text style={{ textAlign: chatDetails.from_user == item.from_user ? 'right' : 'left', color: 'gray', fontSize: 11 }}>{time}</Text> {item.message}
{item.is_detected && <Ionicons name="mic" size={15} color={CONVO_DEFAULT_ICON_COLOR} />} </Text>
{/* {chatDetails.to_user == item.from_user && item.id != playinId && <Ionicons name="play" size={15} style={styles.chatIcon} />} <View
{chatDetails.to_user == item.from_user && item.id == playinId && <Ionicons name="pause" size={15} style={styles.chatIcon} />} */} style={{
{chatDetails.to_user == item.from_user && <PlayMessage message={item.message} />} flex: 1,
</View> flexDirection:
{/* {item.id == playinId ? chatDetails.from_user == item.from_user
<Slider ? "row-reverse"
style={{ width: 200, height: 40, FborderRadius: 5, padding: 0, margin: 0 }} : "row",
minimumValue={0} textAlign:
maximumValue={1} chatDetails.from_user == item.from_user
value={0.67} ? "right"
: "left",
}}
>
<Text
style={{
textAlign:
chatDetails.from_user == item.from_user
? "right"
: "left",
color: "gray",
fontSize: 11,
}}
>
{time}
</Text>
{item.is_detected && (
<Ionicons
name="mic"
size={15}
color={CONVO_DEFAULT_ICON_COLOR}
/>
)}
minimumTrackTintColor="black" {chatDetails.to_user == item.from_user && (
maximumTrackTintColor="grey" <PlayMessage message={item.message} />
/> : null )}
} */}
</View> </View>
) </View>
);
}} }}
invertStickyHeaders invertStickyHeaders
inverted inverted
contentContainerStyle={{ flexDirection: 'column-reverse' }} contentContainerStyle={{ flexDirection: "column-reverse" }}
renderSectionHeader={({ section: { title } }) => { renderSectionHeader={({ section: { title } }) => {
var date = "" var date = "";
if (new Date(title).toLocaleDateString() == new Date().toLocaleDateString()) { if (
date = "Today" new Date(title).toLocaleDateString() ==
new Date().toLocaleDateString()
) {
date = "Today";
} }
// else if (new Date(title).toLocaleDateString() == new Date().setDate(new Date().getDate() - 1).toLocaleDateString()){
// date = "Yesterday"
// }
else { else {
date = new Date(title).toLocaleDateString() date = new Date(title).toLocaleDateString();
} }
return ( return <Text style={styles.header}>{date}</Text>;
<Text style={styles.header}>{date}</Text>
)
}} }}
/> />
} )}
{/* <FlatList {/* <FlatList
inverted={true} inverted={true}
style={{ alignContent: 'flex-end' }} style={{ alignContent: 'flex-end' }}
...@@ -234,31 +360,63 @@ export default function ChatScreen({ navigation }) { ...@@ -234,31 +360,63 @@ export default function ChatScreen({ navigation }) {
<Text style={{ textAlign: chatDetails.from == item.from ? 'right' : 'left', color: 'gray' }}>{new Date(item.time).toLocaleTimeString().slice(0, 5)}</Text></View> <Text style={{ textAlign: chatDetails.from == item.from ? 'right' : 'left', color: 'gray' }}>{new Date(item.time).toLocaleTimeString().slice(0, 5)}</Text></View>
) )
}} /> */} }} /> */}
</View>
<View style={{ flex: 0.075, padding: 0, backgroundColor: "white" }}>
<View
style={{ flexDirection: "row", display: "flex", height: "100%" }}
>
</View> </View>
<View style={{ flex: 0.075, padding: 0, backgroundColor: 'white' }}> <View
<View style={{ flexDirection: 'row', display: 'flex', height: '100%' }}> style={{ flexDirection: "row", display: "flex", height: "100%" }}
<SafeAreaView style={{ flex: 0.8, height: '100%', flexDirection: 'column-reverse' }}> >
<SafeAreaView
style={{
flex: 0.8,
height: "100%",
flexDirection: "column-reverse",
}}
>
{/* <TextInput {/* <TextInput
style={{ borderWidth: 2, borderColor: 'gray', color: 'black', marginHorizontal: 5, paddingHorizontal: 10, borderRadius: 5 }} style={{ borderWidth: 2, borderColor: 'gray', color: 'black', marginHorizontal: 5, paddingHorizontal: 10, borderRadius: 5 }}
defaultValue={input} defaultValue={input}
onChange={(e) => setInput(e.target.value)}></TextInput> */} onChange={(e) => setInput(e.target.value)}></TextInput> */}
<Input style={{}} value={input} w="100%" onChangeText={setInput} placeholder="" /> <Input
style={{}}
value={input}
w="100%"
onChangeText={setInput}
placeholder=""
/>
</SafeAreaView> </SafeAreaView>
{input ? {input ? (
<View style={{ flex: 0.2, height: '100%', flexDirection: 'column-reverse' }}> <View
<Button style={{ width: '100%', height: '100%' }} title='Send' onPress={onSendPress} /> style={{
flex: 0.2,
height: "100%",
flexDirection: "column-reverse",
}}
>
<Button
style={{ width: "100%", height: "100%" }}
title="Send"
onPress={onSendPress}
/>
</View> </View>
: ) : (
<View style={{ flex: 0.2, height: '100%', flexDirection: 'column-reverse' }}><AudioRecorder setDetectedText={setInput} /></View> <View
} style={{
flex: 0.2,
height: "100%",
flexDirection: "column-reverse",
}}
>
<AudioRecorder setDetectedText={setInput} />
</View>
)}
</View> </View>
</View> </View>
</View> </View>
</View> </View>
); );
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment