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

change formatting

parent f739c893
import React, { useEffect, useState } from 'react'
import { FlatList, StyleSheet, TextInput, SectionList, Button, ActivityIndicator, View, Text, SafeAreaView } from 'react-native';
import { AudioRecorder } from '../components/AudioRecorder';
import _ from 'lodash'
import EditScreenInfo from '../components/EditScreenInfo';
import React, { useEffect, useState } from "react";
import {
FlatList,
StyleSheet,
TextInput,
SectionList,
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 { RootTabScreenProps } from '../types';
import { addChats, create, getList, getOne } from '../api/api';
import { BACKEND_ADDRESS } from '../api/constants';
import Ionicons from '@expo/vector-icons/Ionicons';
import { CONVO_DEFAULT_ICON_COLOR, styles } from '../util/styles';
import { StatusBar } from 'expo-status-bar';
import Slider from '@react-native-community/slider';
import { PlayMessage } from '../components/PlayMessage';
import { Toast, Input } from 'native-base';
import { ERROR_TOAST_PROPS } from '../util/util';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { RootTabScreenProps } from "../types";
import { addChats, create, getList, getOne } from "../api/api";
import { BACKEND_ADDRESS } from "../api/constants";
import Ionicons from "@expo/vector-icons/Ionicons";
import { CONVO_DEFAULT_ICON_COLOR, styles } from "../util/styles";
import { StatusBar } from "expo-status-bar";
import Slider from "@react-native-community/slider";
import { PlayMessage } from "../components/PlayMessage";
import { Toast, Input } from "native-base";
import { ERROR_TOAST_PROPS } from "../util/util";
import AsyncStorage from "@react-native-async-storage/async-storage";
export default function ChatScreen({ navigation }) {
const currentTime = new Date()
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: 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() },
const currentTime = new Date();
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: 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: '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: 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() },
]
];
const [detectedText, setDetectedText] = useState("")
const [detectedText, setDetectedText] = useState("");
const [playinId, setPlayingId] = useState(3)
const [chatDetails, setChatDetails] = useState()
const [playinId, setPlayingId] = useState(3);
const [chatDetails, setChatDetails] = useState();
const [chats, setChats] = useState([])
const [input, setInput] = useState('test')
const [loading, setLoading] = useState(true)
const [chats, setChats] = useState([]);
const [input, setInput] = useState("test");
const [loading, setLoading] = useState(true);
const loadSampleChats = () => {
const chats_ = defaultChatData//res.results
const sections = [...new Set(chats_.map(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0)))];
const sectionChats = sections.map(section => {
console.log({ section })
return ({
title: section, data: chats_.filter(chat => {
console.log({ chat })
return (new Date(chat.timestamp).setHours(0, 0, 0, 0).valueOf() == section)
}).sort((a, b) => { return (a.timestamp - b.timestamp) })
})
})
console.log({ chats_, sections, sectionChats })
setChats(sectionChats)
console.log({ chats })
}
useEffect(() => { if (chatDetails) { loadChats(); setLoading(false) } }, [chatDetails])
const chats_ = defaultChatData; //res.results
const sections = [
...new Set(
chats_.map((chat) => new Date(chat.timestamp).setHours(0, 0, 0, 0))
),
];
const sectionChats = sections.map((section) => {
console.log({ section });
return {
title: section,
data: chats_
.filter((chat) => {
console.log({ chat });
return (
new Date(chat.timestamp).setHours(0, 0, 0, 0).valueOf() == section
);
})
.sort((a, b) => {
return a.timestamp - b.timestamp;
}),
};
});
console.log({ chats_, sections, sectionChats });
setChats(sectionChats);
console.log({ chats });
};
useEffect(() => {
if (chatDetails) {
loadChats();
setLoading(false);
}
}, [chatDetails]);
// const ws = new WebSocket(`ws://${BACKEND_ADDRESS}/chatSocket/`)
useEffect(() => {
loadChatDetails()
loadChatDetails();
// startWebsocket()
// loadSampleChats()
}, [])
}, []);
// const startWebsocket = () => {
// ws.onopen = () => {
......@@ -94,56 +155,76 @@ export default function ChatScreen({ navigation }) {
// }
const loadChatDetails = async () => {
await getOne('conversations', 1).then(res => {
return res.json()
}).then(res => {
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
if (res.from_user == user_id) {
setChatDetails(res)
}
else {
const n_res = { ...res, from_user: res.to_user, to_user: res.from_user }
setChatDetails(n_res)
}
await getOne("conversations", 1)
.then((res) => {
return res.json();
})
})
}
.then((res) => {
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
if (res.from_user == user_id) {
setChatDetails(res);
} else {
const n_res = {
...res,
from_user: res.to_user,
to_user: res.from_user,
};
setChatDetails(n_res);
}
});
});
};
const loadChats = async () => {
await getList('chats').then(res => {
return res.json()
}).then(res => {
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)
}
await getList("chats")
.then((res) => {
return res.json();
})
.then((res) => {
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 = () => {
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)
})
setLoading(true)
setInput('')
loadChats()
});
setLoading(true);
setInput("");
loadChats();
} catch (e) {
Toast.show({
title: "Error sending message. try again!",
...ERROR_TOAST_PROPS,
});
}
catch (e) {
Toast.show({ title: 'Error sending message. try again!', ...ERROR_TOAST_PROPS })
}
}
};
return (
<View style={styles.container}>
......@@ -153,71 +234,116 @@ export default function ChatScreen({ navigation }) {
<EditScreenInfo path="/screens/TabOneScreen.tsx" /> */}
<View style={{ flex: 1, width: '100%' }}>
<View style={{ display: 'flex', flex: 0.9, justifyContent: 'space-between' }}>
<View style={{ flex: 1, width: "100%" }}>
<View
style={{
display: "flex",
flex: 0.8,
justifyContent: "space-between",
}}
>
<StatusBar />
{loading ? <ActivityIndicator /> :
{loading ? (
<ActivityIndicator />
) : (
<SectionList
refreshing={loading}
onRefresh={() => {
// loadChatDetails() //remove
loadChats()
loadChats();
}}
sections={chats}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => {
// console.log({ item })
const timeString = new Date(item.timestamp).toLocaleTimeString()
const time = timeString.slice(-11, -6) + " " + timeString.slice(-2)
const timeString = new Date(
item.timestamp
).toLocaleTimeString();
const time =
timeString.slice(-11, -6) + " " + timeString.slice(-2);
return (
<View style={{ margin: 5, padding: 5 }}><Text
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>
<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.is_detected && <Ionicons name="mic" size={15} color={CONVO_DEFAULT_ICON_COLOR} />}
{/* {chatDetails.to_user == item.from_user && item.id != playinId && <Ionicons name="play" size={15} style={styles.chatIcon} />}
{chatDetails.to_user == item.from_user && item.id == playinId && <Ionicons name="pause" size={15} style={styles.chatIcon} />} */}
{chatDetails.to_user == item.from_user && <PlayMessage message={item.message} />}
<View style={{ margin: 5, padding: 5 }}>
<Text
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>
<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.is_detected && (
<Ionicons
name="mic"
size={15}
color={CONVO_DEFAULT_ICON_COLOR}
/>
)}
{chatDetails.to_user == item.from_user && (
<PlayMessage message={item.message} />
)}
</View>
{/* {item.id == playinId ?
<Slider
style={{ width: 200, height: 40, FborderRadius: 5, padding: 0, margin: 0 }}
minimumValue={0}
maximumValue={1}
value={0.67}
minimumTrackTintColor="black"
maximumTrackTintColor="grey"
/> : null
} */}
</View>
)
);
}}
invertStickyHeaders
inverted
contentContainerStyle={{ flexDirection: 'column-reverse' }}
inverted
contentContainerStyle={{ flexDirection: "column-reverse" }}
renderSectionHeader={({ section: { title } }) => {
var date = ""
if (new Date(title).toLocaleDateString() == new Date().toLocaleDateString()) {
date = "Today"
var date = "";
if (
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 {
date = new Date(title).toLocaleDateString()
date = new Date(title).toLocaleDateString();
}
return (
<Text style={styles.header}>{date}</Text>
)
return <Text style={styles.header}>{date}</Text>;
}}
/>
}
)}
{/* <FlatList
inverted={true}
style={{ alignContent: 'flex-end' }}
......@@ -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>
)
}} /> */}
</View>
<View style={{ flex: 0.075, padding: 0, backgroundColor: 'white' }}>
<View style={{ flexDirection: 'row', display: 'flex', height: '100%' }}>
<SafeAreaView style={{ flex: 0.8, height: '100%', flexDirection: 'column-reverse' }}>
<View style={{ flex: 0.075, padding: 0, backgroundColor: "white" }}>
<View
style={{ flexDirection: "row", display: "flex", height: "100%" }}
>
</View>
<View
style={{ flexDirection: "row", display: "flex", height: "100%" }}
>
<SafeAreaView
style={{
flex: 0.8,
height: "100%",
flexDirection: "column-reverse",
}}
>
{/* <TextInput
style={{ borderWidth: 2, borderColor: 'gray', color: 'black', marginHorizontal: 5, paddingHorizontal: 10, borderRadius: 5 }}
defaultValue={input}
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>
{input ?
<View style={{ flex: 0.2, height: '100%', flexDirection: 'column-reverse' }}>
<Button style={{ width: '100%', height: '100%' }} title='Send' onPress={onSendPress} />
{input ? (
<View
style={{
flex: 0.2,
height: "100%",
flexDirection: "column-reverse",
}}
>
<Button
style={{ width: "100%", height: "100%" }}
title="Send"
onPress={onSendPress}
/>
</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>
);
}
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