import * as React from 'react'; import { useState, useEffect, useRef } from 'react'; import { Accordion, AccordionControlProps, Avatar, Box, Center, Container, CopyButton, Divider, Flex, Grid, Stack, Textarea, TypographyStylesProvider, px, rem, useMantineTheme } from '@mantine/core'; import { Input, Tooltip } from '@mantine/core'; import { List } from '@mantine/core'; import { ScrollArea } from '@mantine/core'; import { createStyles, keyframes } from '@mantine/core'; import { ActionIcon } from '@mantine/core'; import { Menu, Button, Text } from '@mantine/core'; import { useElementSize, useListState, useResizeObserver, useViewportSize } from '@mantine/hooks'; import { IconAdjustments, IconBulb, IconCameraSelfie, IconCheck, IconClick, IconColumnInsertRight, IconCopy, IconDots, IconEdit, IconFileDiff, IconFolder, IconGitCommit, IconGitCompare, IconMessageDots, IconMessagePlus, IconPlayerStop, IconPrinter, IconPrompt, IconReplace, IconRobot, IconSend, IconSquareRoundedPlus, IconTerminal2, IconUser, IconX } from '@tabler/icons-react'; import { IconSettings, IconSearch, IconPhoto, IconMessageCircle, IconTrash, IconArrowsLeftRight } from '@tabler/icons-react'; import { Prism } from '@mantine/prism'; import ReactMarkdown from 'react-markdown'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import okaidia from 'react-syntax-highlighter/dist/esm/styles/prism/okaidia'; import messageUtil from '../util/MessageUtil'; const blink = keyframes({ '50%': { opacity: 0 }, }); const useStyles = createStyles((theme, _params, classNames) => ({ menu: { }, avatar: { marginTop: 8, marginLeft: 8, }, })); const chatPanel = () => { const theme = useMantineTheme(); const chatContainerRef = useRef(null); const scrollViewport = useRef(null); const [messages, messageHandlers] = useListState<{ type: string; message: string; contexts?: any[] }>([]); const [commandMenus, commandMenusHandlers] = useListState<{ pattern: string; description: string; name: string }>([]); const [contextMenus, contextMenusHandlers] = useListState<{ pattern: string; description: string; name: string }>([]); const [contexts, contextsHandlers] = useListState([]); const [currentMessage, setCurrentMessage] = useState(''); const [generating, setGenerating] = useState(false); const [responsed, setResponsed] = useState(false); const [registed, setRegisted] = useState(false); const [input, setInput] = useState(''); const [menuOpend, setMenuOpend] = useState(false); const [menuType, setMenuType] = useState(''); // contexts or commands const { classes } = useStyles(); const { height, width } = useViewportSize(); const [inputRef, inputRect] = useResizeObserver(); const handlePlusClick = (event: React.MouseEvent) => { setMenuType('contexts'); setMenuOpend(!menuOpend); event.stopPropagation(); }; const handleSendClick = (event: React.MouseEvent) => { if (input) { // Add the user's message to the chat UI messageHandlers.append({ type: 'user', message: input, contexts: contexts ? [...contexts].map((item) => ({ ...item })) : undefined }); // Process and send the message to the extension const contextStrs = contexts.map(({ file, context }, index) => { return `[context|${file}]`; }); const text = input + contextStrs.join(' '); console.log(`message text: ${text}`); messageUtil.sendMessage({ command: 'sendMessage', text: text }); // Clear the input field setInput(''); contexts.length = 0; // start generating setGenerating(true); setResponsed(false); setCurrentMessage(''); } }; const handleContextClick = (contextName: string) => { // Process and send the message to the extension messageUtil.sendMessage({ command: 'addContext', selected: contextName }); }; const scrollToBottom = () => scrollViewport?.current?.scrollTo({ top: scrollViewport.current.scrollHeight, behavior: 'smooth' }); useEffect(() => { inputRef.current.focus(); messageUtil.sendMessage({ command: 'regContextList' }); messageUtil.sendMessage({ command: 'regCommandList' }); messageUtil.sendMessage({ command: 'historyMessages' }); setTimeout(() => { scrollToBottom(); }, 2000); }, []); useEffect(() => { if (generating) { // new a bot message messageHandlers.append({ type: 'bot', message: currentMessage }); } }, [generating]); // Add the received message to the chat UI as a bot message useEffect(() => { const lastIndex = messages?.length - 1; const lastMessage = messages[lastIndex]; if (currentMessage && lastMessage?.type === 'bot') { // update the last one bot message messageHandlers.setItem(lastIndex, { type: 'bot', message: currentMessage }); } }, [currentMessage]); // Add the received message to the chat UI as a bot message useEffect(() => { if (registed) return; setRegisted(true); messageUtil.registerHandler('receiveMessagePartial', (message: { text: string; }) => { setCurrentMessage(message.text); setResponsed(true); scrollToBottom(); }); messageUtil.registerHandler('receiveMessage', (message: { text: string; }) => { setCurrentMessage(message.text); setGenerating(false); setResponsed(true); scrollToBottom(); }); messageUtil.registerHandler('regCommandList', (message: { result: { pattern: string; description: string; name: string }[] }) => { commandMenusHandlers.append(...message.result); }); messageUtil.registerHandler('regContextList', (message: { result: { pattern: string; description: string; name: string }[] }) => { contextMenusHandlers.append(...message.result); }); messageUtil.registerHandler('appendContext', (message: { command: string; context: string }) => { // context is a temp file path const match = /\|([^]+?)\]/.exec(message.context); // Process and send the message to the extension messageUtil.sendMessage({ command: 'contextDetail', file: match && match[1], }); }); messageUtil.registerHandler('contextDetailResponse', (message: { command: string; file: string; result: string }) => { //result is a content json // 1. diff json structure // { // languageId: languageId, // path: fileSelected, // content: codeSelected // }; // 2. command json structure // { // command: commandString, // content: stdout // }; const context = JSON.parse(message.result); if (typeof context !== 'undefined' && context) { contextsHandlers.append({ file: message.file, context: context, }); } }); messageUtil.registerHandler('loadHistoryMessages', (message: { command: string; entries: [{ hash: '', user: '', date: '', request: '', response: '', context: [{ content: '', role: '' }] }] }) => { console.log(JSON.stringify(message)); message.entries?.forEach(({ hash, user, date, request, response, context }, index) => { const contexts = context.map(({ content, role }) => ({ context: JSON.parse(content) })); messageHandlers.append({ type: 'user', message: request, contexts: contexts }); messageHandlers.append({ type: 'bot', message: response }); if (index === message.entries.length - 1) { scrollToBottom(); } }); }); }, [registed]); const handleInputChange = (event: React.ChangeEvent) => { const value = event.target.value; // if value start with '/' command show menu if (value === '/') { setMenuOpend(true); setMenuType('commands'); } else { setMenuOpend(false); } setInput(value); }; const handleKeyDown = (event: React.KeyboardEvent) => { if (event.key === 'Enter' && event.ctrlKey) { handleSendClick(event as any); } }; const defaultMessages = (
No messages yet
); const commandMenusNode = commandMenus.map(({ pattern, description, name }, index) => { return ( { setInput(`/${pattern} `); }} icon={} > /{pattern} {description} ); }); const contextMenusNode = contextMenus.map(({ pattern, description, name }, index) => { return ( { handleContextClick(name); }} icon={} > {name} {description} ); }); const messageList = messages.map(({ message: messageText, type: messageType, contexts }, index) => { // setMessage(messageText); return (<> { messageType === 'bot' ? : } {contexts && { contexts?.map(({ context }, index) => { return ( {'command' in context ? context.command : context.path} { context.content ? context.content :
No content
}
); }) }
}
{match[1] && (
{match[1]}
)}
{({ copied, copy }) => ( {copied ? : } )} {match[1] && match[1] === 'commitmsg' ? (<> { messageUtil.sendMessage({ command: 'doCommit', content: value }); setCommited(true); setTimeout(() => { setCommited(false); }, 2000); }}> {commited ? : } ) : (<> { messageUtil.sendMessage({ command: 'show_diff', content: value }); }}> { messageUtil.sendMessage({ command: 'code_apply', content: value }); }}> { messageUtil.sendMessage({ command: 'code_file_apply', content: value }); }}> )} {value} ) : ( {children} ); } }} > {messageText}
{(generating && messageType === 'bot' && index === messages.length - 1) ? | : ''}
{index !== messages.length - 1 && } ); }); return ( {messageList.length > 0 ? messageList : defaultMessages} {generating &&
} {contexts && contexts.length > 0 && { contexts.map(({ context }, index) => { return ( {'command' in context ? context.command : context.path} { contextsHandlers.remove(index); }}> { context.content ? context.content :
No content
}
); }) }
} { setMenuOpend(!menuOpend); inputRef.current.focus(); }} onClose={() => setMenuType('')} onOpen={() => menuType !== '' ? setMenuOpend(true) : setMenuOpend(false)} returnFocus={true}>