91 lines
2.5 KiB
JavaScript
91 lines
2.5 KiB
JavaScript
import {useEffect, useState} from 'react';
|
|
|
|
import {useClient} from '@/context/client.js';
|
|
|
|
import styles from './chat.module.css';
|
|
|
|
export default function Chat({
|
|
chatHistory,
|
|
onClose,
|
|
message,
|
|
setChatHistory,
|
|
setMessage,
|
|
}) {
|
|
const client = useClient();
|
|
const [disabled, setDisabled] = useState(true);
|
|
const [historyCaret, setHistoryCaret] = useState(0);
|
|
useEffect(() => {
|
|
setDisabled(false);
|
|
}, []);
|
|
return (
|
|
<div className={styles.chat}>
|
|
<form
|
|
onSubmit={(event) => {
|
|
if (message) {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'chat', value: message},
|
|
});
|
|
setChatHistory([message, ...chatHistory]);
|
|
setMessage('');
|
|
onClose();
|
|
}
|
|
event.preventDefault();
|
|
}}
|
|
>
|
|
<input
|
|
disabled={disabled}
|
|
onChange={(event) => {
|
|
setMessage(event.target.value);
|
|
}}
|
|
onKeyDown={(event) => {
|
|
switch (event.key) {
|
|
case 'ArrowDown': {
|
|
if (0 === historyCaret) {
|
|
break;
|
|
}
|
|
let localHistoryCaret = historyCaret - 1;
|
|
setMessage(chatHistory[localHistoryCaret])
|
|
setHistoryCaret(localHistoryCaret);
|
|
if (0 === localHistoryCaret) {
|
|
setChatHistory(chatHistory.slice(1));
|
|
}
|
|
break;
|
|
}
|
|
case 'ArrowUp': {
|
|
if (historyCaret === chatHistory.length - 1) {
|
|
break;
|
|
}
|
|
let localHistoryCaret = historyCaret;
|
|
let localChatHistory = chatHistory;
|
|
if (0 === historyCaret) {
|
|
localChatHistory = [message, ...localChatHistory];
|
|
setChatHistory(localChatHistory);
|
|
}
|
|
localHistoryCaret += 1;
|
|
setMessage(localChatHistory[localHistoryCaret])
|
|
setHistoryCaret(localHistoryCaret);
|
|
break;
|
|
}
|
|
case 'Escape': {
|
|
onClose();
|
|
break;
|
|
}
|
|
}
|
|
}}
|
|
onMouseDown={(event) => {
|
|
event.stopPropagation();
|
|
}}
|
|
maxLength="255"
|
|
ref={(element) => {
|
|
if (element) {
|
|
element.focus();
|
|
}
|
|
}}
|
|
type="text"
|
|
value={message}
|
|
/>
|
|
</form>
|
|
</div>
|
|
);
|
|
} |