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

Input and chat scroll layout, and disclaimer modal #5

Merged
merged 18 commits into from
Nov 24, 2023
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
88 changes: 88 additions & 0 deletions components/MessageContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import React, { useEffect, useRef } from 'react';
import { MessageState } from '@/types/chat';
import {
ChatBubbleLeftEllipsisIcon,
UserCircleIcon,
} from '@heroicons/react/24/solid';
import ReactMarkdown from 'react-markdown';
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from '@/components/ui/accordion';

import styles from '@/styles/Home.module.css';

export const MessageContainer: React.FC<{
loading: boolean;
messageState: MessageState;
}> = ({ loading, messageState }) => {
const messagesEndRef = useRef<HTMLDivElement>(null);

const { messages } = messageState;

useEffect(
() => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }),
[messages],
);

const apiMsgClass = 'bg-ec_blue_03 p-6 flex border-b border-b-slate-200';
const userMsgClass = (index: number) =>
loading && index === messages.length - 1
? styles.usermessagewaiting + ' flex'
: 'bg-white p-6 flex';

return (
<div className="overflow-y-auto scroll-smooth scroll-pe-6 scroll-pb-5 ">
{messages.map((message, index) => {
const className =
message.type === 'apiMessage' ? apiMsgClass : userMsgClass(index);
return (
<div key={`chatMessage-${index}`}>
<div className={`${className} border-b border-b-slate-200`}>
{message.type === 'apiMessage' ? (
<ChatBubbleLeftEllipsisIcon className="shrink-0 h-[24px] w-[24px] text-ec_blue mr-3" />
) : (
<UserCircleIcon className="shrink-0 h-[24px] w-[24px] text-slate-800 mr-3" />
)}
<div className={styles.markdownanswer + ' '}>
<ReactMarkdown linkTarget="_blank">
{message.message}
</ReactMarkdown>
</div>
</div>
{message.sourceDocs && (
<div className="" key={`sourceDocsAccordion-${index}`}>
<Accordion type="single" collapsible className="flex-col">
{message.sourceDocs.map((doc, index) => (
<div key={`messageSourceDocs-${index}`}>
<AccordionItem value={`item-${index}`}>
<AccordionTrigger>
<h3>Source {index + 1}</h3>
</AccordionTrigger>
<AccordionContent>
<ReactMarkdown linkTarget="_blank">
{doc.pageContent}
</ReactMarkdown>
<p className="mt-2">
<b>Source:</b> {doc.metadata.source}
</p>
<div className="text-xs">
I am an AI powered search tool, all data provided
should be fact checked
</div>
</AccordionContent>
</AccordionItem>
</div>
))}
</Accordion>
</div>
)}
</div>
);
})}
<div ref={messagesEndRef} className="h-4" />
</div>
);
};
171 changes: 171 additions & 0 deletions components/MessageInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import React, {
Dispatch,
SetStateAction,
useEffect,
useRef,
useState,
} from 'react';
import { MessageState } from '@/types/chat';
import styles from '@/styles/Home.module.css';
import LoadingDots from './ui/LoadingDots';

export const MessageInput: React.FC<{
loading: boolean;
setLoading: (loading: boolean) => void;
messageState: MessageState;
setMessageState: Dispatch<SetStateAction<MessageState>>;
}> = ({ loading, setLoading, messageState, setMessageState }) => {
const [query, setQuery] = useState<string>('');
const [error, setError] = useState<string | null>(null);

const { history } = messageState;

//handle form submission
async function handleSubmit(e: any) {
e.preventDefault();

setError(null);

if (!query) {
alert('Please input a question');
return;
}

const question = query.trim();

setMessageState((state) => ({
...state,
messages: [
...state.messages,
{
type: 'userMessage',
message: question,
},
],
}));

setLoading(true);
setQuery('');

try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
question,
history,
}),
});
const data = await response.json();
console.log('data', data);

if (data.error) {
setError(data.error);
} else {
setMessageState((state) => ({
...state,
messages: [
...state.messages,
{
type: 'apiMessage',
message: data.text,
sourceDocs: data.sourceDocuments,
},
],
history: [...state.history, [question, data.text]],
}));
}
console.log('messageState', messageState);

