Lint fixes

This commit is contained in:
eduardruzga
2024-11-23 00:29:16 +02:00
parent f6a7c4f5b5
commit 6e8aa04d27
10 changed files with 368 additions and 351 deletions

View File

@@ -19,7 +19,6 @@ import * as Tooltip from '@radix-ui/react-tooltip';
import styles from './BaseChat.module.scss'; import styles from './BaseChat.module.scss';
import type { ProviderInfo } from '~/utils/types'; import type { ProviderInfo } from '~/utils/types';
import WithTooltip from '~/components/ui/Tooltip';
import { ExportChatButton } from '~/components/chat/ExportChatButton'; import { ExportChatButton } from '~/components/chat/ExportChatButton';
const EXAMPLE_PROMPTS = [ const EXAMPLE_PROMPTS = [
@@ -27,7 +26,7 @@ const EXAMPLE_PROMPTS = [
{ text: 'Build a simple blog using Astro' }, { text: 'Build a simple blog using Astro' },
{ text: 'Create a cookie consent form using Material UI' }, { text: 'Create a cookie consent form using Material UI' },
{ text: 'Make a space invaders game' }, { text: 'Make a space invaders game' },
{ text: 'How do I center a div?' } { text: 'How do I center a div?' },
]; ];
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -110,7 +109,6 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
enhancingPrompt = false, enhancingPrompt = false,
promptEnhanced = false, promptEnhanced = false,
messages, messages,
description,
input = '', input = '',
model, model,
setModel, setModel,
@@ -121,9 +119,9 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
enhancePrompt, enhancePrompt,
handleStop, handleStop,
importChat, importChat,
exportChat exportChat,
}, },
ref ref,
) => { ) => {
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200; const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
const [apiKeys, setApiKeys] = useState<Record<string, string>>({}); const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
@@ -163,7 +161,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
expires: 30, // 30 days expires: 30, // 30 days
secure: true, // Only send over HTTPS secure: true, // Only send over HTTPS
sameSite: 'strict', // Protect against CSRF sameSite: 'strict', // Protect against CSRF
path: '/' // Accessible across the site path: '/', // Accessible across the site
}); });
} catch (error) { } catch (error) {
console.error('Error saving API keys to cookies:', error); console.error('Error saving API keys to cookies:', error);
@@ -176,7 +174,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
ref={ref} ref={ref}
className={classNames( className={classNames(
styles.BaseChat, styles.BaseChat,
'relative flex flex-col lg:flex-row h-full w-full overflow-hidden bg-bolt-elements-background-depth-1' 'relative flex flex-col lg:flex-row h-full w-full overflow-hidden bg-bolt-elements-background-depth-1',
)} )}
data-chat-visible={showChat} data-chat-visible={showChat}
> >
@@ -195,7 +193,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
)} )}
<div <div
className={classNames('pt-6 px-2 sm:px-6', { className={classNames('pt-6 px-2 sm:px-6', {
'h-full flex flex-col': chatStarted 'h-full flex flex-col': chatStarted,
})} })}
> >
<ClientOnly> <ClientOnly>
@@ -215,8 +213,8 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
'bg-bolt-elements-background-depth-2 p-3 rounded-lg border border-bolt-elements-borderColor relative w-full max-w-chat mx-auto z-prompt mb-6', 'bg-bolt-elements-background-depth-2 p-3 rounded-lg border border-bolt-elements-borderColor relative w-full max-w-chat mx-auto z-prompt mb-6',
{ {
'sticky bottom-2': chatStarted, 'sticky bottom-2': chatStarted,
}, },
)} )}
> >
<ModelSelector <ModelSelector
key={provider?.name + ':' + modelList.length} key={provider?.name + ':' + modelList.length}
@@ -226,45 +224,46 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
provider={provider} provider={provider}
setProvider={setProvider} setProvider={setProvider}
providerList={PROVIDER_LIST} providerList={PROVIDER_LIST}
apiKeys={apiKeys} apiKeys={apiKeys}
/> />
{provider && ( {provider && (
<APIKeyManager <APIKeyManager
provider={provider} provider={provider}
apiKey={apiKeys[provider.name] || ''} apiKey={apiKeys[provider.name] || ''}
setApiKey={(key) => updateApiKey(provider.name, key)}/> setApiKey={(key) => updateApiKey(provider.name, key)}
)} />
)}
<div <div
className={classNames( 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' 'shadow-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background backdrop-filter backdrop-blur-[8px] rounded-lg overflow-hidden transition-all',
)} )}
> >
<textarea <textarea
ref={textareaRef} ref={textareaRef}
className={`w-full pl-4 pt-4 pr-16 focus:outline-none focus:ring-0 focus:border-none focus:shadow-none resize-none text-md text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary bg-transparent transition-all`} className={`w-full pl-4 pt-4 pr-16 focus:outline-none focus:ring-0 focus:border-none focus:shadow-none resize-none text-md text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary bg-transparent transition-all`}
onKeyDown={(event) => { onKeyDown={(event) => {
if (event.key === 'Enter') { if (event.key === 'Enter') {
if (event.shiftKey) { if (event.shiftKey) {
return; return;
}
event.preventDefault();
sendMessage?.(event);
} }
}}
event.preventDefault(); value={input}
onChange={(event) => {
sendMessage?.(event); handleInputChange?.(event);
} }}
}} style={{
value={input} minHeight: TEXTAREA_MIN_HEIGHT,
onChange={(event) => { maxHeight: TEXTAREA_MAX_HEIGHT,
handleInputChange?.(event); }}
}} placeholder="How can Bolt help you today?"
style={{ translate="no"
minHeight: TEXTAREA_MIN_HEIGHT, />
maxHeight: TEXTAREA_MAX_HEIGHT
}}
placeholder="How can Bolt help you today?"
translate="no"
/>
<ClientOnly> <ClientOnly>
{() => ( {() => (
<SendButton <SendButton
@@ -289,14 +288,13 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
className={classNames('transition-all', { className={classNames('transition-all', {
'opacity-100!': enhancingPrompt, 'opacity-100!': enhancingPrompt,
'text-bolt-elements-item-contentAccent! pr-1.5 enabled:hover:bg-bolt-elements-item-backgroundAccent!': 'text-bolt-elements-item-contentAccent! pr-1.5 enabled:hover:bg-bolt-elements-item-backgroundAccent!':
promptEnhanced promptEnhanced,
})} })}
onClick={() => enhancePrompt?.()} onClick={() => enhancePrompt?.()}
> >
{enhancingPrompt ? ( {enhancingPrompt ? (
<> <>
<div <div className="i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl animate-spin"></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="ml-1.5">Enhancing prompt...</div>
</> </>
) : ( ) : (
@@ -306,15 +304,13 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
</> </>
)} )}
</IconButton> </IconButton>
<ClientOnly>{() => <ExportChatButton exportChat={exportChat}/>}</ClientOnly> <ClientOnly>{() => <ExportChatButton exportChat={exportChat} />}</ClientOnly>
</div> </div>
{input.length > 3 ? ( {input.length > 3 ? (
<div className="text-xs text-bolt-elements-textTertiary"> <div className="text-xs text-bolt-elements-textTertiary">
Use <kbd Use <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Shift</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>{' '}
<kbd for a new line
className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Return</kbd> for
a new line
</div> </div>
) : null} ) : null}
</div> </div>
@@ -331,25 +327,28 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
accept=".json" accept=".json"
onChange={async (e) => { onChange={async (e) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (file && importChat) { if (file && importChat) {
try { try {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = async (e) => { reader.onload = async (e) => {
try { try {
const content = e.target?.result as string; const content = e.target?.result as string;
const data = JSON.parse(content); const data = JSON.parse(content);
if (!Array.isArray(data.messages)) { if (!Array.isArray(data.messages)) {
toast.error('Invalid chat file format'); toast.error('Invalid chat file format');
} }
await importChat(data.description, data.messages); await importChat(data.description, data.messages);
toast.success('Chat imported successfully'); toast.success('Chat imported successfully');
} catch (error) { } catch (error) {
toast.error('Failed to parse chat file'); toast.error('Failed to parse chat file: ' + error.message);
} }
}; };
reader.onerror = () => toast.error('Failed to read chat file'); reader.onerror = () => toast.error('Failed to read chat file');
reader.readAsText(file); reader.readAsText(file);
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to import chat'); toast.error(error instanceof Error ? error.message : 'Failed to import chat');
} }
@@ -377,8 +376,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
)} )}
{!chatStarted && ( {!chatStarted && (
<div id="examples" className="relative w-full max-w-xl mx-auto mt-8 flex justify-center"> <div id="examples" className="relative w-full max-w-xl mx-auto mt-8 flex justify-center">
<div <div className="flex flex-col space-y-2 [mask-image:linear-gradient(to_bottom,black_0%,transparent_180%)] hover:[mask-image:none]">
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) => { {EXAMPLE_PROMPTS.map((examplePrompt, index) => {
return ( return (
<button <button
@@ -402,5 +400,5 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
</div> </div>
</Tooltip.Provider> </Tooltip.Provider>
); );
} },
); );

View File

@@ -35,7 +35,15 @@ export function Chat() {
return ( return (
<> <>
{ready && <ChatImpl description={title} initialMessages={initialMessages} exportChat={exportChat} storeMessageHistory={storeMessageHistory} importChat={importChat} />} {ready && (
<ChatImpl
description={title}
initialMessages={initialMessages}
exportChat={exportChat}
storeMessageHistory={storeMessageHistory}
importChat={importChat}
/>
)}
<ToastContainer <ToastContainer
closeButton={({ closeToast }) => { closeButton={({ closeToast }) => {
return ( return (
@@ -74,217 +82,219 @@ interface ChatProps {
exportChat: () => void; exportChat: () => void;
} }
export const ChatImpl = memo(({ description, initialMessages, storeMessageHistory, importChat, exportChat }: ChatProps) => { export const ChatImpl = memo(
useShortcuts(); ({ description, initialMessages, storeMessageHistory, importChat, exportChat }: ChatProps) => {
useShortcuts();
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
const [chatStarted, setChatStarted] = useState(initialMessages.length > 0); const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
const [model, setModel] = useState(() => { const [model, setModel] = useState(() => {
const savedModel = Cookies.get('selectedModel'); const savedModel = Cookies.get('selectedModel');
return savedModel || DEFAULT_MODEL; return savedModel || DEFAULT_MODEL;
}); });
const [provider, setProvider] = useState(() => { const [provider, setProvider] = useState(() => {
const savedProvider = Cookies.get('selectedProvider'); const savedProvider = Cookies.get('selectedProvider');
return PROVIDER_LIST.find((p) => p.name === savedProvider) || DEFAULT_PROVIDER; return PROVIDER_LIST.find((p) => p.name === savedProvider) || DEFAULT_PROVIDER;
}); });
const { showChat } = useStore(chatStore); const { showChat } = useStore(chatStore);
const [animationScope, animate] = useAnimate(); const [animationScope, animate] = useAnimate();
const [apiKeys, setApiKeys] = useState<Record<string, string>>({}); const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({ const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({
api: '/api/chat', api: '/api/chat',
body: { body: {
apiKeys, apiKeys,
}, },
onError: (error) => { onError: (error) => {
logger.error('Request failed\n\n', error); logger.error('Request failed\n\n', error);
toast.error( toast.error(
'There was an error processing your request: ' + (error.message ? error.message : 'No details were returned'), 'There was an error processing your request: ' + (error.message ? error.message : 'No details were returned'),
);
},
onFinish: () => {
logger.debug('Finished streaming');
},
initialMessages,
});
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
const { parsedMessages, parseMessages } = useMessageParser();
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
useEffect(() => {
chatStore.setKey('started', initialMessages.length > 0);
}, []);
useEffect(() => {
parseMessages(messages, isLoading);
if (messages.length > initialMessages.length) {
storeMessageHistory(messages).catch((error) => toast.error(error.message));
}
}, [messages, isLoading, parseMessages]);
const scrollTextArea = () => {
const textarea = textareaRef.current;
if (textarea) {
textarea.scrollTop = textarea.scrollHeight;
}
};
const abort = () => {
stop();
chatStore.setKey('aborted', true);
workbenchStore.abortAllActions();
};
useEffect(() => {
const textarea = textareaRef.current;
if (textarea) {
textarea.style.height = 'auto';
const scrollHeight = textarea.scrollHeight;
textarea.style.height = `${Math.min(scrollHeight, TEXTAREA_MAX_HEIGHT)}px`;
textarea.style.overflowY = scrollHeight > TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';
}
}, [input, textareaRef]);
const runAnimation = async () => {
if (chatStarted) {
return;
}
await Promise.all([
animate('#examples', { opacity: 0, display: 'none' }, { duration: 0.1 }),
animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn }),
]);
chatStore.setKey('started', true);
setChatStarted(true);
};
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
const _input = messageInput || input;
if (_input.length === 0 || isLoading) {
return;
}
/**
* @note (delm) Usually saving files shouldn't take long but it may take longer if there
* many unsaved files. In that case we need to block user input and show an indicator
* of some kind so the user is aware that something is happening. But I consider the
* happy case to be no unsaved files and I would expect users to save their changes
* before they send another message.
*/
await workbenchStore.saveAllFiles();
const fileModifications = workbenchStore.getFileModifcations();
chatStore.setKey('aborted', false);
runAnimation();
if (fileModifications !== undefined) {
const diff = fileModificationsToHTML(fileModifications);
/**
* If we have file modifications we append a new user message manually since we have to prefix
* the user input with the file modifications and we don't want the new user input to appear
* in the prompt. Using `append` is almost the same as `handleSubmit` except that we have to
* manually reset the input and we'd have to manually pass in file attachments. However, those
* aren't relevant here.
*/
append({ role: 'user', content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${diff}\n\n${_input}` });
/**
* After sending a new message we reset all modifications since the model
* should now be aware of all the changes.
*/
workbenchStore.resetAllFileModifications();
} else {
append({ role: 'user', content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}` });
}
setInput('');
resetEnhancer();
textareaRef.current?.blur();
};
const [messageRef, scrollRef] = useSnapScroll();
useEffect(() => {
const storedApiKeys = Cookies.get('apiKeys');
if (storedApiKeys) {
setApiKeys(JSON.parse(storedApiKeys));
}
}, []);
const handleModelChange = (newModel: string) => {
setModel(newModel);
Cookies.set('selectedModel', newModel, { expires: 30 });
};
const handleProviderChange = (newProvider: ProviderInfo) => {
setProvider(newProvider);
Cookies.set('selectedProvider', newProvider.name, { expires: 30 });
};
return (
<BaseChat
ref={animationScope}
textareaRef={textareaRef}
input={input}
showChat={showChat}
chatStarted={chatStarted}
isStreaming={isLoading}
enhancingPrompt={enhancingPrompt}
promptEnhanced={promptEnhanced}
sendMessage={sendMessage}
model={model}
setModel={handleModelChange}
provider={provider}
setProvider={handleProviderChange}
messageRef={messageRef}
scrollRef={scrollRef}
handleInputChange={handleInputChange}
handleStop={abort}
description={description}
importChat={importChat}
exportChat={exportChat}
messages={messages.map((message, i) => {
if (message.role === 'user') {
return message;
}
return {
...message,
content: parsedMessages[i] || '',
};
})}
enhancePrompt={() => {
enhancePrompt(
input,
(input) => {
setInput(input);
scrollTextArea();
},
model,
provider,
apiKeys,
); );
}} },
/> onFinish: () => {
); logger.debug('Finished streaming');
}); },
initialMessages,
});
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
const { parsedMessages, parseMessages } = useMessageParser();
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
useEffect(() => {
chatStore.setKey('started', initialMessages.length > 0);
}, []);
useEffect(() => {
parseMessages(messages, isLoading);
if (messages.length > initialMessages.length) {
storeMessageHistory(messages).catch((error) => toast.error(error.message));
}
}, [messages, isLoading, parseMessages]);
const scrollTextArea = () => {
const textarea = textareaRef.current;
if (textarea) {
textarea.scrollTop = textarea.scrollHeight;
}
};
const abort = () => {
stop();
chatStore.setKey('aborted', true);
workbenchStore.abortAllActions();
};
useEffect(() => {
const textarea = textareaRef.current;
if (textarea) {
textarea.style.height = 'auto';
const scrollHeight = textarea.scrollHeight;
textarea.style.height = `${Math.min(scrollHeight, TEXTAREA_MAX_HEIGHT)}px`;
textarea.style.overflowY = scrollHeight > TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';
}
}, [input, textareaRef]);
const runAnimation = async () => {
if (chatStarted) {
return;
}
await Promise.all([
animate('#examples', { opacity: 0, display: 'none' }, { duration: 0.1 }),
animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn }),
]);
chatStore.setKey('started', true);
setChatStarted(true);
};
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
const _input = messageInput || input;
if (_input.length === 0 || isLoading) {
return;
}
/**
* @note (delm) Usually saving files shouldn't take long but it may take longer if there
* many unsaved files. In that case we need to block user input and show an indicator
* of some kind so the user is aware that something is happening. But I consider the
* happy case to be no unsaved files and I would expect users to save their changes
* before they send another message.
*/
await workbenchStore.saveAllFiles();
const fileModifications = workbenchStore.getFileModifcations();
chatStore.setKey('aborted', false);
runAnimation();
if (fileModifications !== undefined) {
const diff = fileModificationsToHTML(fileModifications);
/**
* If we have file modifications we append a new user message manually since we have to prefix
* the user input with the file modifications and we don't want the new user input to appear
* in the prompt. Using `append` is almost the same as `handleSubmit` except that we have to
* manually reset the input and we'd have to manually pass in file attachments. However, those
* aren't relevant here.
*/
append({ role: 'user', content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${diff}\n\n${_input}` });
/**
* After sending a new message we reset all modifications since the model
* should now be aware of all the changes.
*/
workbenchStore.resetAllFileModifications();
} else {
append({ role: 'user', content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}` });
}
setInput('');
resetEnhancer();
textareaRef.current?.blur();
};
const [messageRef, scrollRef] = useSnapScroll();
useEffect(() => {
const storedApiKeys = Cookies.get('apiKeys');
if (storedApiKeys) {
setApiKeys(JSON.parse(storedApiKeys));
}
}, []);
const handleModelChange = (newModel: string) => {
setModel(newModel);
Cookies.set('selectedModel', newModel, { expires: 30 });
};
const handleProviderChange = (newProvider: ProviderInfo) => {
setProvider(newProvider);
Cookies.set('selectedProvider', newProvider.name, { expires: 30 });
};
return (
<BaseChat
ref={animationScope}
textareaRef={textareaRef}
input={input}
showChat={showChat}
chatStarted={chatStarted}
isStreaming={isLoading}
enhancingPrompt={enhancingPrompt}
promptEnhanced={promptEnhanced}
sendMessage={sendMessage}
model={model}
setModel={handleModelChange}
provider={provider}
setProvider={handleProviderChange}
messageRef={messageRef}
scrollRef={scrollRef}
handleInputChange={handleInputChange}
handleStop={abort}
description={description}
importChat={importChat}
exportChat={exportChat}
messages={messages.map((message, i) => {
if (message.role === 'user') {
return message;
}
return {
...message,
content: parsedMessages[i] || '',
};
})}
enhancePrompt={() => {
enhancePrompt(
input,
(input) => {
setInput(input);
scrollTextArea();
},
model,
provider,
apiKeys,
);
}}
/>
);
},
);

View File

@@ -2,13 +2,12 @@ import WithTooltip from '~/components/ui/Tooltip';
import { IconButton } from '~/components/ui/IconButton'; import { IconButton } from '~/components/ui/IconButton';
import React from 'react'; import React from 'react';
export const ExportChatButton = ({exportChat}: {exportChat: () => void}) => { export const ExportChatButton = ({ exportChat }: { exportChat: () => void }) => {
return (<WithTooltip tooltip="Export Chat"> return (
<IconButton <WithTooltip tooltip="Export Chat">
title="Export Chat" <IconButton title="Export Chat" onClick={exportChat}>
onClick={exportChat} <div className="i-ph:download-simple text-xl"></div>
> </IconButton>
<div className="i-ph:download-simple text-xl"></div> </WithTooltip>
</IconButton> );
</WithTooltip>); };
}

View File

@@ -32,6 +32,7 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
toast.error('Chat persistence is not available'); toast.error('Chat persistence is not available');
return; return;
} }
const urlId = await forkChat(db, chatId.get()!, messageId); const urlId = await forkChat(db, chatId.get()!, messageId);
window.location.href = `/chat/${urlId}`; window.location.href = `/chat/${urlId}`;
} catch (error) { } catch (error) {
@@ -40,47 +41,48 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
}; };
return ( return (
<div id={id} ref={ref} className={props.className}> <div id={id} ref={ref} className={props.className}>
{messages.length > 0 {messages.length > 0
? messages.map((message, index) => { ? messages.map((message, index) => {
const { role, content, id: messageId } = message; const { role, content, id: messageId } = message;
const isUserMessage = role === 'user'; const isUserMessage = role === 'user';
const isFirst = index === 0; const isFirst = index === 0;
const isLast = index === messages.length - 1; const isLast = index === messages.length - 1;
return ( return (
<div <div
key={index} key={index}
className={classNames('flex gap-4 p-6 w-full rounded-[calc(0.75rem-1px)]', { className={classNames('flex gap-4 p-6 w-full rounded-[calc(0.75rem-1px)]', {
'bg-bolt-elements-messages-background': isUserMessage || !isStreaming || (isStreaming && !isLast), 'bg-bolt-elements-messages-background': isUserMessage || !isStreaming || (isStreaming && !isLast),
'bg-gradient-to-b from-bolt-elements-messages-background from-30% to-transparent': 'bg-gradient-to-b from-bolt-elements-messages-background from-30% to-transparent':
isStreaming && isLast, isStreaming && isLast,
'mt-4': !isFirst, 'mt-4': !isFirst,
})} })}
> >
{isUserMessage && ( {isUserMessage && (
<div className="flex items-center justify-center w-[34px] h-[34px] overflow-hidden bg-white text-gray-600 rounded-full shrink-0 self-start"> <div className="flex items-center justify-center w-[34px] h-[34px] overflow-hidden bg-white text-gray-600 rounded-full shrink-0 self-start">
<div className="i-ph:user-fill text-xl"></div> <div className="i-ph:user-fill text-xl"></div>
</div>
)}
<div className="grid grid-col-1 w-full">
{isUserMessage ? <UserMessage content={content} /> : <AssistantMessage content={content} />}
</div> </div>
{!isUserMessage && ( )}
<div className="flex gap-2 flex-col lg:flex-row"> <div className="grid grid-col-1 w-full">
<WithTooltip tooltip="Revert to this message"> {isUserMessage ? <UserMessage content={content} /> : <AssistantMessage content={content} />}
{messageId && (<button </div>
onClick={() => handleRewind(messageId)} {!isUserMessage && (
key="i-ph:arrow-u-up-left" <div className="flex gap-2 flex-col lg:flex-row">
className={classNames( <WithTooltip tooltip="Revert to this message">
'i-ph:arrow-u-up-left', {messageId && (
'text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors', <button
)} onClick={() => handleRewind(messageId)}
key="i-ph:arrow-u-up-left"
className={classNames(
'i-ph:arrow-u-up-left',
'text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors',
)}
/> />
)} )}
</WithTooltip> </WithTooltip>
<WithTooltip tooltip="Fork chat from this message"> <WithTooltip tooltip="Fork chat from this message">
<button <button
onClick={() => handleFork(messageId)} onClick={() => handleFork(messageId)}
key="i-ph:git-fork" key="i-ph:git-fork"
@@ -90,15 +92,15 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
)} )}
/> />
</WithTooltip> </WithTooltip>
</div> </div>
)} )}
</div> </div>
); );
}) })
: null} : null}
{isStreaming && ( {isStreaming && (
<div className="text-center w-full text-bolt-elements-textSecondary i-svg-spinners:3-dots-fade text-4xl mt-4"></div> <div className="text-center w-full text-bolt-elements-textSecondary i-svg-spinners:3-dots-fade text-4xl mt-4"></div>
)} )}
</div> </div>
); );
}); });

