From 23f7d1f78da66657311a859d80f4e1b5ab1f0514 Mon Sep 17 00:00:00 2001 From: urec56 Date: Wed, 14 Feb 2024 06:37:35 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D1=84=D1=80=D0=BE=D0=BD=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- front/src/chat/App.jsx | 21 +++-- front/src/chat/api.js | 22 ++++- front/src/chat/components/AppFooter.jsx | 11 --- front/src/chat/components/AppHeader.jsx | 13 --- front/src/chat/components/AppZalupa.jsx | 85 ------------------- front/src/chat/components/layout/AppChat.jsx | 72 ++++++++++++++++ .../src/chat/components/layout/AppContent.jsx | 14 ++- .../chat/components/layout/ChatMessage.jsx | 18 ++++ front/src/chat/components/layout/api.js | 34 ++++++++ 9 files changed, 170 insertions(+), 120 deletions(-) delete mode 100644 front/src/chat/components/AppFooter.jsx delete mode 100644 front/src/chat/components/AppHeader.jsx delete mode 100644 front/src/chat/components/AppZalupa.jsx create mode 100644 front/src/chat/components/layout/AppChat.jsx create mode 100644 front/src/chat/components/layout/ChatMessage.jsx create mode 100644 front/src/chat/components/layout/api.js diff --git a/front/src/chat/App.jsx b/front/src/chat/App.jsx index e06c02f..63703a8 100644 --- a/front/src/chat/App.jsx +++ b/front/src/chat/App.jsx @@ -3,15 +3,20 @@ import AppHeader from "./components/layout/AppHeader.jsx"; import AppFooter from "./components/layout/AppFooter.jsx"; import AppContent from "./components/layout/AppContent.jsx"; import AppZalupa from "./components/layout/AppZalupa.jsx"; +import ChatPage from "./components/layout/AppChat.jsx"; export default function App() { - return - - {/**/} - - - - - + return + + + + // + // + // {/**/} + // + // + // + // + // } diff --git a/front/src/chat/api.js b/front/src/chat/api.js index d8dbb38..1100cda 100644 --- a/front/src/chat/api.js +++ b/front/src/chat/api.js @@ -26,7 +26,7 @@ export function fetchAssets() { }) } -export async function fetchUsers() { +export function fetchUsers() { return (fetch('http://localhost:8000/api/users', { method: "GET" }) @@ -43,3 +43,23 @@ export async function fetchUsers() { ) } +export function fetchLastMessage() { + return (fetch('http://localhost:8000/api/chat/get_last_message/2', { + method: "GET", + credentials: "include" +}) + .then(function (res) { + return res.json(); + }) + .then(function (data) { + console.log(data); + return data; + }) + .catch(function (err) { + console.log('Ошибка:', err); + }) + ) +} + +let chat_id = 2 +export let ws = new WebSocket(`ws://localhost:8000/chat/ws/${chat_id}?user_id=1`); \ No newline at end of file diff --git a/front/src/chat/components/AppFooter.jsx b/front/src/chat/components/AppFooter.jsx deleted file mode 100644 index 7a6e5a9..0000000 --- a/front/src/chat/components/AppFooter.jsx +++ /dev/null @@ -1,11 +0,0 @@ -import {Layout} from "antd"; - -const footerStyle = { - textAlign: 'center', - color: '#fff', - backgroundColor: '#4096ff', -}; - -export default function () { - return (Footer) -} \ No newline at end of file diff --git a/front/src/chat/components/AppHeader.jsx b/front/src/chat/components/AppHeader.jsx deleted file mode 100644 index 8dddf7d..0000000 --- a/front/src/chat/components/AppHeader.jsx +++ /dev/null @@ -1,13 +0,0 @@ -import {Layout} from "antd"; - -const headerStyle = { - textAlign: 'center', - color: '#fff', - paddingInline: 48, - lineHeight: '64px', - backgroundColor: '#4096ff', -}; - -export default function () { - return (Header) -} diff --git a/front/src/chat/components/AppZalupa.jsx b/front/src/chat/components/AppZalupa.jsx deleted file mode 100644 index 9da1c44..0000000 --- a/front/src/chat/components/AppZalupa.jsx +++ /dev/null @@ -1,85 +0,0 @@ -import React, { useEffect, useState } from 'react'; -import { Avatar, Button, Skeleton, List} from 'antd'; - - -const count = 3; -const fakeDataUrl = `http://localhost:8000/api/users`; - -export default function () { - const [initLoading, setInitLoading] = useState(true); - const [loading, setLoading] = useState(false); - const [data, setData] = useState([]); - const [list, setList] = useState([]); - useEffect(() => { - fetch(fakeDataUrl) - .then((res) => res.json()) - .then((res) => { - setInitLoading(false); - setData(res.results); - setList(res.results); - }); - }, []); - const onLoadMore = () => { - setLoading(true); - setList( - data.concat( - [...new Array(count)].map(() => ({ - loading: true, - name: {}, - picture: {}, - })), - ), - ); - fetch(fakeDataUrl) - .then((res) => res.json()) - .then((res) => { - const newData = data.concat(res.results); - setData(newData); - setList(newData); - setLoading(false); - // Resetting window's offsetTop so as to display react-virtualized demo underfloor. - // In real scene, you can using public method of react-virtualized: - // https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized - window.dispatchEvent(new Event('resize')); - }); - }; - const loadMore = - !initLoading && !loading ? ( -
- -
- ) : null; - return ( - ( - edit, more]} - > - - } - title={{item.name?.last}} - description="Ant Design, a design language for background applications, is refined by Ant UED Team" - /> -
content
-
-
- )} - /> - ); -}; - - - diff --git a/front/src/chat/components/layout/AppChat.jsx b/front/src/chat/components/layout/AppChat.jsx new file mode 100644 index 0000000..d4a4fed --- /dev/null +++ b/front/src/chat/components/layout/AppChat.jsx @@ -0,0 +1,72 @@ +import React, { useState, useEffect } from 'react'; +import ChatMessage from './ChatMessage'; // Предполагается, что у вас есть компонент для отображения сообщений чата +import { getChatMessages, getUserData } from './api'; // Функции для получения данных из API + +function ChatPage() { + const [userData, setUserData] = useState(null); + const [messages, setMessages] = useState([]); + const [loading, setLoading] = useState(true); + + useEffect(() => { + // Получение данных пользователя из API + getUserData() + .then(data => { + setUserData(data); + }) + .catch(error => { + console.error('Error fetching user data:', error); + }); + }, []); + + useEffect(() => { + // Получение последних сообщений чата из API + getChatMessages() + .then(data => { + setMessages(data); + setLoading(false); + }) + .catch(error => { + console.error('Error fetching chat messages:', error); + setLoading(false); + }); + }, []); + + const loadMoreMessages = () => { + // Загрузка дополнительных сообщений из API + // Реализация этой функции зависит от вашего API и его пагинации + // Может потребоваться отслеживать текущую страницу сообщений и передавать ее в API запрос + }; + + return ( +
+ {/* Хедер с логотипом и данными пользователя */} +
+
Your Logo
+ {userData && ( +
+ User Avatar + {userData.username} +
+ )} +
+ + {/* Отображение сообщений чата */} +
+ {loading ? ( +

Loading messages...

+ ) : ( + <> + {messages.map(message => ( + + ))} + + + )} +
+ + {/* Дополнительный код и стили */} +
+ ); +} + +export default ChatPage; \ No newline at end of file diff --git a/front/src/chat/components/layout/AppContent.jsx b/front/src/chat/components/layout/AppContent.jsx index c24df99..34884ff 100644 --- a/front/src/chat/components/layout/AppContent.jsx +++ b/front/src/chat/components/layout/AppContent.jsx @@ -1,5 +1,5 @@ import {Layout, Spin} from "antd"; -import {fakeFetchCrypto, fetchAssets, fetchUsers} from "../../api.js"; +import {fakeFetchCrypto, fetchAssets, fetchUsers, fetchLastMessage, ws} from "../../api.js"; import {useEffect, useState} from "react"; @@ -19,20 +19,30 @@ export default function AppContent() { const [loading, setLoading] = useState(true) const [users, setUsers] = useState([]) const [assets, setAssets] = useState([]) + const [lastMessage, setMessage] = useState([]) + const [messages, setMessages] = useState([]) useEffect(() => { async function preload() { const result = await fetchUsers() + const message = await fetchLastMessage() + setMessage(message[0].message) setUsers(result) setLoading(false) } preload() }, []); + ws.onmessage = function (event) { + const data = JSON.parse(event.data) + setMessages(data.message); + }; if (loading) { return } - return ({users[0].email}) + return ( + {messages} + ) } diff --git a/front/src/chat/components/layout/ChatMessage.jsx b/front/src/chat/components/layout/ChatMessage.jsx new file mode 100644 index 0000000..7a00947 --- /dev/null +++ b/front/src/chat/components/layout/ChatMessage.jsx @@ -0,0 +1,18 @@ +import React from 'react'; + +function ChatMessage({ message }) { + return ( +
+
+ Sender Avatar + {message.id} +
+
+

{message.message}

+ {message.created_at} +
+
+ ); +} + +export default ChatMessage; diff --git a/front/src/chat/components/layout/api.js b/front/src/chat/components/layout/api.js new file mode 100644 index 0000000..ed86106 --- /dev/null +++ b/front/src/chat/components/layout/api.js @@ -0,0 +1,34 @@ +export async function getChatMessages() { + try { + const response = await fetch('http://localhost:8000/api/chat/get_some_messages/2?messages_count=0&messages_to_get=20', { + method: "GET", + credentials: "include" + }); + if (!response.ok) { + throw new Error('Failed to fetch chat messages'); + } + const data = await response.json(); + return data; + } catch (error) { + console.error('Error fetching chat messages:', error); + throw error; + } +} + +// Функция для получения данных пользователя из API +export async function getUserData() { + try { + const response = await fetch('http://localhost:8000/api/users/me', { + method: "GET", + credentials: "include" + }); + if (!response.ok) { + throw new Error('Failed to fetch user data'); + } + const data = await response.json(); + return data; + } catch (error) { + console.error('Error fetching user data:', error); + throw error; + } +} \ No newline at end of file