setLoading(false);

const appendResponse = await fetch('/api/appendQuestion', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ question }),
});

if (!appendResponse.ok) {
console.error('Failed to append question to CSV');
}
} catch (error) {
setLoading(false);
setError('An error occurred while fetching the data. Please try again.');
console.log('error', error);
}
}

const textAreaRef = useRef<HTMLTextAreaElement>(null);

useEffect(() => {
textAreaRef.current?.focus();
}, []);

//prevent empty submissions
const handleEnter = (e: any) => {
if (e.key === 'Enter' && query) {
handleSubmit(e);
} else if (e.key == 'Enter') {
e.preventDefault();
}
};

return (
<div
id="input-center"
className="flex justify-center align-center px-4 py-0 flex-row -order-1 my-[16px]"
>
{error && (
<div className="border border-red-400 rounded-md p-4">
<p className="text-red-500">{error}</p>
</div>
)}
<div className={styles.cloudform + ' relative w-full'}>
<form onSubmit={handleSubmit} className="relative w-full">
<textarea
disabled={loading}
onKeyDown={handleEnter}
ref={textAreaRef}
autoFocus={false}
rows={1}
maxLength={512}
id="userInput"
name="userInput"
placeholder={
loading ? 'Waiting for response...' : 'Ask a question...'
}
value={query}
onChange={(e) => setQuery(e.target.value)}
className={styles.textarea + ' relative w-full'}
/>
<button
type="submit"
disabled={loading}
className="bottom-5 right-4 text-neutral-400 bg-none p-1.5 border-none absolute "
>
{loading ? (
<div
className={styles.loadingwheel + ' bottom-2 right-3 absolute'}
>
<LoadingDots color="#003057" />
</div>
) : (
// Send icon SVG in input field
<svg
viewBox="0 0 20 20"
className={styles.svgicon}
xmlns="http://www.w3.org/2000/svg"
>
<path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"></path>
</svg>
)}
</button>
</form>
</div>
</div>
);
};
103 changes: 103 additions & 0 deletions components/Overlay.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { Dialog, Transition } from '@headlessui/react';
import { Fragment, useState } from 'react';
import { Disclaimers } from './ui/Disclaimers';

export default function LoadingModal() {
const [isOpen, setIsOpen] = useState(true);
const [disclaimersRead, setDisclaimersRead] = useState(false);

return (
<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={() => {}}>
<Transition.Child
as={Fragment}
enter="ease-out duration-200"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black/25" />
</Transition.Child>

<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-200 p-0 text-ec_blue text-left align-middle shadow-xl transition-all">
<Dialog.Title
as="h3"
className="text-lg text-center font-medium leading-6 px-6 pt-6 pb-3"
>
When decoding electoral guidance feels a bit like:
</Dialog.Title>
<div className="mt-2">
<div className="px-6 pb-3 width:100%;height:0;padding-bottom:100%;position:relative;">
<iframe
src="https://giphy.com/embed/BZNGgpMF2Nnx8nEO6q"
width="100%"
height="100%"
className="position:absolute giphy-embed"
allowFullScreen
></iframe>
</div>
<h2 className="px-6 pb-3">
Ask the (unofficial) chat bot to do the searching for you
</h2>
<div className="bg-white p-6 pb-3">
<h3 className=" text-gray-500">Disclaimers</h3>
<Disclaimers />
<div className="relative flex gap-x-3">
<div className="flex h-6 items-center">
<input
id="candidates"
name="candidates"
type="checkbox"
className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-600"
onClick={() => setDisclaimersRead(!disclaimersRead)}
/>
</div>
<div className="text-sm leading-6">
<label
htmlFor="candidates"
className="font-medium text-gray-900"
>
I have read and acknowledge the disclaimers
</label>
</div>
</div>
</div>
</div>

<div className="text-center bg-white p-6 pt-3">
{disclaimersRead ? (
<button
type="button"
className="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
onClick={() => setIsOpen(false)}
disabled={!disclaimersRead}
>
Get started!
</button>
) : (
<span className="italic text-sm">
Please acknowledge disclaimers to get started
</span>
)}
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
}
Loading