Untitled
unknown
plain_text
10 months ago
4.9 kB
4
Indexable
import React, { useState, useEffect, useRef } from 'react'; import { View, Text, TextInput, Button, ScrollView, TouchableOpacity, Alert } from 'react-native'; import NetInfo from '@react-native-community/netinfo'; import DocumentPicker from 'react-native-document-picker'; import { WebSocket } from 'react-native'; interface Message { id?: string; sender: string; message?: string; attachment?: string; fileName?: string; created: string; isMe?: boolean; isRead?: boolean; error?: string; } const App: React.FC = () => { const [message, setMessage] = useState(''); const [attachment, setAttachment] = useState<DocumentPicker.DocumentPickerResponse | null>(null); const [messages, setMessages] = useState<Message[]>([]); const [connected, setConnected] = useState(false); const websocketRef = useRef<WebSocket | null>(null); const token = 'NjhRN045Q043TzZlMEduelZzR3cyZFdvbkNRMUtScnFJYkRGb1RoZzR2QUV3OHBGdUVBSUFxSzFPaTRqQU5TN2lQbVo5U2RqWE9lRkpLdThhS3gxYlE9PQ=='; const targetCustomerId = ''; const groupId = '1'; const reconnectInterval = 5000; useEffect(() => { const connectWebSocket = () => { websocketRef.current = new WebSocket(`wss://app.haroct.com.my/ws?token=${token}&targetCustomerId=${targetCustomerId}&groupId=${groupId}`); websocketRef.current.onopen = () => { console.log("Connection established!"); setConnected(true); }; websocketRef.current.onerror = (e) => { console.error("WebSocket error observed:", e); setConnected(false); }; websocketRef.current.onclose = (e) => { if (!e.wasClean) { console.error('Connection closed unexpectedly'); setTimeout(connectWebSocket, reconnectInterval); } setConnected(false); }; websocketRef.current.onmessage = (e) => { const data = JSON.parse(e.data) as Message; if (data.history) { setMessages(data.history); } else { setMessages(prevMessages => [...prevMessages, data]); } }; }; connectWebSocket(); return () => { if (websocketRef.current) { websocketRef.current.close(); } }; }, []); const sendMessage = () => { if (!message.trim() && !attachment) return; const payload: Message = { targetCustomerId: targetCustomerId, groupId: groupId, message: message.trim() ? message : null, attachment: null, fileName: null }; if (attachment) { payload.fileName = attachment.name; payload.attachment = attachment.uri; setAttachment(null); } setMessage(''); websocketRef.current?.send(JSON.stringify(payload)); }; const pickAttachment = async () => { try { const result = await DocumentPicker.pick({ type: [DocumentPicker.types.allFiles], }); setAttachment(result); } catch (err) { if (DocumentPicker.isCancel(err)) { // User cancelled the picker } else { throw err; } } }; const displayMessage = (data: Message) => { if (data.error) { Alert.alert("Error", data.error); return; } return ( <View key={data.id} style={{ padding: 10, backgroundColor: data.isMe ? '#d9f9b1' : '#ffffff', marginVertical: 5 }}> <Text><strong>{data.sender}:</strong> {data.message}</Text> {data.attachment && <Text><a href={data.attachment} target="_blank"><i className="fa fa-paperclip"></i> {data.fileName}</a></Text>} <Text style={{ color: 'gray', textAlign: 'right' }}>{data.created}</Text> </View> ); }; return ( <View style={{ flex: 1, padding: 20 }}> <ScrollView style={{ flex: 1 }} contentContainerStyle={{ paddingVertical: 20 }}> {messages.map(displayMessage)} </ScrollView> <TextInput style={{ height: 40, borderColor: 'gray', borderWidth: 1, marginBottom: 10 }} placeholder="Type a message" value={message} onChangeText={setMessage} /> <Button title="Pick Attachment" onPress={pickAttachment} /> {attachment && <Text>Attachment: {attachment.name}</Text>} <Button title="Send" onPress={sendMessage} disabled={!connected} /> </View> ); }; export default App;
Editor is loading...
Leave a Comment