View File

@@ -54,6 +54,7 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History
onClick={(event) => { onClick={(event) => {
event.preventDefault(); event.preventDefault();
exportChat(item.id); exportChat(item.id);
//exportChat(item.messages, item.description); //exportChat(item.messages, item.description);
}} }}
title="Export chat" title="Export chat"
@@ -70,14 +71,14 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History
)} )}
<Dialog.Trigger asChild> <Dialog.Trigger asChild>
<WithTooltip tooltip="Delete chat"> <WithTooltip tooltip="Delete chat">
<button <button
className="i-ph:trash scale-110" className="i-ph:trash scale-110"
onClick={(event) => { onClick={(event) => {
// we prevent the default so we don't trigger the anchor above // we prevent the default so we don't trigger the anchor above
event.preventDefault(); event.preventDefault();
onDelete?.(event); onDelete?.(event);
}} }}
/> />
</WithTooltip> </WithTooltip>
</Dialog.Trigger> </Dialog.Trigger>
</div> </div>

View File

@@ -16,8 +16,8 @@ const menuVariants = {
left: '-150px', left: '-150px',
transition: { transition: {
duration: 0.2, duration: 0.2,
ease: cubicEasingFn ease: cubicEasingFn,
} },
}, },
open: { open: {
opacity: 1, opacity: 1,
@@ -25,9 +25,9 @@ const menuVariants = {
left: 0, left: 0,
transition: { transition: {
duration: 0.2, duration: 0.2,
ease: cubicEasingFn ease: cubicEasingFn,
} },
} },
} satisfies Variants; } satisfies Variants;
type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null; type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null;
@@ -134,8 +134,7 @@ export function Menu() {
<DialogRoot open={dialogContent !== null}> <DialogRoot open={dialogContent !== null}>
{binDates(list).map(({ category, items }) => ( {binDates(list).map(({ category, items }) => (
<div key={category} className="mt-4 first:mt-0 space-y-1"> <div key={category} className="mt-4 first:mt-0 space-y-1">
<div <div className="text-bolt-elements-textTertiary sticky top-0 z-1 bg-bolt-elements-background-depth-2 pl-2 pt-2 pb-1">
className="text-bolt-elements-textTertiary sticky top-0 z-1 bg-bolt-elements-background-depth-2 pl-2 pt-2 pb-1">
{category} {category}
</div> </div>
{items.map((item) => ( {items.map((item) => (

View File

@@ -1,27 +1,32 @@
import React from 'react'; import React from 'react';
import * as Tooltip from '@radix-ui/react-tooltip'; import * as Tooltip from '@radix-ui/react-tooltip';
import type {ReactNode} from 'react'; import type { ReactNode } from 'react';
interface ToolTipProps { interface ToolTipProps {
tooltip: string, tooltip: string;
children: ReactNode | ReactNode[]; children: ReactNode | ReactNode[];
sideOffset?: number, sideOffset?: number;
className?: string, className?: string;
arrowClassName?: string, arrowClassName?: string;
tooltipStyle?: any, //TODO better type tooltipStyle?: any; //TODO better type
} }
const WithTooltip = ({ tooltip, children, sideOffset = 5, className = '', arrowClassName = '', tooltipStyle = {} }: ToolTipProps) => { const WithTooltip = ({
tooltip,
children,
sideOffset = 5,
className = '',
arrowClassName = '',
tooltipStyle = {},
}: ToolTipProps) => {
return ( return (
<Tooltip.Root> <Tooltip.Root>
<Tooltip.Trigger asChild> <Tooltip.Trigger asChild>{children}</Tooltip.Trigger>
{children}
</Tooltip.Trigger>
<Tooltip.Portal> <Tooltip.Portal>
<Tooltip.Content <Tooltip.Content
className={`bg-bolt-elements-tooltip-background text-bolt-elements-textPrimary px-3 py-2 rounded-lg text-sm shadow-lg ${className}`} className={`bg-bolt-elements-tooltip-background text-bolt-elements-textPrimary px-3 py-2 rounded-lg text-sm shadow-lg ${className}`}
sideOffset={sideOffset} sideOffset={sideOffset}
style={{ zIndex: 2000, backgroundColor: "white", ...tooltipStyle }} style={{ zIndex: 2000, backgroundColor: 'white', ...tooltipStyle }}
> >
{tooltip} {tooltip}
<Tooltip.Arrow className={`fill-bolt-elements-tooltip-background ${arrowClassName}`} /> <Tooltip.Arrow className={`fill-bolt-elements-tooltip-background ${arrowClassName}`} />

View File

@@ -179,18 +179,21 @@ export async function forkChat(db: IDBDatabase, chatId: string, messageId: strin
return createChatFromMessages(db, chat.description ? `${chat.description} (fork)` : 'Forked chat', messages); return createChatFromMessages(db, chat.description ? `${chat.description} (fork)` : 'Forked chat', messages);
} }
export async function duplicateChat(db: IDBDatabase, id: string): Promise<string> { export async function duplicateChat(db: IDBDatabase, id: string): Promise<string> {
const chat = await getMessages(db, id); const chat = await getMessages(db, id);
if (!chat) { if (!chat) {
throw new Error('Chat not found'); throw new Error('Chat not found');
} }
return createChatFromMessages(db, `${chat.description || 'Chat'} (copy)`, chat.messages); return createChatFromMessages(db, `${chat.description || 'Chat'} (copy)`, chat.messages);
} }
export async function createChatFromMessages(db: IDBDatabase, description: string, messages: Message[]) : Promise<string> { export async function createChatFromMessages(
db: IDBDatabase,
description: string,
messages: Message[],
): Promise<string> {
const newId = await getNextId(db); const newId = await getNextId(db);
const newUrlId = await getUrlId(db, newId); // Get a new urlId for the duplicated chat const newUrlId = await getUrlId(db, newId); // Get a new urlId for the duplicated chat
@@ -199,7 +202,7 @@ export async function createChatFromMessages(db: IDBDatabase, description: strin
newId, newId,
messages, messages,
newUrlId, // Use the new urlId newUrlId, // Use the new urlId
description description,
); );
return newUrlId; // Return the urlId instead of id for navigation return newUrlId; // Return the urlId instead of id for navigation

View File

@@ -11,7 +11,7 @@ import {
openDatabase, openDatabase,
setMessages, setMessages,
duplicateChat, duplicateChat,
createChatFromMessages createChatFromMessages,
} from './db'; } from './db';
export interface ChatHistoryItem { export interface ChatHistoryItem {
@@ -121,7 +121,7 @@ export function useChatHistory() {
console.log(error); console.log(error);
} }
}, },
importChat: async (description: string, messages:Message[]) => { importChat: async (description: string, messages: Message[]) => {
if (!db) { if (!db) {
return; return;
} }
@@ -131,7 +131,7 @@ export function useChatHistory() {
window.location.href = `/chat/${newId}`; window.location.href = `/chat/${newId}`;
toast.success('Chat imported successfully'); toast.success('Chat imported successfully');
} catch (error) { } catch (error) {
toast.error('Failed to import chat'); toast.error('Failed to import chat: ' + error.message);
} }
}, },
exportChat: async (id = urlId) => { exportChat: async (id = urlId) => {
@@ -155,7 +155,7 @@ export function useChatHistory() {
a.click(); a.click();
document.body.removeChild(a); document.body.removeChild(a);
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} },
}; };
} }

View File

@@ -11,7 +11,7 @@ interface Logger {
setLevel: (level: DebugLevel) => void; setLevel: (level: DebugLevel) => void;
} }
let currentLevel: DebugLevel = import.meta.env.VITE_LOG_LEVEL ?? import.meta.env.DEV ? 'debug' : 'info'; let currentLevel: DebugLevel = (import.meta.env.VITE_LOG_LEVEL ?? import.meta.env.DEV) ? 'debug' : 'info';
const isWorker = 'HTMLRewriter' in globalThis; const isWorker = 'HTMLRewriter' in globalThis;
const supportsColor = !isWorker; const supportsColor = !isWorker;