import React, { useState, useEffect, useRef } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faHeadset,
faXmark,
faMicrophone,
faMicrophoneSlash,
faPaperPlane,
faComment,
} from '@fortawesome/free-solid-svg-icons';
import useLex, { Message } from '../hooks/useLex';
import useTranscribeStreaming from '../hooks/useTranscribeStreaming';
import KendraContent from './KendraContent';
import { useForm } from 'react-hook-form';
import './Lex.css';
const BOT_ID = process.env.REACT_APP_BOT_ID!;
const BOT_ALIAS_ID = process.env.REACT_APP_BOT_ALIAS_ID!;
const IDENTITY_POOL_ID = process.env.REACT_APP_IDENTITY_POOL_ID!;
const REGION = process.env.REACT_APP_REGION!;
interface Text {
text: string;
}
interface MessageBoxProps {
message: Message;
idx: number;
}
function MessageBoxUser(props: MessageBoxProps) {
return (
<>
{props.message.contents.map((c, j) => {
return (
);
})}
>
);
}
function MessageBoxChatbot(props: MessageBoxProps) {
return (
<>
{props.message.contents.map((c, j) => {
return (
{c.contentType === 'PlainText' ? (
{c.content}
) : (
)}
);
})}
>
);
}
function MessageBox(props: { messages: Message[] }) {
return (
<>
{props.messages.map((m, idx) => {
if (m.user) {
return ;
} else {
return ;
}
})}
>
);
}
function Lex() {
const [expanded, setExpanded] = useState(false);
const [sessionStarted, setSessionStarted] = useState(false);
const [deletingSession, setDeletingSession] = useState(false);
const { register, handleSubmit, setValue } = useForm();
const { sendText, deleteSession, messages, waiting, sessionId } = useLex({
botId: BOT_ID,
botAliasId: BOT_ALIAS_ID,
localeId: 'ja_JP',
identityPoolId: IDENTITY_POOL_ID,
region: REGION,
});
const { transcripts, recording, startRecording, stopRecording } =
useTranscribeStreaming({
languageCode: 'ja-JP',
identityPoolId: IDENTITY_POOL_ID,
region: REGION,
});
useEffect(() => {
(async () => {
for (const t of transcripts) {
if (!t.isPartial) {
await sendText(t.transcripts.join(' '));
}
}
})();
// eslint-disable-next-line
}, [transcripts]);
// eslint-disable-next-line
useEffect(() => {
if (!sessionStarted && sessionId !== null) {
setSessionStarted(true);
}
if (sessionStarted && sessionId === null) {
setSessionStarted(false);
if (recording) {
stopRecording();
}
}
});
const onSubmit = async (data: Text) => {
if (data.text.length === 0) return;
setValue('text', '');
await sendText(data.text);
};
const expandButton = (
setExpanded(true)}
>
);
const messagesBottom = useRef(null);
useEffect(() => {
setTimeout(() => {
if (messagesBottom.current) {
messagesBottom.current.scrollIntoView({ behavior: 'smooth' });
}
}, 100);
}, [messages]);
const closeChatWindow = async (): Promise => {
setDeletingSession(true);
await deleteSession();
setExpanded(false);
setDeletingSession(false);
};
return (
{expanded ? (
<>
CHATBOT
{recording ? (
) : (
)}
{waiting}
>
) : (
expandButton
)}
{expanded && deletingSession && (
CHATBOT を終了しています...
)}
);
}
export default Lex;