Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/issue-53 #57

Merged
merged 5 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file removed --header
Empty file.
Empty file removed --request
Empty file.
Empty file removed --verbose
Empty file.
4 changes: 3 additions & 1 deletion frontend/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"prettier",
"plugin:prettier/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/parser",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
Expand All @@ -19,7 +20,8 @@
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
"project": "./tsconfig.json"
"project": "./tsconfig.json",
"createDefaultProgram": true
},
"plugins": [
"prettier",
Expand Down
2 changes: 1 addition & 1 deletion frontend/.prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"semi": true,
"printWidth": 80,
"printWidth": 100,
"singleQuote": true,
"useTabs": true,
"tabWidth": 2,
Expand Down
6 changes: 5 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
"preview": "vite preview",
"format": "prettier --check --ignore-path .gitignore .",
"format:fix": "prettier --write --ignore-path .gitignore ."
},
"dependencies": {
"@emotion/react": "^11.11.3",
Expand All @@ -31,9 +33,11 @@
"eslint": "^8.56.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^17.1.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-standard-with-typescript": "^43.0.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-n": "^16.6.2",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
Expand Down
64 changes: 64 additions & 0 deletions frontend/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 3 additions & 6 deletions frontend/src/components/chat/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import useChatStore from '../../stores/useChatStore';
import { useChatStore } from '../../stores/useChatStore';
import { useEffect } from 'react';

const formatTime = (createdAt: Date) => {
Expand Down Expand Up @@ -31,13 +31,10 @@ const Chat: React.FC = () => {
const isLastMessageForWriter =
index === array.length - 1 ||
array[index + 1].writer !== message.writer ||
formatTime(array[index + 1].createdAt) !==
formatTime(message.createdAt);
formatTime(array[index + 1].createdAt) !== formatTime(message.createdAt);

const shouldDisplayYear =
index === 0 ||
formatDate(message.createdAt) !==
formatDate(array[index - 1].createdAt);
index === 0 || formatDate(message.createdAt) !== formatDate(array[index - 1].createdAt);

return (
<div key={message.id}>
Expand Down
138 changes: 70 additions & 68 deletions frontend/src/components/chat/ChatForm.tsx
Original file line number Diff line number Diff line change
@@ -1,106 +1,108 @@
import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useRef } from 'react';
import * as StompJs from '@stomp/stompjs';
import ChatRecent from './ChatRecent';
import { useChatStore } from '../../stores/useChatStore';

interface ChatMessage {
applyId: string;
chat: string;
}
type StompClient = StompJs.Client;

const ChatForm = () => {
const [chatList, setChatList] = useState<ChatMessage[]>([]);
const [chat, setChat] = useState<string>('');

const { apply_id } = useParams<{ apply_id: string }>();
const client = useRef<StompJs.Client | null>(null);

const newChatMessage: ChatMessage = {
applyId: 'User',
chat,
};
const { id, messages, inputMessage, setId, setMessages, setInputMessage } = useChatStore();
const client = useRef<StompClient | null>(null);

const connect = () => {
if (client.current) {
client.current.deactivate();
}
client.current = new StompJs.Client({
brokerURL: 'ws://localhost:8010/ws',
onConnect: () => {
console.log('success');
subscribe();
},
debug: (str) => {
debug: (str: string) => {
console.log(str);
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
});
client.current.activate();
};

const publish = (chat: string) => {
if (!client.current || !client.current.connected) return;

client.current.publish({
destination: '/app/chat/5/send-message',
body: JSON.stringify({
applyId: apply_id,
chat: chat,
}),
});
setChatList((prevChatList) => [...prevChatList, newChatMessage]);
setChat('');
client.current.activate();
};

const subscribe = () => {
if (!client.current) return;

client.current.subscribe(`/topic/public/5`, (body) => {
console.log('Received message:', body);
});
if (client.current) {
client.current.subscribe('/topic/public/5', (message: any) => {
const receivedMessage = JSON.parse(message.body);
setMessages((prevMessages) => [
...prevMessages,
{
content: receivedMessage.content,
sender: receivedMessage.sender,
},
]);
});
}
};

const disconnect = () => {
if (!client.current) return;
const connectId = () => {
connect();

client.current.deactivate();
return () => {
if (client.current) {
client.current.deactivate();
}
};
};

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setChat(event.target.value);
};
const sendMessage = () => {
if (client.current && inputMessage.trim() !== '') {
const message = {
content: inputMessage,
sender: id,
type: 'CHAT',
};

client.current.publish({
destination: '/app/chat/5/send-message',
body: JSON.stringify(message),
});

const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
event.preventDefault();
publish(chat);
setInputMessage('');
}
};

useEffect(() => {
connect();

return () => disconnect();
}, []);

return (
<div>
<ChatRecent />
<div className={'chat-list'}>
{chatList.map((chatMessage, index) => (
<div key={index}>{`${chatMessage.applyId}: ${chatMessage.chat}`}</div>
))}
<>
<div>
<div>
<ul>
{messages.map((msg, index) => (
<li key={index}>
<strong>{msg.sender} : </strong>
{msg.content}
</li>
))}
</ul>
</div>
<div>
<input
type="text"
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
sendMessage();
}
}}
/>
<button onClick={sendMessage}>Send</button>
</div>
</div>
<div>
<input
type={'text'}
name={'chatInput'}
onChange={handleChange}
value={chat}
placeholder="채팅을 입력해주세요"
onKeyDown={handleKeyDown}
/>
<input type="text" value={id} onChange={(e) => setId(e.target.value)} />
<button onClick={connectId}>Connect</button>
</div>
</div>
</>
);
};

Expand Down
Loading