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>
@@ -232,12 +230,13 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
<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
@@ -260,7 +259,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
}} }}
style={{ style={{
minHeight: TEXTAREA_MIN_HEIGHT, minHeight: TEXTAREA_MIN_HEIGHT,
maxHeight: TEXTAREA_MAX_HEIGHT maxHeight: TEXTAREA_MAX_HEIGHT,
}} }}
placeholder="How can Bolt help you today?" placeholder="How can Bolt help you today?"
translate="no" translate="no"
@@ -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,7 +82,8 @@ interface ChatProps {
exportChat: () => void; exportChat: () => void;
} }
export const ChatImpl = memo(({ description, initialMessages, storeMessageHistory, importChat, exportChat }: ChatProps) => { export const ChatImpl = memo(
({ description, initialMessages, storeMessageHistory, importChat, exportChat }: ChatProps) => {
useShortcuts(); useShortcuts();
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -287,4 +296,5 @@ export const ChatImpl = memo(({ description, initialMessages, storeMessageHistor
}} }}
/> />
); );
}); },
);

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> <div className="i-ph:download-simple text-xl"></div>
</IconButton> </IconButton>
</WithTooltip>); </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) {
@@ -69,7 +70,8 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
{!isUserMessage && ( {!isUserMessage && (
<div className="flex gap-2 flex-col lg:flex-row"> <div className="flex gap-2 flex-col lg:flex-row">
<WithTooltip tooltip="Revert to this message"> <WithTooltip tooltip="Revert to this message">
{messageId && (<button {messageId && (
<button
onClick={() => handleRewind(messageId)} onClick={() => handleRewind(messageId)}
key="i-ph:arrow-u-up-left" key="i-ph:arrow-u-up-left"
className={classNames( className={classNames(

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"

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;