bolt.diy/app/components/chat/BaseChat.tsx

327 lines
13 KiB
TypeScript
Raw Normal View History

// @ts-nocheck
// Preventing TS checks with files presented in the video for a better presentation.
import type { Message } from 'ai';
import React, { type RefCallback, useEffect } from 'react';
2024-07-10 16:44:39 +00:00
import { ClientOnly } from 'remix-utils/client-only';
import { Menu } from '~/components/sidebar/Menu.client';
import { IconButton } from '~/components/ui/IconButton';
import { Workbench } from '~/components/workbench/Workbench.client';
import { classNames } from '~/utils/classNames';
2024-11-14 12:29:47 +00:00
import { MODEL_LIST, DEFAULT_PROVIDER, PROVIDER_LIST, initializeModelList } from '~/utils/constants';
import { Messages } from './Messages.client';
2024-07-10 16:44:39 +00:00
import { SendButton } from './SendButton.client';
2024-10-15 14:15:02 +00:00
import { useState } from 'react';
import { APIKeyManager } from './APIKeyManager';
2024-10-29 03:19:30 +00:00
import Cookies from 'js-cookie';
2024-07-10 16:44:39 +00:00
import styles from './BaseChat.module.scss';
2024-11-14 12:29:47 +00:00
import type { ProviderInfo } from '~/utils/types';
const EXAMPLE_PROMPTS = [
{ text: 'Build a todo app in React using Tailwind' },
{ text: 'Build a simple blog using Astro' },
{ text: 'Create a cookie consent form using Material UI' },
{ text: 'Make a space invaders game' },
{ text: 'How do I center a div?' },
];
const providerList = PROVIDER_LIST;
2024-10-15 14:15:02 +00:00
const ModelSelector = ({ model, setModel, provider, setProvider, modelList, providerList }) => {
2024-10-15 14:15:02 +00:00
return (
<div className="mb-2 flex gap-2">
<select
2024-11-12 09:25:58 +00:00
value={provider?.name}
onChange={(e) => {
2024-11-15 20:28:36 +00:00
setProvider(providerList.find((p) => p.name === e.target.value));
const firstModel = [...modelList].find((m) => m.provider == e.target.value);
setModel(firstModel ? firstModel.name : '');
}}
className="flex-1 p-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus transition-all"
2024-10-15 14:15:02 +00:00
>
{providerList.map((provider) => (
<option key={provider.name} value={provider.name}>
{provider.name}
2024-10-15 14:15:02 +00:00
</option>
))}
</select>
<select
key={provider?.name}
2024-10-15 14:15:02 +00:00
value={model}
onChange={(e) => setModel(e.target.value)}
2024-11-15 20:28:36 +00:00
style={{ maxWidth: '70%' }}
className="flex-1 p-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus transition-all"
2024-10-15 14:15:02 +00:00
>
{[...modelList]
.filter((e) => e.provider == provider?.name && e.name)
.map((modelOption) => (
<option key={modelOption.name} value={modelOption.name}>
{modelOption.label}
</option>
))}
2024-10-15 14:15:02 +00:00
</select>
</div>
);
};
2024-10-15 14:15:02 +00:00
const TEXTAREA_MIN_HEIGHT = 76;
2024-07-10 16:44:39 +00:00
interface BaseChatProps {
textareaRef?: React.RefObject<HTMLTextAreaElement> | undefined;
2024-07-24 13:47:48 +00:00
messageRef?: RefCallback<HTMLDivElement> | undefined;
scrollRef?: RefCallback<HTMLDivElement> | undefined;
showChat?: boolean;
2024-07-10 16:44:39 +00:00
chatStarted?: boolean;
isStreaming?: boolean;
messages?: Message[];
2024-07-10 16:44:39 +00:00
enhancingPrompt?: boolean;
promptEnhanced?: boolean;
input?: string;
model?: string;
setModel?: (model: string) => void;
provider?: ProviderInfo;
setProvider?: (provider: ProviderInfo) => void;
handleStop?: () => void;
sendMessage?: (event: React.UIEvent, messageInput?: string) => void;
2024-07-10 16:44:39 +00:00
handleInputChange?: (event: React.ChangeEvent<HTMLTextAreaElement>) => void;
enhancePrompt?: () => void;
}
export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
(
{
textareaRef,
2024-07-24 13:47:48 +00:00
messageRef,
scrollRef,
showChat = true,
2024-07-10 16:44:39 +00:00
chatStarted = false,
isStreaming = false,
2024-07-10 16:44:39 +00:00
enhancingPrompt = false,
promptEnhanced = false,
messages,
2024-07-10 16:44:39 +00:00
input = '',
model,
setModel,
provider,
setProvider,
2024-07-10 16:44:39 +00:00
sendMessage,
handleInputChange,
enhancePrompt,
handleStop,
2024-07-10 16:44:39 +00:00
},
ref,
) => {
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
const [modelList, setModelList] = useState(MODEL_LIST);
useEffect(() => {
2024-10-29 03:19:30 +00:00
// Load API keys from cookies on component mount
try {
const storedApiKeys = Cookies.get('apiKeys');
if (storedApiKeys) {
const parsedKeys = JSON.parse(storedApiKeys);
if (typeof parsedKeys === 'object' && parsedKeys !== null) {
setApiKeys(parsedKeys);
}
}
} catch (error) {
console.error('Error loading API keys from cookies:', error);
// Clear invalid cookie data
Cookies.remove('apiKeys');
}
2024-11-15 20:28:36 +00:00
initializeModelList().then((modelList) => {
setModelList(modelList);
});
}, []);
const updateApiKey = (provider: string, key: string) => {
2024-10-29 03:19:30 +00:00
try {
const updatedApiKeys = { ...apiKeys, [provider]: key };
setApiKeys(updatedApiKeys);
// Save updated API keys to cookies with 30 day expiry and secure settings
Cookies.set('apiKeys', JSON.stringify(updatedApiKeys), {
expires: 30, // 30 days
secure: true, // Only send over HTTPS
sameSite: 'strict', // Protect against CSRF
path: '/', // Accessible across the site
2024-10-29 03:19:30 +00:00
});
} catch (error) {
console.error('Error saving API keys to cookies:', error);
}
};
2024-07-10 16:44:39 +00:00
return (
<div
ref={ref}
className={classNames(
styles.BaseChat,
'relative flex h-full w-full overflow-hidden bg-bolt-elements-background-depth-1',
)}
data-chat-visible={showChat}
>
2024-07-31 21:21:40 +00:00
<ClientOnly>{() => <Menu />}</ClientOnly>
<div ref={scrollRef} className="flex overflow-y-auto w-full h-full">
<div className={classNames(styles.Chat, 'flex flex-col flex-grow min-w-[var(--chat-min-width)] h-full')}>
2024-07-10 16:44:39 +00:00
{!chatStarted && (
<div id="intro" className="mt-[26vh] max-w-chat mx-auto text-center">
<h1 className="text-6xl font-bold text-bolt-elements-textPrimary mb-4 animate-fade-in">
Where ideas begin
</h1>
<p className="text-xl mb-8 text-bolt-elements-textSecondary animate-fade-in animation-delay-200">
Bring ideas to life in seconds or get help on existing projects.
</p>
2024-07-10 16:44:39 +00:00
</div>
)}
<div
className={classNames('pt-6 px-6', {
'h-full flex flex-col': chatStarted,
})}
2024-07-10 16:44:39 +00:00
>
<ClientOnly>
{() => {
return chatStarted ? (
<Messages
2024-07-24 13:47:48 +00:00
ref={messageRef}
className="flex flex-col w-full flex-1 max-w-chat px-4 pb-6 mx-auto z-1"
messages={messages}
isStreaming={isStreaming}
/>
) : null;
}}
</ClientOnly>
<div
2024-11-20 14:47:19 +00:00
className={classNames(
'bg-bolt-elements-background-depth-2 border-y border-bolt-elements-borderColor relative w-full max-w-chat mx-auto z-prompt',
{
'sticky bottom-0': chatStarted
})}
>
2024-10-15 14:15:02 +00:00
<ModelSelector
key={provider?.name + ':' + modelList.length}
2024-10-15 14:15:02 +00:00
model={model}
setModel={setModel}
modelList={modelList}
provider={provider}
setProvider={setProvider}
providerList={PROVIDER_LIST}
2024-10-15 14:15:02 +00:00
/>
2024-11-15 20:28:36 +00:00
{provider && (
2024-11-12 09:25:58 +00:00
<APIKeyManager
provider={provider}
apiKey={apiKeys[provider.name] || ''}
setApiKey={(key) => updateApiKey(provider.name, key)}
2024-11-15 20:28:36 +00:00
/>
)}
<div
className={classNames(
'shadow-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background backdrop-filter backdrop-blur-[8px] rounded-lg overflow-hidden transition-all',
)}
>
<textarea
ref={textareaRef}
className={`w-full pl-4 pt-4 pr-16 focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus resize-none text-md text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary bg-transparent transition-all`}
onKeyDown={(event) => {
if (event.key === 'Enter') {
if (event.shiftKey) {
return;
}
2024-07-10 16:44:39 +00:00
event.preventDefault();
2024-07-10 16:44:39 +00:00
sendMessage?.(event);
}
}}
value={input}
onChange={(event) => {
handleInputChange?.(event);
}}
style={{
minHeight: TEXTAREA_MIN_HEIGHT,
maxHeight: TEXTAREA_MAX_HEIGHT,
}}
placeholder="How can Bolt help you today?"
translate="no"
/>
<ClientOnly>
{() => (
<SendButton
show={input.length > 0 || isStreaming}
isStreaming={isStreaming}
onClick={(event) => {
if (isStreaming) {
handleStop?.();
return;
}
sendMessage?.(event);
}}
/>
)}
</ClientOnly>
<div className="flex justify-between items-center text-sm p-4 pt-2">
<div className="flex gap-1 items-center">
<IconButton
title="Enhance prompt"
disabled={input.length === 0 || enhancingPrompt}
className={classNames('transition-all', {
'opacity-100!': enhancingPrompt,
'text-bolt-elements-item-contentAccent! pr-1.5 enabled:hover:bg-bolt-elements-item-backgroundAccent!':
promptEnhanced,
})}
onClick={() => enhancePrompt?.()}
>
{enhancingPrompt ? (
<>
<div className="i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl animate-spin"></div>
<div className="ml-1.5">Enhancing prompt...</div>
</>
) : (
<>
<div className="i-bolt:stars text-xl"></div>
{promptEnhanced && <div className="ml-1.5">Prompt enhanced</div>}
</>
)}
</IconButton>
</div>
{input.length > 3 ? (
<div className="text-xs text-bolt-elements-textTertiary">
Use <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Shift</kbd> +{' '}
<kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Return</kbd> for
a new line
</div>
) : null}
2024-07-10 16:44:39 +00:00
</div>
</div>
<div className="bg-bolt-elements-background-depth-1 pb-6">{/* Ghost Element */}</div>
2024-07-10 16:44:39 +00:00
</div>
</div>
{!chatStarted && (
<div id="examples" className="relative w-full max-w-xl mx-auto mt-8 flex justify-center">
<div className="flex flex-col space-y-2 [mask-image:linear-gradient(to_bottom,black_0%,transparent_180%)] hover:[mask-image:none]">
{EXAMPLE_PROMPTS.map((examplePrompt, index) => {
return (
<button
key={index}
onClick={(event) => {
sendMessage?.(event, examplePrompt.text);
}}
className="group flex items-center w-full gap-2 justify-center bg-transparent text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary transition-theme"
>
{examplePrompt.text}
<div className="i-ph:arrow-bend-down-left" />
</button>
);
})}
</div>
</div>
)}
2024-07-10 16:44:39 +00:00
</div>
<ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
2024-07-10 16:44:39 +00:00
</div>
</div>
);
},
);