Skip to content

Commit

Permalink
feat: add in prettier and format code for consistency (#168)
Browse files Browse the repository at this point in the history
  • Loading branch information
srsholmes authored Mar 26, 2023
1 parent b843f6e commit d6973b9
Show file tree
Hide file tree
Showing 72 changed files with 1,139 additions and 4,572 deletions.
112 changes: 81 additions & 31 deletions components/Chat/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import { Conversation, ErrorMessage, KeyValuePair, Message, OpenAIModel } from "@/types";
import { FC, MutableRefObject, useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "next-i18next";
import { ChatInput } from "./ChatInput";
import { ChatLoader } from "./ChatLoader";
import { ChatMessage } from "./ChatMessage";
import { ErrorMessageDiv } from "./ErrorMessageDiv";
import { ModelSelect } from "./ModelSelect";
import { SystemPrompt } from "./SystemPrompt";
import {
Conversation,
ErrorMessage,
KeyValuePair,
Message,
OpenAIModel,
} from '@/types';
import {
FC,
MutableRefObject,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import { useTranslation } from 'next-i18next';
import { ChatInput } from './ChatInput';
import { ChatLoader } from './ChatLoader';
import { ChatMessage } from './ChatMessage';
import { ErrorMessageDiv } from './ErrorMessageDiv';
import { ModelSelect } from './ModelSelect';
import { SystemPrompt } from './SystemPrompt';

interface Props {
conversation: Conversation;
Expand All @@ -17,14 +30,31 @@ interface Props {
modelError: ErrorMessage | null;
messageError: boolean;
loading: boolean;
lightMode: "light" | "dark";
lightMode: 'light' | 'dark';
onSend: (message: Message, deleteCount?: number) => void;
onUpdateConversation: (conversation: Conversation, data: KeyValuePair) => void;
onUpdateConversation: (
conversation: Conversation,
data: KeyValuePair,
) => void;
onEditMessage: (message: Message, messageIndex: number) => void;
stopConversationRef: MutableRefObject<boolean>;
}

export const Chat: FC<Props> = ({ conversation, models, apiKey, serverSideApiKeyIsSet, messageIsStreaming, modelError, messageError, loading, lightMode, onSend, onUpdateConversation, onEditMessage, stopConversationRef }) => {
export const Chat: FC<Props> = ({
conversation,
models,
apiKey,
serverSideApiKeyIsSet,
messageIsStreaming,
modelError,
messageError,
loading,
lightMode,
onSend,
onUpdateConversation,
onEditMessage,
stopConversationRef,
}) => {
const { t } = useTranslation('chat');
const [currentMessage, setCurrentMessage] = useState<Message>();
const [autoScrollEnabled, setAutoScrollEnabled] = useState(true);
Expand All @@ -42,7 +72,8 @@ export const Chat: FC<Props> = ({ conversation, models, apiKey, serverSideApiKey

const handleScroll = () => {
if (chatContainerRef.current) {
const { scrollTop, scrollHeight, clientHeight } = chatContainerRef.current;
const { scrollTop, scrollHeight, clientHeight } =
chatContainerRef.current;
const bottomTolerance = 5;

if (scrollTop + clientHeight < scrollHeight - bottomTolerance) {
Expand All @@ -62,51 +93,70 @@ export const Chat: FC<Props> = ({ conversation, models, apiKey, serverSideApiKey
const chatContainer = chatContainerRef.current;

if (chatContainer) {
chatContainer.addEventListener("scroll", handleScroll);
chatContainer.addEventListener('scroll', handleScroll);

return () => {
chatContainer.removeEventListener("scroll", handleScroll);
chatContainer.removeEventListener('scroll', handleScroll);
};
}
}, []);

return (
<div className="relative flex-1 overflow-none dark:bg-[#343541] bg-white">
<div className="overflow-none relative flex-1 bg-white dark:bg-[#343541]">
{!(apiKey || serverSideApiKeyIsSet) ? (
<div className="flex flex-col justify-center mx-auto h-full w-[300px] sm:w-[500px] space-y-6">
<div className="text-2xl font-semibold text-center text-gray-800 dark:text-gray-100">{t('OpenAI API Key Required')}</div>
<div className="text-center text-gray-500 dark:text-gray-400">{t('Please set your OpenAI API key in the bottom left of the sidebar.')}</div>
<div className="mx-auto flex h-full w-[300px] flex-col justify-center space-y-6 sm:w-[500px]">
<div className="text-center text-2xl font-semibold text-gray-800 dark:text-gray-100">
{t('OpenAI API Key Required')}
</div>
<div className="text-center text-gray-500 dark:text-gray-400">
{t(
'Please set your OpenAI API key in the bottom left of the sidebar.',
)}
</div>
</div>
) : modelError ? <ErrorMessageDiv error={modelError} /> : (
) : modelError ? (
<ErrorMessageDiv error={modelError} />
) : (
<>
<div
className="overflow-scroll max-h-full"
ref={chatContainerRef}
>
<div className="max-h-full overflow-scroll" ref={chatContainerRef}>
{conversation.messages.length === 0 ? (
<>
<div className="flex flex-col mx-auto pt-12 space-y-10 w-[350px] sm:w-[600px]">
<div className="text-4xl font-semibold text-center text-gray-800 dark:text-gray-100">{models.length === 0 ? t("Loading...") : "Chatbot UI"}</div>
<div className="mx-auto flex w-[350px] flex-col space-y-10 pt-12 sm:w-[600px]">
<div className="text-center text-4xl font-semibold text-gray-800 dark:text-gray-100">
{models.length === 0 ? t('Loading...') : 'Chatbot UI'}
</div>

{models.length > 0 && (
<div className="flex flex-col h-full space-y-4 border p-4 rounded border-neutral-500">
<div className="flex h-full flex-col space-y-4 rounded border border-neutral-500 p-4">
<ModelSelect
model={conversation.model}
models={models}
onModelChange={(model) => onUpdateConversation(conversation, { key: "model", value: model })}
onModelChange={(model) =>
onUpdateConversation(conversation, {
key: 'model',
value: model,
})
}
/>

<SystemPrompt
conversation={conversation}
onChangePrompt={(prompt) => onUpdateConversation(conversation, { key: "prompt", value: prompt })}
onChangePrompt={(prompt) =>
onUpdateConversation(conversation, {
key: 'prompt',
value: prompt,
})
}
/>
</div>
)}
</div>
</>
) : (
<>
<div className="flex justify-center py-2 text-neutral-500 bg-neutral-100 dark:bg-[#444654] dark:text-neutral-200 text-sm border border-b-neutral-300 dark:border-none">{t('Model')}: {conversation.model.name}</div>
<div className="flex justify-center border border-b-neutral-300 bg-neutral-100 py-2 text-sm text-neutral-500 dark:border-none dark:bg-[#444654] dark:text-neutral-200">
{t('Model')}: {conversation.model.name}
</div>

{conversation.messages.map((message, index) => (
<ChatMessage
Expand All @@ -121,7 +171,7 @@ export const Chat: FC<Props> = ({ conversation, models, apiKey, serverSideApiKey
{loading && <ChatLoader />}

<div
className="bg-white dark:bg-[#343541] h-[162px]"
className="h-[162px] bg-white dark:bg-[#343541]"
ref={messagesEndRef}
/>
</>
Expand Down
99 changes: 60 additions & 39 deletions components/Chat/ChatInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { Message, OpenAIModel, OpenAIModelID } from "@/types";
import { IconPlayerStop, IconRepeat, IconSend } from "@tabler/icons-react";
import { FC, KeyboardEvent, MutableRefObject, useEffect, useState } from "react";
import { useTranslation } from "next-i18next";
import { Message, OpenAIModel, OpenAIModelID } from '@/types';
import { IconPlayerStop, IconRepeat, IconSend } from '@tabler/icons-react';
import {
FC,
KeyboardEvent,
MutableRefObject,
useEffect,
useState,
} from 'react';
import { useTranslation } from 'next-i18next';

interface Props {
messageIsStreaming: boolean;
Expand All @@ -13,7 +19,15 @@ interface Props {
textareaRef: MutableRefObject<HTMLTextAreaElement | null>;
}

export const ChatInput: FC<Props> = ({ messageIsStreaming, model, messages, onSend, onRegenerate, stopConversationRef, textareaRef }) => {
export const ChatInput: FC<Props> = ({
messageIsStreaming,
model,
messages,
onSend,
onRegenerate,
stopConversationRef,
textareaRef,
}) => {
const { t } = useTranslation('chat');
const [content, setContent] = useState<string>();
const [isTyping, setIsTyping] = useState<boolean>(false);
Expand All @@ -23,7 +37,12 @@ export const ChatInput: FC<Props> = ({ messageIsStreaming, model, messages, onSe
const maxLength = model.id === OpenAIModelID.GPT_3_5 ? 12000 : 24000;

if (value.length > maxLength) {
alert(t(`Message limit is {{maxLength}} characters. You have entered {{valueLength}} characters.`, { maxLength, valueLength: value.length }));
alert(
t(
`Message limit is {{maxLength}} characters. You have entered {{valueLength}} characters.`,
{ maxLength, valueLength: value.length },
),
);
return;
}

Expand All @@ -36,27 +55,29 @@ export const ChatInput: FC<Props> = ({ messageIsStreaming, model, messages, onSe
}

if (!content) {
alert(t("Please enter a message"));
alert(t('Please enter a message'));
return;
}

onSend({ role: "user", content });
setContent("");
onSend({ role: 'user', content });
setContent('');

if (window.innerWidth < 640 && textareaRef && textareaRef.current) {
textareaRef.current.blur();
}
};

const isMobile = () => {
const userAgent = typeof window.navigator === "undefined" ? "" : navigator.userAgent;
const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i;
const userAgent =
typeof window.navigator === 'undefined' ? '' : navigator.userAgent;
const mobileRegex =
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i;
return mobileRegex.test(userAgent);
};

const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (!isTyping) {
if (e.key === "Enter" && !e.shiftKey && !isMobile()) {
if (e.key === 'Enter' && !e.shiftKey && !isMobile()) {
e.preventDefault();
handleSend();
}
Expand All @@ -65,9 +86,11 @@ export const ChatInput: FC<Props> = ({ messageIsStreaming, model, messages, onSe

useEffect(() => {
if (textareaRef && textareaRef.current) {
textareaRef.current.style.height = "inherit";
textareaRef.current.style.height = 'inherit';
textareaRef.current.style.height = `${textareaRef.current?.scrollHeight}px`;
textareaRef.current.style.overflow = `${textareaRef?.current?.scrollHeight > 400 ? "auto" : "hidden"}`;
textareaRef.current.style.overflow = `${
textareaRef?.current?.scrollHeight > 400 ? 'auto' : 'hidden'
}`;
}
}, [content]);

Expand All @@ -79,45 +102,43 @@ export const ChatInput: FC<Props> = ({ messageIsStreaming, model, messages, onSe
}

return (
<div className="absolute bottom-0 left-0 w-full dark:border-white/20 border-transparent dark:bg-[#444654] dark:bg-gradient-to-t from-[#343541] via-[#343541] to-[#343541]/0 bg-white dark:!bg-transparent dark:bg-vert-dark-gradient pt-6 md:pt-2">
<div className="stretch mx-2 md:mt-[52px] mt-4 flex flex-row gap-3 last:mb-2 md:mx-4 md:last:mb-6 lg:mx-auto lg:max-w-3xl">
<div className="dark:bg-vert-dark-gradient absolute bottom-0 left-0 w-full border-transparent bg-white from-[#343541] via-[#343541] to-[#343541]/0 pt-6 dark:border-white/20 dark:bg-[#444654] dark:!bg-transparent dark:bg-gradient-to-t md:pt-2">
<div className="stretch mx-2 mt-4 flex flex-row gap-3 last:mb-2 md:mx-4 md:mt-[52px] md:last:mb-6 lg:mx-auto lg:max-w-3xl">
{messageIsStreaming && (
<button
className="absolute -top-2 md:top-0 left-0 right-0 mx-auto dark:bg-[#343541] border w-fit border-gray-500 py-2 px-4 rounded text-black dark:text-white hover:opacity-50"
className="absolute -top-2 left-0 right-0 mx-auto w-fit rounded border border-gray-500 py-2 px-4 text-black hover:opacity-50 dark:bg-[#343541] dark:text-white md:top-0"
onClick={handleStopConversation}
>
<IconPlayerStop
size={16}
className="inline-block mb-[2px]"
/>{" "}
<IconPlayerStop size={16} className="mb-[2px] inline-block" />{' '}
{t('Stop Generating')}
</button>
)}

{!messageIsStreaming && messages.length > 0 && (
<button
className="absolute -top-2 md:top-0 left-0 right-0 mx-auto dark:bg-[#343541] border w-fit border-gray-500 py-2 px-4 rounded text-black dark:text-white hover:opacity-50"
className="absolute -top-2 left-0 right-0 mx-auto w-fit rounded border border-gray-500 py-2 px-4 text-black hover:opacity-50 dark:bg-[#343541] dark:text-white md:top-0"
onClick={onRegenerate}
>
<IconRepeat
size={16}
className="inline-block mb-[2px]"
/>{" "}
{t("Regenerate response")}
<IconRepeat size={16} className="mb-[2px] inline-block" />{' '}
{t('Regenerate response')}
</button>
)}

<div className="flex flex-col w-full py-2 flex-grow md:py-3 md:pl-4 relative border border-black/10 bg-white dark:border-gray-900/50 dark:text-white dark:bg-[#40414F] rounded-md shadow-[0_0_10px_rgba(0,0,0,0.10)] dark:shadow-[0_0_15px_rgba(0,0,0,0.10)]">
<div className="relative flex w-full flex-grow flex-col rounded-md border border-black/10 bg-white py-2 shadow-[0_0_10px_rgba(0,0,0,0.10)] dark:border-gray-900/50 dark:bg-[#40414F] dark:text-white dark:shadow-[0_0_15px_rgba(0,0,0,0.10)] md:py-3 md:pl-4">
<textarea
ref={textareaRef}
className="text-black dark:text-white m-0 w-full resize-none outline-none border-0 bg-transparent p-0 pr-7 focus:ring-0 focus-visible:ring-0 dark:bg-transparent pl-2 md:pl-0"
className="m-0 w-full resize-none border-0 bg-transparent p-0 pr-7 pl-2 text-black outline-none focus:ring-0 focus-visible:ring-0 dark:bg-transparent dark:text-white md:pl-0"
style={{
resize: "none",
resize: 'none',
bottom: `${textareaRef?.current?.scrollHeight}px`,
maxHeight: "400px",
overflow: `${textareaRef.current && textareaRef.current.scrollHeight > 400 ? "auto" : "hidden"}`
maxHeight: '400px',
overflow: `${
textareaRef.current && textareaRef.current.scrollHeight > 400
? 'auto'
: 'hidden'
}`,
}}
placeholder={t("Type a message...") || ''}
placeholder={t('Type a message...') || ''}
value={content}
rows={1}
onCompositionStart={() => setIsTyping(true)}
Expand All @@ -127,13 +148,10 @@ export const ChatInput: FC<Props> = ({ messageIsStreaming, model, messages, onSe
/>

<button
className="absolute right-5 focus:outline-none text-neutral-800 hover:text-neutral-900 dark:text-neutral-100 dark:hover:text-neutral-200 dark:bg-opacity-50 hover:bg-neutral-200 p-1 rounded-sm"
className="absolute right-5 rounded-sm p-1 text-neutral-800 hover:bg-neutral-200 hover:text-neutral-900 focus:outline-none dark:bg-opacity-50 dark:text-neutral-100 dark:hover:text-neutral-200"
onClick={handleSend}
>
<IconSend
size={16}
className="opacity-60"
/>
<IconSend size={16} className="opacity-60" />
</button>
</div>
</div>
Expand All @@ -146,7 +164,10 @@ export const ChatInput: FC<Props> = ({ messageIsStreaming, model, messages, onSe
>
ChatBot UI
</a>
. {t("Chatbot UI is an advanced chatbot kit for OpenAI's chat models aiming to mimic ChatGPT's interface and functionality.")}
.{' '}
{t(
"Chatbot UI is an advanced chatbot kit for OpenAI's chat models aiming to mimic ChatGPT's interface and functionality.",
)}
</div>
</div>
);
Expand Down
12 changes: 6 additions & 6 deletions components/Chat/ChatLoader.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { IconDots } from "@tabler/icons-react";
import { FC } from "react";
import { IconDots } from '@tabler/icons-react';
import { FC } from 'react';

interface Props {}

export const ChatLoader: FC<Props> = () => {
return (
<div
className="group text-gray-800 dark:text-gray-100 border-b border-black/10 dark:border-gray-900/50 bg-gray-50 dark:bg-[#444654]"
style={{ overflowWrap: "anywhere" }}
className="group border-b border-black/10 bg-gray-50 text-gray-800 dark:border-gray-900/50 dark:bg-[#444654] dark:text-gray-100"
style={{ overflowWrap: 'anywhere' }}
>
<div className="text-base gap-4 md:gap-6 md:max-w-2xl lg:max-w-2xl xl:max-w-3xl p-4 md:py-6 flex lg:px-0 m-auto">
<div className="font-bold min-w-[40px]">AI:</div>
<div className="m-auto flex gap-4 p-4 text-base md:max-w-2xl md:gap-6 md:py-6 lg:max-w-2xl lg:px-0 xl:max-w-3xl">
<div className="min-w-[40px] font-bold">AI:</div>
<IconDots className="animate-pulse" />
</div>
</div>
Expand Down
Loading

1 comment on commit d6973b9

@vercel
Copy link

@vercel vercel bot commented on d6973b9 Mar 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.