80 lines
1.8 KiB
TypeScript
Raw Normal View History

import { ChangeEvent, KeyboardEvent, useEffect, useState } from "react";
import { useWaku } from "@waku/react";
import { LightNode } from "@waku/interfaces";
2022-06-17 10:48:15 +10:00
import {
TextInput,
TextComposer,
Row,
Fill,
Fit,
SendButton,
} from "@livechat/ui-kit";
interface Props {
hasLightPushPeers: boolean;
2022-06-17 10:48:15 +10:00
sendMessage: ((msg: string) => Promise<void>) | undefined;
}
export default function MessageInput(props: Props) {
const { hasLightPushPeers } = props;
const { node } = useWaku<LightNode>();
2022-06-17 10:48:15 +10:00
const [inputText, setInputText] = useState<string>("");
const [isActive, setActiveButton] = useState<boolean>(false);
2022-06-17 10:48:15 +10:00
const onMessage = async () => {
if (props.sendMessage && inputText) {
try {
await props.sendMessage(inputText);
} catch (e) {
console.error(`Failed to send message: ${e}`);
}
2022-06-17 10:48:15 +10:00
setInputText("");
}
};
const onChange = (event: ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
2022-06-17 10:48:15 +10:00
setInputText(event.target.value);
};
const onKeyDown = async (event: KeyboardEvent<HTMLInputElement>) => {
2022-06-17 10:48:15 +10:00
if (
isActive &&
2022-06-17 10:48:15 +10:00
event.key === "Enter" &&
!event.altKey &&
!event.ctrlKey &&
!event.shiftKey
) {
await onMessage();
2022-06-17 10:48:15 +10:00
}
};
// Enable the button if there are peers available or the user is sending a command
useEffect(() => {
if (inputText.startsWith("/") || hasLightPushPeers) {
setActiveButton(true);
} else if (node) {
setActiveButton(false);
}
}, [node, inputText, hasLightPushPeers]);
2022-06-17 10:48:15 +10:00
return (
<TextComposer
onKeyDown={onKeyDown}
onChange={onChange}
active={isActive}
onButtonClick={onMessage}
2022-06-17 10:48:15 +10:00
>
<Row align="center">
<Fill>
<TextInput />
2022-06-17 10:48:15 +10:00
</Fill>
<Fit>
<SendButton />
</Fit>
</Row>
</TextComposer>
);
}