@red-hat-developer-hub/backstage-plugin-lightspeed 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +15 -0
- package/config.d.ts +21 -0
- package/dist/api/LightspeedApiClient.esm.js +3 -2
- package/dist/api/LightspeedApiClient.esm.js.map +1 -1
- package/dist/api/api.esm.js.map +1 -1
- package/dist/components/Attachment.esm.js +98 -0
- package/dist/components/Attachment.esm.js.map +1 -0
- package/dist/components/AttachmentContext.esm.js +105 -0
- package/dist/components/AttachmentContext.esm.js.map +1 -0
- package/dist/components/FilePreview.esm.js +59 -0
- package/dist/components/FilePreview.esm.js.map +1 -0
- package/dist/components/LightSpeedChat.esm.js +40 -26
- package/dist/components/LightSpeedChat.esm.js.map +1 -1
- package/dist/components/LightspeedChatBox.esm.js +56 -5
- package/dist/components/LightspeedChatBox.esm.js.map +1 -1
- package/dist/components/LightspeedPage.esm.js +3 -2
- package/dist/components/LightspeedPage.esm.js.map +1 -1
- package/dist/const.esm.js +58 -1
- package/dist/const.esm.js.map +1 -1
- package/dist/hooks/useAutoScroll.esm.js +78 -0
- package/dist/hooks/useAutoScroll.esm.js.map +1 -0
- package/dist/hooks/useBufferedMessages.esm.js +27 -0
- package/dist/hooks/useBufferedMessages.esm.js.map +1 -0
- package/dist/hooks/useConversationMessages.esm.js +34 -4
- package/dist/hooks/useConversationMessages.esm.js.map +1 -1
- package/dist/hooks/useCreateCoversationMessage.esm.js +4 -2
- package/dist/hooks/useCreateCoversationMessage.esm.js.map +1 -1
- package/dist/hooks/useWelcomePrompts.esm.js +20 -0
- package/dist/hooks/useWelcomePrompts.esm.js.map +1 -0
- package/dist/types.esm.js +9 -0
- package/dist/types.esm.js.map +1 -0
- package/dist/utils/attachment-utils.esm.js +23 -0
- package/dist/utils/attachment-utils.esm.js.map +1 -0
- package/dist/utils/lightspeed-chatbox-utils.esm.js +9 -4
- package/dist/utils/lightspeed-chatbox-utils.esm.js.map +1 -1
- package/dist/utils/prompt-utils.esm.js +17 -0
- package/dist/utils/prompt-utils.esm.js.map +1 -0
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LightSpeedChat.esm.js","sources":["../../src/components/LightSpeedChat.tsx"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\n\nimport { ErrorPanel } from '@backstage/core-components';\n\nimport { Box, makeStyles } from '@material-ui/core';\nimport {\n Chatbot,\n ChatbotContent,\n ChatbotDisplayMode,\n ChatbotFooter,\n ChatbotFootnote,\n ChatbotHeader,\n ChatbotHeaderMain,\n ChatbotHeaderMenu,\n ChatbotHeaderTitle,\n MessageBar,\n MessageProps,\n} from '@patternfly/chatbot';\nimport ChatbotConversationHistoryNav from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';\nimport { DropdownItem, Title } from '@patternfly/react-core';\nimport { useQueryClient } from '@tanstack/react-query';\n\nimport { TEMP_CONVERSATION_ID } from '../const';\nimport {\n useBackstageUserIdentity,\n useConversationMessages,\n useConversations,\n useDeleteConversation,\n useIsMobile,\n useLastOpenedConversation,\n useLightspeedDeletePermission,\n} from '../hooks';\nimport { ConversationSummary } from '../types';\nimport {\n getCategorizeMessages,\n getFootnoteProps,\n} from '../utils/lightspeed-chatbox-utils';\nimport { DeleteModal } from './DeleteModal';\nimport { LightspeedChatBox } from './LightspeedChatBox';\nimport { LightspeedChatBoxHeader } from './LightspeedChatBoxHeader';\n\nconst useStyles = makeStyles(theme => ({\n body: {\n // remove default margin and padding from common elements\n '& h1, & h2, & h3, & h4, & h5, & h6, & p, & ul, & ol, & li': {\n margin: 0,\n padding: 0,\n },\n },\n header: {\n padding: `${theme.spacing(3)}px !important`,\n },\n headerMenu: {\n // align hamburger icon with title\n '& .pf-v6-c-button': {\n display: 'flex',\n alignItems: 'center',\n },\n },\n headerTitle: {\n justifyContent: 'left !important',\n },\n footer: {\n '&>.pf-chatbot__footer-container': {\n width: '95% !important',\n maxWidth: 'unset !important',\n },\n },\n}));\n\ntype LightspeedChatProps = {\n selectedModel: string;\n userName?: string;\n avatar?: string;\n profileLoading: boolean;\n handleSelectedModel: (item: string) => void;\n models: { label: string; value: string }[];\n};\n\nexport const LightspeedChat = ({\n selectedModel,\n userName,\n avatar,\n profileLoading,\n handleSelectedModel,\n models,\n}: LightspeedChatProps) => {\n const isMobile = useIsMobile();\n const classes = useStyles();\n const user = useBackstageUserIdentity();\n const [filterValue, setFilterValue] = React.useState<string>('');\n const [announcement, setAnnouncement] = React.useState<string>('');\n const [conversationId, setConversationId] = React.useState<string>('');\n const [isDrawerOpen, setIsDrawerOpen] = React.useState<boolean>(!isMobile);\n const [newChatCreated, setNewChatCreated] = React.useState<boolean>(false);\n const [isSendButtonDisabled, setIsSendButtonDisabled] =\n React.useState<boolean>(false);\n const [error, setError] = React.useState<Error | null>(null);\n const [targetConversationId, setTargetConversationId] =\n React.useState<string>('');\n const [isDeleteModalOpen, setIsDeleteModalOpen] =\n React.useState<boolean>(false);\n const { isReady, lastOpenedId, setLastOpenedId, clearLastOpenedId } =\n useLastOpenedConversation(user);\n\n // Sync conversationId with lastOpenedId whenever lastOpenedId changes\n React.useEffect(() => {\n if (isReady && lastOpenedId !== null) {\n setConversationId(lastOpenedId);\n }\n }, [lastOpenedId, isReady]);\n\n const queryClient = useQueryClient();\n\n const { data: conversations = [] } = useConversations();\n const { mutateAsync: deleteConversation } = useDeleteConversation();\n const { allowed: hasDeleteAccess } = useLightspeedDeletePermission();\n\n React.useEffect(() => {\n if (user && lastOpenedId === null && isReady) {\n setConversationId(TEMP_CONVERSATION_ID);\n setNewChatCreated(true);\n }\n }, [user, isReady, lastOpenedId, setConversationId]);\n\n React.useEffect(() => {\n // Update last opened conversation whenever `conversationId` changes\n if (conversationId) {\n setLastOpenedId(conversationId);\n }\n }, [conversationId, setLastOpenedId]);\n\n const onStart = (conv_id: string) => {\n setConversationId(conv_id);\n };\n\n const onComplete = (message: string) => {\n setIsSendButtonDisabled(false);\n setAnnouncement(`Message from Bot: ${message}`);\n queryClient.invalidateQueries({\n queryKey: ['conversations'],\n });\n setNewChatCreated(false);\n };\n\n const { conversationMessages, handleInputPrompt, scrollToBottomRef } =\n useConversationMessages(\n conversationId,\n userName,\n selectedModel,\n avatar,\n onComplete,\n onStart,\n );\n\n const [messages, setMessages] =\n React.useState<MessageProps[]>(conversationMessages);\n\n // Auto-scrolls to the latest message\n React.useEffect(() => {\n setTimeout(() => {\n scrollToBottomRef.current?.scrollIntoView({ behavior: 'auto' });\n }, 10);\n // eslint-disable-next-line\n }, [messages, scrollToBottomRef.current]);\n\n const sendMessage = (message: string | number) => {\n if (conversationId !== TEMP_CONVERSATION_ID) {\n setNewChatCreated(false);\n }\n setAnnouncement(\n `Message from User: ${prompt}. Message from Bot is loading.`,\n );\n handleInputPrompt(message.toString());\n setIsSendButtonDisabled(true);\n };\n\n const onNewChat = React.useCallback(() => {\n (async () => {\n setMessages([]);\n setConversationId(TEMP_CONVERSATION_ID);\n setNewChatCreated(true);\n })();\n }, [setConversationId, setMessages]);\n\n const openDeleteModal = (conversation_id: string) => {\n setTargetConversationId(conversation_id);\n setIsDeleteModalOpen(true);\n };\n\n const handleDeleteConversation = React.useCallback(() => {\n (async () => {\n try {\n await deleteConversation({\n conversation_id: targetConversationId,\n invalidateCache: false,\n });\n if (targetConversationId === lastOpenedId) {\n onNewChat();\n clearLastOpenedId();\n }\n setIsDeleteModalOpen(false);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(e);\n setError(e);\n }\n })();\n }, [\n deleteConversation,\n clearLastOpenedId,\n lastOpenedId,\n onNewChat,\n targetConversationId,\n ]);\n\n const additionalMessageProps = React.useCallback(\n (conversationSummary: ConversationSummary) => ({\n menuItems: (\n <DropdownItem\n isDisabled={!hasDeleteAccess}\n onClick={() => openDeleteModal(conversationSummary.conversation_id)}\n >\n Delete\n </DropdownItem>\n ),\n }),\n [hasDeleteAccess],\n );\n const categorizedMessages = getCategorizeMessages(\n conversations,\n additionalMessageProps,\n );\n\n const filterConversations = React.useCallback(\n (targetValue: string) => {\n const filteredConversations = Object.entries(categorizedMessages).reduce(\n (acc, [key, items]) => {\n const filteredItems = items.filter(item =>\n item.text\n .toLocaleLowerCase('en-US')\n .includes(targetValue.toLocaleLowerCase('en-US')),\n );\n if (filteredItems.length > 0) {\n acc[key] = filteredItems;\n }\n return acc;\n },\n {} as any,\n );\n return filteredConversations;\n },\n [categorizedMessages],\n );\n\n React.useEffect(() => {\n setMessages(conversationMessages);\n }, [conversationMessages]);\n\n const onSelectActiveItem = React.useCallback(\n (\n _: React.MouseEvent | undefined,\n selectedItem: string | number | undefined,\n ) => {\n setNewChatCreated(false);\n setConversationId((c_id: string) => {\n if (c_id !== selectedItem) {\n return String(selectedItem);\n }\n return c_id;\n });\n },\n [setConversationId],\n );\n\n const conversationFound = !!conversations.find(\n c => c.conversation_id === conversationId,\n );\n\n const welcomePrompts =\n (newChatCreated && conversationMessages.length === 0) ||\n (!conversationFound && conversationMessages.length === 0)\n ? [\n {\n title: 'Topic 1',\n message: 'Helpful prompt for Topic 1',\n onClick: () => sendMessage('Helpful prompt for Topic 1'),\n },\n {\n title: 'Topic 2',\n message: 'Helpful prompt for Topic 2',\n onClick: () => sendMessage('Helpful prompt for Topic 2'),\n },\n ]\n : [];\n\n const handleFilter = React.useCallback((value: string) => {\n setFilterValue(value);\n }, []);\n\n const onDrawerToggle = React.useCallback(() => {\n setIsDrawerOpen(isOpen => !isOpen);\n }, []);\n\n if (error) {\n return (\n <Box padding={1}>\n <ErrorPanel error={error} />\n </Box>\n );\n }\n\n return (\n <>\n {isDeleteModalOpen && (\n <DeleteModal\n isOpen={isDeleteModalOpen}\n onClose={() => setIsDeleteModalOpen(false)}\n onConfirm={handleDeleteConversation}\n />\n )}\n <Chatbot\n displayMode={ChatbotDisplayMode.embedded}\n className={classes.body}\n >\n <ChatbotHeader className={classes.header}>\n <ChatbotHeaderMain>\n <ChatbotHeaderMenu\n aria-expanded={isDrawerOpen}\n onMenuToggle={() => setIsDrawerOpen(!isDrawerOpen)}\n className={classes.headerMenu}\n />\n <ChatbotHeaderTitle className={classes.headerTitle}>\n <Title headingLevel=\"h1\" size=\"3xl\">\n Developer Hub Lightspeed\n </Title>\n </ChatbotHeaderTitle>\n </ChatbotHeaderMain>\n\n <LightspeedChatBoxHeader\n selectedModel={selectedModel}\n handleSelectedModel={item => handleSelectedModel(item)}\n models={models}\n />\n </ChatbotHeader>\n <ChatbotConversationHistoryNav\n drawerPanelContentProps={{ isResizable: true, minSize: '200px' }}\n reverseButtonOrder\n displayMode={ChatbotDisplayMode.embedded}\n onDrawerToggle={onDrawerToggle}\n isDrawerOpen={isDrawerOpen}\n setIsDrawerOpen={setIsDrawerOpen}\n activeItemId={conversationId}\n onSelectActiveItem={onSelectActiveItem}\n conversations={filterConversations(filterValue)}\n onNewChat={newChatCreated ? undefined : onNewChat}\n handleTextInputChange={handleFilter}\n drawerContent={\n <>\n <ChatbotContent>\n <LightspeedChatBox\n userName={userName}\n messages={messages}\n profileLoading={profileLoading}\n announcement={announcement}\n ref={scrollToBottomRef}\n welcomePrompts={welcomePrompts}\n />\n </ChatbotContent>\n <ChatbotFooter className={classes.footer}>\n <MessageBar\n onSendMessage={sendMessage}\n isSendButtonDisabled={isSendButtonDisabled}\n hasAttachButton={false}\n hasMicrophoneButton\n />\n <ChatbotFootnote {...getFootnoteProps()} />\n </ChatbotFooter>\n </>\n }\n />\n </Chatbot>\n </>\n );\n};\n"],"names":["React"],"m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QAClB,aAAa,kBAAmB,CAAA,QAAA;AAAA,QAChC,cAAA;AAAA,QACA,YAAA;AAAA,QACA,eAAA;AAAA,QACA,YAAc,EAAA,cAAA;AAAA,QACd,kBAAA;AAAA,QACA,aAAA,EAAe,oBAAoB,WAAW,CAAA;AAAA,QAC9C,SAAA,EAAW,iBAAiB,SAAY,GAAA,SAAA;AAAA,QACxC,qBAAuB,EAAA,YAAA;AAAA,QACvB,aAAA,kBAEIA,cAAA,CAAA,aAAA,CAAAA,cAAA,CAAA,QAAA,EAAA,IAAA,kBAAAA,cAAA,CAAA,aAAA,CAAC,cACC,EAAA,IAAA,kBAAAA,cAAA,CAAA,aAAA;AAAA,UAAC,iBAAA;AAAA,UAAA;AAAA,YACC,QAAA;AAAA,YACA,QAAA;AAAA,YACA,cAAA;AAAA,YACA,YAAA;AAAA,YACA,GAAK,EAAA,iBAAA;AAAA,YACL;AAAA;AAAA,SAEJ,CACA,kBAAAA,cAAA,CAAA,aAAA,CAAC,aAAc,EAAA,EAAA,SAAA,EAAW,QAAQ,MAChC,EAAA,kBAAAA,cAAA,CAAA,aAAA;AAAA,UAAC,UAAA;AAAA,UAAA;AAAA,YACC,aAAe,EAAA,WAAA;AAAA,YACf,oBAAA;AAAA,YACA,eAAiB,EAAA,KAAA;AAAA,YACjB,mBAAmB,EAAA;AAAA;AAAA,2BAEpBA,cAAA,CAAA,aAAA,CAAA,eAAA,EAAA,EAAiB,GAAG,gBAAiB,EAAA,EAAG,CAC3C,CACF;AAAA;AAAA;AAEJ,GAEJ,CAAA;AAEJ;;;;"}
|
|
1
|
+
{"version":3,"file":"LightSpeedChat.esm.js","sources":["../../src/components/LightSpeedChat.tsx"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\n\nimport { ErrorPanel } from '@backstage/core-components';\n\nimport { Box, makeStyles } from '@material-ui/core';\nimport {\n Chatbot,\n ChatbotContent,\n ChatbotDisplayMode,\n ChatbotFooter,\n ChatbotFootnote,\n ChatbotHeader,\n ChatbotHeaderMain,\n ChatbotHeaderMenu,\n ChatbotHeaderTitle,\n MessageBar,\n MessageProps,\n} from '@patternfly/chatbot';\nimport ChatbotConversationHistoryNav from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';\nimport { DropdownItem, DropEvent, Title } from '@patternfly/react-core';\nimport { useQueryClient } from '@tanstack/react-query';\n\nimport { TEMP_CONVERSATION_ID } from '../const';\nimport {\n useBackstageUserIdentity,\n useConversationMessages,\n useConversations,\n useDeleteConversation,\n useIsMobile,\n useLastOpenedConversation,\n useLightspeedDeletePermission,\n} from '../hooks';\nimport { useWelcomePrompts } from '../hooks/useWelcomePrompts';\nimport { ConversationSummary } from '../types';\nimport { getAttachments } from '../utils/attachment-utils';\nimport {\n getCategorizeMessages,\n getFootnoteProps,\n} from '../utils/lightspeed-chatbox-utils';\nimport Attachment from './Attachment';\nimport { useFileAttachmentContext } from './AttachmentContext';\nimport { DeleteModal } from './DeleteModal';\nimport FilePreview from './FilePreview';\nimport { LightspeedChatBox } from './LightspeedChatBox';\nimport { LightspeedChatBoxHeader } from './LightspeedChatBoxHeader';\n\nconst useStyles = makeStyles(theme => ({\n body: {\n // remove default margin and padding from common elements\n '& h1, & h2, & h3, & h4, & h5, & h6, & p, & ul, & ol, & li': {\n margin: 0,\n padding: 0,\n },\n },\n header: {\n padding: `${theme.spacing(3)}px !important`,\n },\n headerMenu: {\n // align hamburger icon with title\n '& .pf-v6-c-button': {\n display: 'flex',\n alignItems: 'center',\n },\n },\n headerTitle: {\n justifyContent: 'left !important',\n },\n footer: {\n '&>.pf-chatbot__footer-container': {\n width: '95% !important',\n maxWidth: 'unset !important',\n },\n },\n footerPopover: {\n '& img': {\n maxWidth: '100%',\n },\n },\n}));\n\ntype LightspeedChatProps = {\n selectedModel: string;\n userName?: string;\n avatar?: string;\n profileLoading: boolean;\n handleSelectedModel: (item: string) => void;\n models: { label: string; value: string }[];\n};\n\nexport const LightspeedChat = ({\n selectedModel,\n userName,\n avatar,\n profileLoading,\n handleSelectedModel,\n models,\n}: LightspeedChatProps) => {\n const isMobile = useIsMobile();\n const classes = useStyles();\n const user = useBackstageUserIdentity();\n const [filterValue, setFilterValue] = React.useState<string>('');\n const [announcement, setAnnouncement] = React.useState<string>('');\n const [conversationId, setConversationId] = React.useState<string>('');\n const [isDrawerOpen, setIsDrawerOpen] = React.useState<boolean>(!isMobile);\n const [newChatCreated, setNewChatCreated] = React.useState<boolean>(false);\n const [isSendButtonDisabled, setIsSendButtonDisabled] =\n React.useState<boolean>(false);\n const [error, setError] = React.useState<Error | null>(null);\n const [targetConversationId, setTargetConversationId] =\n React.useState<string>('');\n const [isDeleteModalOpen, setIsDeleteModalOpen] =\n React.useState<boolean>(false);\n const { isReady, lastOpenedId, setLastOpenedId, clearLastOpenedId } =\n useLastOpenedConversation(user);\n\n const { fileContents, setFileContents, handleFileUpload } =\n useFileAttachmentContext();\n\n // Sync conversationId with lastOpenedId whenever lastOpenedId changes\n React.useEffect(() => {\n if (isReady && lastOpenedId !== null) {\n setConversationId(lastOpenedId);\n }\n }, [lastOpenedId, isReady]);\n\n const queryClient = useQueryClient();\n\n const { data: conversations = [] } = useConversations();\n const { mutateAsync: deleteConversation } = useDeleteConversation();\n const { allowed: hasDeleteAccess } = useLightspeedDeletePermission();\n const samplePrompts = useWelcomePrompts();\n React.useEffect(() => {\n if (user && lastOpenedId === null && isReady) {\n setConversationId(TEMP_CONVERSATION_ID);\n setNewChatCreated(true);\n }\n }, [user, isReady, lastOpenedId, setConversationId]);\n\n React.useEffect(() => {\n // Update last opened conversation whenever `conversationId` changes\n if (conversationId) {\n setLastOpenedId(conversationId);\n }\n }, [conversationId, setLastOpenedId]);\n\n const onStart = (conv_id: string) => {\n setConversationId(conv_id);\n };\n\n const onComplete = (message: string) => {\n setIsSendButtonDisabled(false);\n setAnnouncement(`Message from Bot: ${message}`);\n queryClient.invalidateQueries({\n queryKey: ['conversations'],\n });\n queryClient.invalidateQueries({\n queryKey: ['conversationMessages', conversationId],\n });\n setNewChatCreated(false);\n };\n\n const { conversationMessages, handleInputPrompt, scrollToBottomRef } =\n useConversationMessages(\n conversationId,\n userName,\n selectedModel,\n avatar,\n onComplete,\n onStart,\n );\n\n const [messages, setMessages] =\n React.useState<MessageProps[]>(conversationMessages);\n\n const sendMessage = (message: string | number) => {\n if (conversationId !== TEMP_CONVERSATION_ID) {\n setNewChatCreated(false);\n }\n setAnnouncement(\n `Message from User: ${prompt}. Message from Bot is loading.`,\n );\n handleInputPrompt(message.toString(), getAttachments(fileContents));\n setIsSendButtonDisabled(true);\n setFileContents([]);\n };\n\n const onNewChat = React.useCallback(() => {\n (async () => {\n if (conversationId !== TEMP_CONVERSATION_ID) {\n setMessages([]);\n setConversationId(TEMP_CONVERSATION_ID);\n setNewChatCreated(true);\n }\n })();\n }, [conversationId, setConversationId, setMessages]);\n\n const openDeleteModal = (conversation_id: string) => {\n setTargetConversationId(conversation_id);\n setIsDeleteModalOpen(true);\n };\n\n const handleDeleteConversation = React.useCallback(() => {\n (async () => {\n try {\n await deleteConversation({\n conversation_id: targetConversationId,\n invalidateCache: false,\n });\n if (targetConversationId === lastOpenedId) {\n onNewChat();\n clearLastOpenedId();\n }\n setIsDeleteModalOpen(false);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(e);\n setError(e);\n }\n })();\n }, [\n deleteConversation,\n clearLastOpenedId,\n lastOpenedId,\n onNewChat,\n targetConversationId,\n ]);\n\n const additionalMessageProps = React.useCallback(\n (conversationSummary: ConversationSummary) => ({\n menuItems: (\n <DropdownItem\n isDisabled={!hasDeleteAccess}\n onClick={() => openDeleteModal(conversationSummary.conversation_id)}\n >\n Delete\n </DropdownItem>\n ),\n }),\n [hasDeleteAccess],\n );\n const categorizedMessages = getCategorizeMessages(\n conversations,\n additionalMessageProps,\n );\n\n const filterConversations = React.useCallback(\n (targetValue: string) => {\n const filteredConversations = Object.entries(categorizedMessages).reduce(\n (acc, [key, items]) => {\n const filteredItems = items.filter(item =>\n item.text\n .toLocaleLowerCase('en-US')\n .includes(targetValue.toLocaleLowerCase('en-US')),\n );\n if (filteredItems.length > 0) {\n acc[key] = filteredItems;\n }\n return acc;\n },\n {} as any,\n );\n return filteredConversations;\n },\n [categorizedMessages],\n );\n\n React.useEffect(() => {\n setMessages(conversationMessages);\n }, [conversationMessages]);\n\n const onSelectActiveItem = React.useCallback(\n (\n _: React.MouseEvent | undefined,\n selectedItem: string | number | undefined,\n ) => {\n setNewChatCreated(false);\n setConversationId((c_id: string) => {\n if (c_id !== selectedItem) {\n return String(selectedItem);\n }\n return c_id;\n });\n scrollToBottomRef.current?.scrollToBottom();\n },\n [setConversationId, scrollToBottomRef],\n );\n\n const conversationFound = !!conversations.find(\n (c: ConversationSummary) => c.conversation_id === conversationId,\n );\n\n const welcomePrompts =\n (newChatCreated && conversationMessages.length === 0) ||\n (!conversationFound && conversationMessages.length === 0)\n ? samplePrompts?.map(prompt => ({\n title: prompt.title,\n message: prompt.message,\n onClick: () => {\n sendMessage(prompt.message);\n },\n }))\n : [];\n\n const handleFilter = React.useCallback((value: string) => {\n setFilterValue(value);\n }, []);\n\n const onDrawerToggle = React.useCallback(() => {\n setIsDrawerOpen(isOpen => !isOpen);\n }, []);\n\n const handleAttach = (data: File[], event: DropEvent) => {\n event.preventDefault();\n handleFileUpload(data);\n };\n\n if (error) {\n return (\n <Box padding={1}>\n <ErrorPanel error={error} />\n </Box>\n );\n }\n\n return (\n <>\n {isDeleteModalOpen && (\n <DeleteModal\n isOpen={isDeleteModalOpen}\n onClose={() => setIsDeleteModalOpen(false)}\n onConfirm={handleDeleteConversation}\n />\n )}\n <Chatbot\n displayMode={ChatbotDisplayMode.embedded}\n className={classes.body}\n >\n <ChatbotHeader className={classes.header}>\n <ChatbotHeaderMain>\n <ChatbotHeaderMenu\n aria-expanded={isDrawerOpen}\n onMenuToggle={() => setIsDrawerOpen(!isDrawerOpen)}\n className={classes.headerMenu}\n />\n <ChatbotHeaderTitle className={classes.headerTitle}>\n <Title headingLevel=\"h1\" size=\"3xl\">\n Developer Hub Lightspeed\n </Title>\n </ChatbotHeaderTitle>\n </ChatbotHeaderMain>\n\n <LightspeedChatBoxHeader\n selectedModel={selectedModel}\n handleSelectedModel={item => handleSelectedModel(item)}\n models={models}\n />\n </ChatbotHeader>\n <ChatbotConversationHistoryNav\n drawerPanelContentProps={{ isResizable: true, minSize: '200px' }}\n reverseButtonOrder\n displayMode={ChatbotDisplayMode.embedded}\n onDrawerToggle={onDrawerToggle}\n isDrawerOpen={isDrawerOpen}\n setIsDrawerOpen={setIsDrawerOpen}\n activeItemId={conversationId}\n onSelectActiveItem={onSelectActiveItem}\n conversations={filterConversations(filterValue)}\n onNewChat={newChatCreated ? undefined : onNewChat}\n handleTextInputChange={handleFilter}\n drawerContent={\n <>\n <ChatbotContent>\n <LightspeedChatBox\n userName={userName}\n messages={messages}\n profileLoading={profileLoading}\n announcement={announcement}\n ref={scrollToBottomRef}\n welcomePrompts={welcomePrompts}\n />\n </ChatbotContent>\n <ChatbotFooter className={classes.footer}>\n <FilePreview />\n <MessageBar\n onSendMessage={sendMessage}\n isSendButtonDisabled={isSendButtonDisabled}\n hasAttachButton\n handleAttach={handleAttach}\n hasMicrophoneButton\n />\n <ChatbotFootnote {...getFootnoteProps(classes.footerPopover)} />\n </ChatbotFooter>\n </>\n }\n />\n </Chatbot>\n <Attachment />\n </>\n );\n};\n"],"names":["React","prompt"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,SAAA,GAAY,WAAW,CAAU,KAAA,MAAA;AAA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A,aAAa,CAAG,EAAA,CAChE,CACF;AAAA;AAAA;AAEJ,GACF,kBACCA,cAAA,CAAA,aAAA,CAAA,UAAA,EAAA,IAAW,CACd,CAAA;AAEJ;;;;"}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import React__default from 'react';
|
|
2
|
+
import { useApi, configApiRef } from '@backstage/core-plugin-api';
|
|
2
3
|
import { makeStyles } from '@material-ui/core';
|
|
3
4
|
import { MessageBox, ChatbotWelcomePrompt, Message } from '@patternfly/chatbot';
|
|
5
|
+
import { Alert } from '@patternfly/react-core';
|
|
6
|
+
import { FUNCTION_DISCLAIMER, FUNCTION_DISCLAIMER_WITHOUT_QUESTION_VALIDATION } from '../const.esm.js';
|
|
7
|
+
import { useAutoScroll } from '../hooks/useAutoScroll.esm.js';
|
|
8
|
+
import { useBufferedMessages } from '../hooks/useBufferedMessages.esm.js';
|
|
4
9
|
|
|
5
10
|
const useStyles = makeStyles((theme) => ({
|
|
6
11
|
prompt: {
|
|
@@ -9,6 +14,9 @@ const useStyles = makeStyles((theme) => ({
|
|
|
9
14
|
container: {
|
|
10
15
|
maxWidth: "unset !important"
|
|
11
16
|
},
|
|
17
|
+
alert: {
|
|
18
|
+
background: "unset !important"
|
|
19
|
+
},
|
|
12
20
|
userMessageText: {
|
|
13
21
|
"& div.pf-chatbot__message--user": {
|
|
14
22
|
"& div.pf-chatbot__message-text": {
|
|
@@ -27,19 +35,62 @@ const LightspeedChatBox = React__default.forwardRef(
|
|
|
27
35
|
profileLoading,
|
|
28
36
|
welcomePrompts
|
|
29
37
|
}, ref) => {
|
|
30
|
-
const [cmessages, setCMessages] = React__default.useState(messages);
|
|
31
38
|
const classes = useStyles();
|
|
39
|
+
const scrollQueued = React__default.useRef(false);
|
|
40
|
+
const containerRef = React__default.useRef(null);
|
|
41
|
+
const configApi = useApi(configApiRef);
|
|
42
|
+
const questionValidationEnabled = configApi.getOptionalBoolean("lightspeed.questionValidation") ?? true;
|
|
43
|
+
const cmessages = useBufferedMessages(messages, 30);
|
|
44
|
+
const { autoScroll, scrollToBottom, scrollToTop } = useAutoScroll(containerRef);
|
|
45
|
+
React__default.useImperativeHandle(ref, () => ({
|
|
46
|
+
scrollToBottom: () => {
|
|
47
|
+
if (scrollQueued.current) return;
|
|
48
|
+
scrollQueued.current = true;
|
|
49
|
+
requestAnimationFrame(() => {
|
|
50
|
+
scrollToBottom();
|
|
51
|
+
scrollQueued.current = false;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}));
|
|
32
55
|
React__default.useEffect(() => {
|
|
33
|
-
|
|
34
|
-
|
|
56
|
+
if (!autoScroll || scrollQueued.current) return undefined;
|
|
57
|
+
scrollQueued.current = true;
|
|
58
|
+
const rafId = requestAnimationFrame(() => {
|
|
59
|
+
const container = containerRef.current;
|
|
60
|
+
if (!container) return;
|
|
61
|
+
setTimeout(() => {
|
|
62
|
+
container.scrollTo({
|
|
63
|
+
top: container.scrollHeight,
|
|
64
|
+
behavior: "auto"
|
|
65
|
+
});
|
|
66
|
+
}, 0);
|
|
67
|
+
scrollQueued.current = false;
|
|
68
|
+
});
|
|
69
|
+
return () => {
|
|
70
|
+
cancelAnimationFrame(rafId);
|
|
71
|
+
scrollQueued.current = false;
|
|
72
|
+
};
|
|
73
|
+
}, [autoScroll, cmessages, containerRef]);
|
|
35
74
|
const messageBoxClasses = `${classes.container} ${classes.userMessageText}`;
|
|
36
75
|
return /* @__PURE__ */ React__default.createElement(
|
|
37
76
|
MessageBox,
|
|
38
77
|
{
|
|
39
78
|
className: welcomePrompts.length ? `${messageBoxClasses} ${classes.prompt}` : messageBoxClasses,
|
|
40
79
|
announcement,
|
|
41
|
-
|
|
80
|
+
ref: containerRef,
|
|
81
|
+
onScrollToTopClick: scrollToTop,
|
|
82
|
+
onScrollToBottomClick: scrollToBottom
|
|
42
83
|
},
|
|
84
|
+
/* @__PURE__ */ React__default.createElement("div", null, /* @__PURE__ */ React__default.createElement(
|
|
85
|
+
Alert,
|
|
86
|
+
{
|
|
87
|
+
title: "Important",
|
|
88
|
+
variant: "info",
|
|
89
|
+
isInline: true,
|
|
90
|
+
className: classes.alert
|
|
91
|
+
},
|
|
92
|
+
questionValidationEnabled ? FUNCTION_DISCLAIMER : FUNCTION_DISCLAIMER_WITHOUT_QUESTION_VALIDATION
|
|
93
|
+
), /* @__PURE__ */ React__default.createElement("br", null)),
|
|
43
94
|
welcomePrompts.length ? /* @__PURE__ */ React__default.createElement(
|
|
44
95
|
ChatbotWelcomePrompt,
|
|
45
96
|
{
|
|
@@ -50,7 +101,7 @@ const LightspeedChatBox = React__default.forwardRef(
|
|
|
50
101
|
) : /* @__PURE__ */ React__default.createElement("br", null),
|
|
51
102
|
cmessages.map((message, index) => {
|
|
52
103
|
if (index === cmessages.length - 1) {
|
|
53
|
-
return /* @__PURE__ */ React__default.createElement(React__default.Fragment, { key: `${message.role}-${index}` }, /* @__PURE__ */ React__default.createElement(Message, { key: `${message.role}-${index}`, ...message })
|
|
104
|
+
return /* @__PURE__ */ React__default.createElement(React__default.Fragment, { key: `${message.role}-${index}` }, /* @__PURE__ */ React__default.createElement(Message, { key: `${message.role}-${index}`, ...message }));
|
|
54
105
|
}
|
|
55
106
|
return /* @__PURE__ */ React__default.createElement(Message, { key: `${message.role}-${index}`, ...message });
|
|
56
107
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LightspeedChatBox.esm.js","sources":["../../src/components/LightspeedChatBox.tsx"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\n\nimport { makeStyles } from '@material-ui/core';\nimport {\n ChatbotWelcomePrompt,\n Message,\n MessageBox,\n MessageProps,\n WelcomePrompt,\n} from '@patternfly/chatbot';\n\nconst useStyles = makeStyles(theme => ({\n prompt: {\n 'justify-content': 'flex-end',\n },\n container: {\n maxWidth: 'unset !important',\n },\n userMessageText: {\n '& div.pf-chatbot__message--user': {\n '& div.pf-chatbot__message-text': {\n '& p': {\n color: theme.palette.common.white,\n },\n },\n },\n },\n}));\n\ntype LightspeedChatBoxProps = {\n userName?: string;\n messages: MessageProps[];\n profileLoading: boolean;\n announcement: string | undefined;\n welcomePrompts: WelcomePrompt[];\n};\n\nexport const LightspeedChatBox = React.forwardRef(\n (\n {\n userName,\n messages,\n announcement,\n profileLoading,\n welcomePrompts,\n }: LightspeedChatBoxProps,\n ref: React.ForwardedRef<
|
|
1
|
+
{"version":3,"file":"LightspeedChatBox.esm.js","sources":["../../src/components/LightspeedChatBox.tsx"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\n\nimport { configApiRef, useApi } from '@backstage/core-plugin-api';\n\nimport { makeStyles } from '@material-ui/core';\nimport {\n ChatbotWelcomePrompt,\n Message,\n MessageBox,\n MessageBoxHandle,\n MessageProps,\n WelcomePrompt,\n} from '@patternfly/chatbot';\nimport { Alert } from '@patternfly/react-core';\n\nimport {\n FUNCTION_DISCLAIMER,\n FUNCTION_DISCLAIMER_WITHOUT_QUESTION_VALIDATION,\n} from '../const';\nimport { useAutoScroll } from '../hooks/useAutoScroll';\nimport { useBufferedMessages } from '../hooks/useBufferedMessages';\n\nconst useStyles = makeStyles(theme => ({\n prompt: {\n 'justify-content': 'flex-end',\n },\n container: {\n maxWidth: 'unset !important',\n },\n alert: {\n background: 'unset !important',\n },\n userMessageText: {\n '& div.pf-chatbot__message--user': {\n '& div.pf-chatbot__message-text': {\n '& p': {\n color: theme.palette.common.white,\n },\n },\n },\n },\n}));\n\ntype LightspeedChatBoxProps = {\n userName?: string;\n messages: MessageProps[];\n profileLoading: boolean;\n announcement: string | undefined;\n welcomePrompts: WelcomePrompt[];\n};\n\nexport interface ScrollContainerHandle {\n scrollToBottom: () => void;\n}\n\nexport const LightspeedChatBox = React.forwardRef(\n (\n {\n userName,\n messages,\n announcement,\n profileLoading,\n welcomePrompts,\n }: LightspeedChatBoxProps,\n ref: React.ForwardedRef<ScrollContainerHandle>,\n ) => {\n const classes = useStyles();\n const scrollQueued = React.useRef(false);\n const containerRef = React.useRef<MessageBoxHandle>(null);\n\n const configApi = useApi(configApiRef);\n const questionValidationEnabled =\n configApi.getOptionalBoolean('lightspeed.questionValidation') ?? true;\n const cmessages = useBufferedMessages(messages, 30);\n const { autoScroll, scrollToBottom, scrollToTop } =\n useAutoScroll(containerRef);\n\n React.useImperativeHandle(ref, () => ({\n scrollToBottom: () => {\n if (scrollQueued.current) return;\n scrollQueued.current = true;\n\n requestAnimationFrame(() => {\n scrollToBottom();\n scrollQueued.current = false;\n });\n },\n }));\n\n // Auto-scrolls to the latest message\n React.useEffect(() => {\n if (!autoScroll || scrollQueued.current) return undefined;\n\n scrollQueued.current = true;\n\n const rafId = requestAnimationFrame(() => {\n const container = containerRef.current;\n if (!container) return;\n\n setTimeout(() => {\n container.scrollTo({\n top: container.scrollHeight,\n behavior: 'auto',\n });\n }, 0);\n\n scrollQueued.current = false;\n });\n\n return () => {\n cancelAnimationFrame(rafId);\n scrollQueued.current = false;\n };\n\n // eslint-disable-next-line\n }, [autoScroll, cmessages, containerRef]);\n\n const messageBoxClasses = `${classes.container} ${classes.userMessageText}`;\n return (\n <MessageBox\n className={\n welcomePrompts.length\n ? `${messageBoxClasses} ${classes.prompt}`\n : messageBoxClasses\n }\n announcement={announcement}\n ref={containerRef}\n onScrollToTopClick={scrollToTop}\n onScrollToBottomClick={scrollToBottom}\n >\n <div>\n <Alert\n title=\"Important\"\n variant=\"info\"\n isInline\n className={classes.alert}\n >\n {questionValidationEnabled\n ? FUNCTION_DISCLAIMER\n : FUNCTION_DISCLAIMER_WITHOUT_QUESTION_VALIDATION}\n </Alert>\n <br />\n </div>\n {welcomePrompts.length ? (\n <ChatbotWelcomePrompt\n title={`Hello, ${profileLoading ? '...' : (userName ?? 'Guest')}`}\n description=\"How can I help you today?\"\n prompts={welcomePrompts}\n />\n ) : (\n <br />\n )}\n {cmessages.map((message, index) => {\n if (index === cmessages.length - 1) {\n return (\n <React.Fragment key={`${message.role}-${index}`}>\n <Message key={`${message.role}-${index}`} {...message} />\n </React.Fragment>\n );\n }\n return <Message key={`${message.role}-${index}`} {...message} />;\n })}\n </MessageBox>\n );\n },\n);\n"],"names":["React"],"mappings":";;;;;;;;;AAsCA,MAAM,SAAA,GAAY,WAAW,CAAU,KAAA,MAAA;AAAA,EACrC,MAAQ,EAAA;AAAA,IACN,iBAAmB,EAAA;AAAA,GACrB;AAAA,EACA,SAAW,EAAA;AAAA,IACT,QAAU,EAAA;AAAA,GACZ;AAAA,EACA,KAAO,EAAA;AAAA,IACL,UAAY,EAAA;AAAA,GACd;AAAA,EACA,eAAiB,EAAA;AAAA,IACf,iCAAmC,EAAA;AAAA,MACjC,gCAAkC,EAAA;AAAA,QAChC,KAAO,EAAA;AAAA,UACL,KAAA,EAAO,KAAM,CAAA,OAAA,CAAQ,MAAO,CAAA;AAAA;AAC9B;AACF;AACF;AAEJ,CAAE,CAAA,CAAA;AAcK,MAAM,oBAAoBA,cAAM,CAAA,UAAA;AAAA,EACrC,CACE;AAAA,IACE,QAAA;AAAA,IACA,QAAA;AAAA,IACA,YAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,KAEF,GACG,KAAA;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L,SAAU,CAAA,GAAA,CAAI,CAAC,OAAA,EAAS,KAAU,KAAA;AACjC,QAAI,IAAA,KAAA,KAAU,SAAU,CAAA,MAAA,GAAS,CAAG,EAAA;AAClC,UACE,uBAAAA,cAAA,CAAA,aAAA,CAACA,eAAM,QAAN,EAAA,EAAe,KAAK,CAAG,EAAA,OAAA,CAAQ,IAAI,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,EAAA,+CAC1C,OAAQ,EAAA,EAAA,GAAA,EAAK,GAAG,OAAQ,CAAA,IAAI,IAAI,KAAK,CAAA,CAAA,EAAK,GAAG,OAAA,EAAS,CACzD,CAAA;AAAA;AAGJ,QAAO,uBAAAA,cAAA,CAAA,aAAA,CAAC,OAAQ,EAAA,EAAA,GAAA,EAAK,CAAG,EAAA,OAAA,CAAQ,IAAI,CAAI,CAAA,EAAA,KAAK,CAAK,CAAA,EAAA,GAAG,OAAS,EAAA,CAAA;AAAA,OAC/D;AAAA,KACH;AAAA;AAGN;;;;"}
|
|
@@ -7,6 +7,7 @@ import { QueryClientProvider } from '@tanstack/react-query';
|
|
|
7
7
|
import { useAllModels } from '../hooks/useAllModels.esm.js';
|
|
8
8
|
import { useLightspeedViewPermission } from '../hooks/useLightspeedViewPermission.esm.js';
|
|
9
9
|
import queryClient from '../utils/queryClient.esm.js';
|
|
10
|
+
import FileAttachmentContextProvider from './AttachmentContext.esm.js';
|
|
10
11
|
import { LightspeedChat } from './LightSpeedChat.esm.js';
|
|
11
12
|
import PermissionRequiredState from './PermissionRequiredState.esm.js';
|
|
12
13
|
|
|
@@ -49,7 +50,7 @@ const LightspeedPageInner = () => {
|
|
|
49
50
|
if (loading) {
|
|
50
51
|
return null;
|
|
51
52
|
}
|
|
52
|
-
return /* @__PURE__ */ React__default.createElement(Page, { themeId: "tool" }, /* @__PURE__ */ React__default.createElement(Content, { className: classes.container }, !hasViewAccess ? /* @__PURE__ */ React__default.createElement(PermissionRequiredState, null) : /* @__PURE__ */ React__default.createElement(
|
|
53
|
+
return /* @__PURE__ */ React__default.createElement(Page, { themeId: "tool" }, /* @__PURE__ */ React__default.createElement(Content, { className: classes.container }, !hasViewAccess ? /* @__PURE__ */ React__default.createElement(PermissionRequiredState, null) : /* @__PURE__ */ React__default.createElement(FileAttachmentContextProvider, null, /* @__PURE__ */ React__default.createElement(
|
|
53
54
|
LightspeedChat,
|
|
54
55
|
{
|
|
55
56
|
selectedModel,
|
|
@@ -61,7 +62,7 @@ const LightspeedPageInner = () => {
|
|
|
61
62
|
avatar: profile?.picture,
|
|
62
63
|
profileLoading
|
|
63
64
|
}
|
|
64
|
-
)));
|
|
65
|
+
))));
|
|
65
66
|
};
|
|
66
67
|
const LightspeedPage = () => {
|
|
67
68
|
return /* @__PURE__ */ React__default.createElement(QueryClientProvider, { client: queryClient }, /* @__PURE__ */ React__default.createElement(LightspeedPageInner, null));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LightspeedPage.esm.js","sources":["../../src/components/LightspeedPage.tsx"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\nimport { useAsync } from 'react-use';\n\nimport { Content, Page } from '@backstage/core-components';\nimport { identityApiRef, useApi } from '@backstage/core-plugin-api';\n\nimport { createStyles, makeStyles, useTheme } from '@material-ui/core/styles';\nimport { QueryClientProvider } from '@tanstack/react-query';\n\nimport { useAllModels } from '../hooks/useAllModels';\nimport { useLightspeedViewPermission } from '../hooks/useLightspeedViewPermission';\nimport queryClient from '../utils/queryClient';\nimport { LightspeedChat } from './LightSpeedChat';\nimport PermissionRequiredState from './PermissionRequiredState';\n\nconst useStyles = makeStyles(() =>\n createStyles({\n container: {\n padding: '0px',\n },\n }),\n);\n\nconst THEME_DARK = 'dark';\nconst THEME_DARK_CLASS = 'pf-v6-theme-dark';\n\nconst LightspeedPageInner = () => {\n const classes = useStyles();\n const {\n palette: { type },\n } = useTheme();\n\n const identityApi = useApi(identityApiRef);\n\n const { data: models } = useAllModels();\n const { allowed: hasViewAccess, loading } = useLightspeedViewPermission();\n\n const { value: profile, loading: profileLoading } = useAsync(\n async () => await identityApi.getProfileInfo(),\n );\n\n const [selectedModel, setSelectedModel] = React.useState('');\n\n const modelsItems = React.useMemo(\n () => (models ? models.map(m => ({ label: m.id, value: m.id })) : []),\n [models],\n );\n\n React.useEffect(() => {\n const htmlTagElement = document.documentElement;\n if (type === THEME_DARK) {\n htmlTagElement.classList.add(THEME_DARK_CLASS);\n } else {\n htmlTagElement.classList.remove(THEME_DARK_CLASS);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [type]);\n\n React.useEffect(() => {\n if (modelsItems.length > 0) setSelectedModel(modelsItems[0].value);\n }, [modelsItems]);\n\n if (loading) {\n return null;\n }\n\n return (\n <Page themeId=\"tool\">\n <Content className={classes.container}>\n {!hasViewAccess ? (\n <PermissionRequiredState />\n ) : (\n <LightspeedChat\n
|
|
1
|
+
{"version":3,"file":"LightspeedPage.esm.js","sources":["../../src/components/LightspeedPage.tsx"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\nimport { useAsync } from 'react-use';\n\nimport { Content, Page } from '@backstage/core-components';\nimport { identityApiRef, useApi } from '@backstage/core-plugin-api';\n\nimport { createStyles, makeStyles, useTheme } from '@material-ui/core/styles';\nimport { QueryClientProvider } from '@tanstack/react-query';\n\nimport { useAllModels } from '../hooks/useAllModels';\nimport { useLightspeedViewPermission } from '../hooks/useLightspeedViewPermission';\nimport queryClient from '../utils/queryClient';\nimport FileAttachmentContextProvider from './AttachmentContext';\nimport { LightspeedChat } from './LightSpeedChat';\nimport PermissionRequiredState from './PermissionRequiredState';\n\nconst useStyles = makeStyles(() =>\n createStyles({\n container: {\n padding: '0px',\n },\n }),\n);\n\nconst THEME_DARK = 'dark';\nconst THEME_DARK_CLASS = 'pf-v6-theme-dark';\n\nconst LightspeedPageInner = () => {\n const classes = useStyles();\n const {\n palette: { type },\n } = useTheme();\n\n const identityApi = useApi(identityApiRef);\n\n const { data: models } = useAllModels();\n const { allowed: hasViewAccess, loading } = useLightspeedViewPermission();\n\n const { value: profile, loading: profileLoading } = useAsync(\n async () => await identityApi.getProfileInfo(),\n );\n\n const [selectedModel, setSelectedModel] = React.useState('');\n\n const modelsItems = React.useMemo(\n () => (models ? models.map(m => ({ label: m.id, value: m.id })) : []),\n [models],\n );\n\n React.useEffect(() => {\n const htmlTagElement = document.documentElement;\n if (type === THEME_DARK) {\n htmlTagElement.classList.add(THEME_DARK_CLASS);\n } else {\n htmlTagElement.classList.remove(THEME_DARK_CLASS);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [type]);\n\n React.useEffect(() => {\n if (modelsItems.length > 0) setSelectedModel(modelsItems[0].value);\n }, [modelsItems]);\n\n if (loading) {\n return null;\n }\n\n return (\n <Page themeId=\"tool\">\n <Content className={classes.container}>\n {!hasViewAccess ? (\n <PermissionRequiredState />\n ) : (\n <FileAttachmentContextProvider>\n <LightspeedChat\n selectedModel={selectedModel}\n handleSelectedModel={item => {\n setSelectedModel(item);\n }}\n models={modelsItems}\n userName={profile?.displayName}\n avatar={profile?.picture}\n profileLoading={profileLoading}\n />\n </FileAttachmentContextProvider>\n )}\n </Content>\n </Page>\n );\n};\n\nexport const LightspeedPage = () => {\n return (\n <QueryClientProvider client={queryClient}>\n <LightspeedPageInner />\n </QueryClientProvider>\n );\n};\n"],"names":["React"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,SAAY,GAAA,UAAA;AAAA,EAAW,MAC3B,YAAa,CAAA;AAAA,IACX,SAAW,EAAA;AAAA,MACT,OAAS,EAAA;AAAA;AACX,GACD;AACH,CAAA;AAEA,MAAM,UAAa,GAAA,MAAA;AACnB,MAAM,gBAAmB,GAAA,kBAAA;AAEzB,MAAM,sBAAsB,MAAM;AAChC,EAAA,MAAM,UAAU,SAAU,EAAA;AAC1B,EAAM,MAAA;AAAA,IACJ,OAAA,EAAS,EAAE,IAAK;AAAA,MACd,QAAS,EAAA;AAEb,EAAM,MAAA,WAAA,GAAc,OAAO,cAAc,CAAA;AAEzC,EAAA,MAAM,EAAE,IAAA,EAAM,MAAO,EAAA,GAAI,YAAa,EAAA;AACtC,EAAA,MAAM,EAAE,OAAA,EAAS,aAAe,EAAA,OAAA,KAAY,2BAA4B,EAAA;AAExE,EAAA,MAAM,EAAE,KAAA,EAAO,OAAS,EAAA,OAAA,EAAS,gBAAmB,GAAA,QAAA;AAAA,IAClD,YAAY,MAAM,WAAA,CAAY,cAAe;AAAA,GAC/C;AAEA,EAAA,MAAM,CAAC,aAAe,EAAA,gBAAgB,CAAI,GAAAA,cAAA,CAAM,SAAS,EAAE,CAAA;AAE3D,EAAA,MAAM,cAAcA,cAAM,CAAA,OAAA;AAAA,IACxB,MAAO,MAAA,GAAS,MAAO,CAAA,GAAA,CAAI,QAAM,EAAE,KAAA,EAAO,CAAE,CAAA,EAAA,EAAI,KAAO,EAAA,CAAA,CAAE,EAAG,EAAA,CAAE,IAAI,EAAC;AAAA,IACnE,CAAC,MAAM;AAAA,GACT;AAEA,EAAAA,cAAA,CAAM,UAAU,MAAM;AACpB,IAAA,MAAM,iBAAiB,QAAS,CAAA,eAA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1
1
|
const TEMP_CONVERSATION_ID = "temp-conversation-id";
|
|
2
|
+
const FUNCTION_DISCLAIMER_WITHOUT_QUESTION_VALIDATION = `Red Hat Developer Hub Lightspeed can answer questions on many topics using your configured models. Lightspeed's responses are influenced by the Red Hat Developer Hub documentation but Lightspeed does not have access to your Software Catalog, TechDocs, or Templates etc. Do not include personal or sensitive information in your input. Interactions with Developer Hub Lightspeed may be reviewed and used to improve products or services.`;
|
|
3
|
+
const FUNCTION_DISCLAIMER = `Red Hat Developer Hub Lightspeed can answer questions on many topics using your configured models. Lightspeed's responses are influenced by the Red Hat Developer Hub documentation but Lightspeed does not have access to your Software Catalog, TechDocs, or Templates etc. Lightspeed uses question (prompt) validation to ensure that conversations remain focused on technical topics relevant to Red Hat Developer Hub, such as Backstage, Kubernetes, and OpenShift. Do not include personal or sensitive information in your input. Interactions with Developer Hub Lightspeed may be reviewed and used to improve products or services.`;
|
|
4
|
+
const createPrompt = (title, message) => {
|
|
5
|
+
return { title, message };
|
|
6
|
+
};
|
|
7
|
+
const DEFAULT_SAMPLE_PROMPTS = [
|
|
8
|
+
createPrompt(
|
|
9
|
+
"Get Help On Code Readability",
|
|
10
|
+
"Can you suggest techniques I can use to make my code more readable and maintainable?"
|
|
11
|
+
),
|
|
12
|
+
createPrompt(
|
|
13
|
+
"Get Help With Debugging",
|
|
14
|
+
"My application is throwing an error when trying to connect to the database. Can you help me identify the issue?"
|
|
15
|
+
),
|
|
16
|
+
createPrompt(
|
|
17
|
+
"Explain a Development Concept",
|
|
18
|
+
"Can you explain how microservices architecture works and its advantages over a monolithic design?"
|
|
19
|
+
),
|
|
20
|
+
createPrompt(
|
|
21
|
+
"Suggest Code Optimizations",
|
|
22
|
+
"Can you suggest common ways to optimize code to achieve better performance?"
|
|
23
|
+
),
|
|
24
|
+
createPrompt(
|
|
25
|
+
"Documentation Summary",
|
|
26
|
+
"Can you summarize the documentation for implementing OAuth 2.0 authentication in a web app?"
|
|
27
|
+
),
|
|
28
|
+
createPrompt(
|
|
29
|
+
"Workflows With Git",
|
|
30
|
+
"I want to make changes to code on another branch without loosing my existing work. What is the procedure to do this using Git?"
|
|
31
|
+
),
|
|
32
|
+
createPrompt(
|
|
33
|
+
"Suggest Testing Strategies",
|
|
34
|
+
"Can you recommend some common testing strategies that will make my application robust and error-free?"
|
|
35
|
+
),
|
|
36
|
+
createPrompt(
|
|
37
|
+
"Demystify Sorting Algorithms",
|
|
38
|
+
"Can you explain the difference between a quicksort and a merge sort algorithm, and when to use each?"
|
|
39
|
+
),
|
|
40
|
+
createPrompt(
|
|
41
|
+
"Understand Event-Driven Architecture",
|
|
42
|
+
"Can you explain what event-driven architecture is and when it\u2019s beneficial to use it in software development?"
|
|
43
|
+
)
|
|
44
|
+
];
|
|
45
|
+
const RHDH_SAMPLE_PROMPTS = [
|
|
46
|
+
createPrompt(
|
|
47
|
+
"Deploy With Tekton",
|
|
48
|
+
"Can you help me automate the deployment of my application using Tekton pipelines?"
|
|
49
|
+
),
|
|
50
|
+
createPrompt(
|
|
51
|
+
"Create An OpenShift Deployment",
|
|
52
|
+
"Can you guide me through creating a new deployment in OpenShift for a containerized application?"
|
|
53
|
+
),
|
|
54
|
+
createPrompt(
|
|
55
|
+
"Getting Started with Backstage",
|
|
56
|
+
"Can you guide me through the first steps to start using Backstage as a developer, like exploring the Software Catalog and adding my service?"
|
|
57
|
+
)
|
|
58
|
+
];
|
|
2
59
|
|
|
3
|
-
export { TEMP_CONVERSATION_ID };
|
|
60
|
+
export { DEFAULT_SAMPLE_PROMPTS, FUNCTION_DISCLAIMER, FUNCTION_DISCLAIMER_WITHOUT_QUESTION_VALIDATION, RHDH_SAMPLE_PROMPTS, TEMP_CONVERSATION_ID };
|
|
4
61
|
//# sourceMappingURL=const.esm.js.map
|
package/dist/const.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"const.esm.js","sources":["../src/const.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const TEMP_CONVERSATION_ID = 'temp-conversation-id';\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"const.esm.js","sources":["../src/const.ts"],"sourcesContent":["import { SamplePrompts } from './types';\n\n/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const TEMP_CONVERSATION_ID = 'temp-conversation-id';\n\nexport const FUNCTION_DISCLAIMER_WITHOUT_QUESTION_VALIDATION = `Red Hat Developer Hub Lightspeed can answer questions on many topics using your configured models. Lightspeed's responses are influenced by the Red Hat Developer Hub documentation but Lightspeed does not have access to your Software Catalog, TechDocs, or Templates etc. Do not include personal or sensitive information in your input. Interactions with Developer Hub Lightspeed may be reviewed and used to improve products or services.`;\n\nexport const FUNCTION_DISCLAIMER = `Red Hat Developer Hub Lightspeed can answer questions on many topics using your configured models. Lightspeed's responses are influenced by the Red Hat Developer Hub documentation but Lightspeed does not have access to your Software Catalog, TechDocs, or Templates etc. Lightspeed uses question (prompt) validation to ensure that conversations remain focused on technical topics relevant to Red Hat Developer Hub, such as Backstage, Kubernetes, and OpenShift. Do not include personal or sensitive information in your input. Interactions with Developer Hub Lightspeed may be reviewed and used to improve products or services.`;\n\nconst createPrompt = (title: string, message: string) => {\n return { title, message };\n};\n\nexport const DEFAULT_SAMPLE_PROMPTS: SamplePrompts = [\n createPrompt(\n 'Get Help On Code Readability',\n 'Can you suggest techniques I can use to make my code more readable and maintainable?',\n ),\n createPrompt(\n 'Get Help With Debugging',\n 'My application is throwing an error when trying to connect to the database. Can you help me identify the issue?',\n ),\n createPrompt(\n 'Explain a Development Concept',\n 'Can you explain how microservices architecture works and its advantages over a monolithic design?',\n ),\n createPrompt(\n 'Suggest Code Optimizations',\n 'Can you suggest common ways to optimize code to achieve better performance?',\n ),\n createPrompt(\n 'Documentation Summary',\n 'Can you summarize the documentation for implementing OAuth 2.0 authentication in a web app?',\n ),\n createPrompt(\n 'Workflows With Git',\n 'I want to make changes to code on another branch without loosing my existing work. What is the procedure to do this using Git?',\n ),\n createPrompt(\n 'Suggest Testing Strategies',\n 'Can you recommend some common testing strategies that will make my application robust and error-free?',\n ),\n createPrompt(\n 'Demystify Sorting Algorithms',\n 'Can you explain the difference between a quicksort and a merge sort algorithm, and when to use each?',\n ),\n createPrompt(\n 'Understand Event-Driven Architecture',\n 'Can you explain what event-driven architecture is and when it’s beneficial to use it in software development?',\n ),\n];\n\nexport const RHDH_SAMPLE_PROMPTS: SamplePrompts = [\n createPrompt(\n 'Deploy With Tekton',\n 'Can you help me automate the deployment of my application using Tekton pipelines?',\n ),\n createPrompt(\n 'Create An OpenShift Deployment',\n 'Can you guide me through creating a new deployment in OpenShift for a containerized application?',\n ),\n createPrompt(\n 'Getting Started with Backstage',\n 'Can you guide me through the first steps to start using Backstage as a developer, like exploring the Software Catalog and adding my service?',\n ),\n];\n"],"names":[],"mappings":"AAiBO,MAAM,oBAAuB,GAAA;AAE7B,MAAM,+CAAkD,GAAA,CAAA,kbAAA;AAExD,MAAM,mBAAsB,GAAA,CAAA,gnBAAA;AAEnC,MAAM,YAAA,GAAe,CAAC,KAAA,EAAe,OAAoB,KAAA;AACvD,EAAO,OAAA,EAAE,OAAO,OAAQ,EAAA;AAC1B,CAAA;AAEO,MAAM,sBAAwC,GAAA;AAAA,EACnD,YAAA;AAAA,IACE,8BAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,yBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,+BAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,4BAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,uBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,oBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,4BAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,8BAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,sCAAA;AAAA,IACA;AAAA;AAEJ;AAEO,MAAM,mBAAqC,GAAA;AAAA,EAChD,YAAA;AAAA,IACE,oBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,gCAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,YAAA;AAAA,IACE,gCAAA;AAAA,IACA;AAAA;AAEJ;;;;"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import React__default from 'react';
|
|
2
|
+
|
|
3
|
+
const useAutoScroll = (containerRef, options = {}) => {
|
|
4
|
+
const { deltaUp = 10, deltaDown = 60, delay = 200 } = options;
|
|
5
|
+
const [autoScroll, setAutoScroll] = React__default.useState(true);
|
|
6
|
+
const lastScrollTop = React__default.useRef(0);
|
|
7
|
+
const manualScrollInterrupted = React__default.useRef(false);
|
|
8
|
+
const debounceTimeout = React__default.useRef(null);
|
|
9
|
+
const onScroll = React__default.useCallback(() => {
|
|
10
|
+
const container = containerRef.current;
|
|
11
|
+
if (!container) return;
|
|
12
|
+
const currentScrollTop = container.scrollTop;
|
|
13
|
+
const isScrollingDown = currentScrollTop > lastScrollTop.current;
|
|
14
|
+
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
|
|
15
|
+
const delta = isScrollingDown ? deltaDown : deltaUp;
|
|
16
|
+
const isAtBottom = distanceFromBottom <= delta;
|
|
17
|
+
if (debounceTimeout.current) clearTimeout(debounceTimeout.current);
|
|
18
|
+
if (isAtBottom && manualScrollInterrupted.current && isScrollingDown) {
|
|
19
|
+
debounceTimeout.current = setTimeout(() => {
|
|
20
|
+
manualScrollInterrupted.current = false;
|
|
21
|
+
setAutoScroll(true);
|
|
22
|
+
}, delay);
|
|
23
|
+
}
|
|
24
|
+
if (!isAtBottom && !manualScrollInterrupted.current) {
|
|
25
|
+
manualScrollInterrupted.current = true;
|
|
26
|
+
setAutoScroll(false);
|
|
27
|
+
}
|
|
28
|
+
lastScrollTop.current = currentScrollTop;
|
|
29
|
+
}, [containerRef, deltaUp, deltaDown, delay]);
|
|
30
|
+
React__default.useEffect(() => {
|
|
31
|
+
const container = containerRef.current;
|
|
32
|
+
if (!container) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
container.addEventListener("scroll", onScroll, { passive: true });
|
|
36
|
+
return () => {
|
|
37
|
+
container.removeEventListener("scroll", onScroll);
|
|
38
|
+
if (debounceTimeout.current) clearTimeout(debounceTimeout.current);
|
|
39
|
+
};
|
|
40
|
+
}, [onScroll, containerRef]);
|
|
41
|
+
const resumeAutoScroll = React__default.useCallback(() => {
|
|
42
|
+
manualScrollInterrupted.current = false;
|
|
43
|
+
setAutoScroll(true);
|
|
44
|
+
}, []);
|
|
45
|
+
const stopAutoScroll = React__default.useCallback(() => {
|
|
46
|
+
manualScrollInterrupted.current = true;
|
|
47
|
+
setAutoScroll(false);
|
|
48
|
+
}, []);
|
|
49
|
+
const scrollToTop = React__default.useCallback(() => {
|
|
50
|
+
stopAutoScroll();
|
|
51
|
+
const container = containerRef.current;
|
|
52
|
+
if (!container) return;
|
|
53
|
+
container.scrollTo({
|
|
54
|
+
top: 0,
|
|
55
|
+
behavior: "smooth"
|
|
56
|
+
});
|
|
57
|
+
}, [stopAutoScroll, containerRef]);
|
|
58
|
+
const scrollToBottom = React__default.useCallback(() => {
|
|
59
|
+
const container = containerRef.current;
|
|
60
|
+
if (container) {
|
|
61
|
+
container.scrollTo({
|
|
62
|
+
top: container.scrollHeight,
|
|
63
|
+
behavior: "smooth"
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
resumeAutoScroll();
|
|
67
|
+
}, [resumeAutoScroll, containerRef]);
|
|
68
|
+
return {
|
|
69
|
+
autoScroll,
|
|
70
|
+
resumeAutoScroll,
|
|
71
|
+
stopAutoScroll,
|
|
72
|
+
scrollToBottom,
|
|
73
|
+
scrollToTop
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export { useAutoScroll };
|
|
78
|
+
//# sourceMappingURL=useAutoScroll.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAutoScroll.esm.js","sources":["../../src/hooks/useAutoScroll.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport React from 'react';\n\ninterface useAutoScrollOptions {\n deltaUp?: number;\n deltaDown?: number;\n delay?: number;\n}\n\nexport const useAutoScroll = (\n containerRef: React.RefObject<HTMLElement>,\n options: useAutoScrollOptions = {},\n) => {\n const { deltaUp = 10, deltaDown = 60, delay = 200 } = options;\n\n const [autoScroll, setAutoScroll] = React.useState(true);\n const lastScrollTop = React.useRef(0);\n const manualScrollInterrupted = React.useRef(false);\n const debounceTimeout = React.useRef<NodeJS.Timeout | null>(null);\n\n const onScroll = React.useCallback(() => {\n const container = containerRef.current;\n if (!container) return;\n\n const currentScrollTop = container.scrollTop;\n const isScrollingDown = currentScrollTop > lastScrollTop.current;\n\n const distanceFromBottom =\n container.scrollHeight - container.scrollTop - container.clientHeight;\n\n const delta = isScrollingDown ? deltaDown : deltaUp;\n const isAtBottom = distanceFromBottom <= delta;\n\n if (debounceTimeout.current) clearTimeout(debounceTimeout.current);\n\n if (isAtBottom && manualScrollInterrupted.current && isScrollingDown) {\n debounceTimeout.current = setTimeout(() => {\n manualScrollInterrupted.current = false;\n setAutoScroll(true);\n }, delay);\n }\n\n if (!isAtBottom && !manualScrollInterrupted.current) {\n manualScrollInterrupted.current = true;\n setAutoScroll(false);\n }\n\n lastScrollTop.current = currentScrollTop;\n }, [containerRef, deltaUp, deltaDown, delay]);\n\n React.useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n\n container.addEventListener('scroll', onScroll, { passive: true });\n return () => {\n container.removeEventListener('scroll', onScroll);\n if (debounceTimeout.current) clearTimeout(debounceTimeout.current);\n };\n }, [onScroll, containerRef]);\n\n const resumeAutoScroll = React.useCallback(() => {\n manualScrollInterrupted.current = false;\n setAutoScroll(true);\n }, []);\n\n const stopAutoScroll = React.useCallback(() => {\n manualScrollInterrupted.current = true;\n setAutoScroll(false);\n }, []);\n\n const scrollToTop = React.useCallback(() => {\n stopAutoScroll();\n const container = containerRef.current;\n if (!container) return;\n\n container.scrollTo({\n top: 0,\n behavior: 'smooth',\n });\n }, [stopAutoScroll, containerRef]);\n\n const scrollToBottom = React.useCallback(() => {\n const container = containerRef.current;\n if (container) {\n container.scrollTo({\n top: container.scrollHeight,\n behavior: 'smooth',\n });\n }\n resumeAutoScroll();\n }, [resumeAutoScroll, containerRef]);\n\n return {\n autoScroll,\n resumeAutoScroll,\n stopAutoScroll,\n scrollToBottom,\n scrollToTop,\n };\n};\n"],"names":["React"],"mappings":";;AAuBO,MAAM,aAAgB,GAAA,CAC3B,YACA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AAA;AAAA,MACjB,GAAK,EAAA,CAAA;AAAA,MACL,QAAU,EAAA;AAAA,KACX,CAAA;AAAA,GACA,EAAA,CAAC,cAAgB,EAAA,YAAY,CAAC,CAAA;AAEjC,EAAM,MAAA,cAAA,GAAiBA,cAAM,CAAA,WAAA,CAAY,MAAM;AAC7C,IAAA,MAAM,YAAY,YAAa,CAAA,OAAA;AAC/B,IAAA,IAAI,SAAW,EAAA;AACb,MAAA,SAAA,CAAU,QAAS,CAAA;AAAA,QACjB,KAAK,SAAU,CAAA,YAAA;AAAA,QACf,QAAU,EAAA;AAAA,OACX,CAAA;AAAA;AAEH,IAAiB,gBAAA,EAAA;AAAA,GAChB,EAAA,CAAC,gBAAkB,EAAA,YAAY,CAAC,CAAA;AAEnC,EAAO,OAAA;AAAA,IACL,UAAA;AAAA,IACA,gBAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF;AACF;;;;"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import React__default from 'react';
|
|
2
|
+
|
|
3
|
+
const useBufferedMessages = (messages, interval = 30) => {
|
|
4
|
+
const [bufferedMessages, setBufferedMessages] = React__default.useState(messages);
|
|
5
|
+
const lastUpdateTime = React__default.useRef(0);
|
|
6
|
+
const animationFrame = React__default.useRef(null);
|
|
7
|
+
React__default.useEffect(() => {
|
|
8
|
+
const now = Date.now();
|
|
9
|
+
const update = () => {
|
|
10
|
+
setBufferedMessages(messages);
|
|
11
|
+
lastUpdateTime.current = now;
|
|
12
|
+
};
|
|
13
|
+
if (now - lastUpdateTime.current > interval) {
|
|
14
|
+
update();
|
|
15
|
+
} else {
|
|
16
|
+
if (animationFrame.current) cancelAnimationFrame(animationFrame.current);
|
|
17
|
+
animationFrame.current = requestAnimationFrame(update);
|
|
18
|
+
}
|
|
19
|
+
return () => {
|
|
20
|
+
if (animationFrame.current) cancelAnimationFrame(animationFrame.current);
|
|
21
|
+
};
|
|
22
|
+
}, [messages, interval]);
|
|
23
|
+
return bufferedMessages;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export { useBufferedMessages };
|
|
27
|
+
//# sourceMappingURL=useBufferedMessages.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useBufferedMessages.esm.js","sources":["../../src/hooks/useBufferedMessages.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport React from 'react';\n\nexport const useBufferedMessages = <T>(messages: T[], interval = 30): T[] => {\n const [bufferedMessages, setBufferedMessages] = React.useState(messages);\n const lastUpdateTime = React.useRef(0);\n const animationFrame = React.useRef<number | null>(null);\n\n React.useEffect(() => {\n const now = Date.now();\n\n const update = () => {\n setBufferedMessages(messages);\n lastUpdateTime.current = now;\n };\n\n if (now - lastUpdateTime.current > interval) {\n update();\n } else {\n if (animationFrame.current) cancelAnimationFrame(animationFrame.current);\n animationFrame.current = requestAnimationFrame(update);\n }\n\n return () => {\n if (animationFrame.current) cancelAnimationFrame(animationFrame.current);\n };\n }, [messages, interval]);\n\n return bufferedMessages;\n};\n"],"names":["React"],"mappings":";;AAiBO,MAAM,mBAAsB,GAAA,CAAI,QAAe,EAAA,QAAA,GAAW,EAAY,KAAA;AAC3E,EAAA,MAAM,CAAC,gBAAkB,EAAA,mBAAmB,CAAI,GAAAA,cAAA,CAAM,SAAS,QAAQ,CAAA;AACvE,EAAM,MAAA,cAAA,GAAiBA,cAAM,CAAA,MAAA,CAAO,CAAC,CAAA;AACrC,EAAM,MAAA,cAAA,GAAiBA,cAAM,CAAA,MAAA,CAAsB,IAAI,CAAA;AAEvD,EAAAA,cAAA,CAAM,UAAU,MAAM;AACpB,IAAM,MAAA,GAAA,GAAM,KAAK,GAAI,EAAA;AAErB,IAAA,MAAM,SAAS,MAAM;AACnB,MAAA,mBAAA,CAAoB,QAAQ,CAAA;AAC5B,MAAA,cAAA,CAAe,OAAU,GAAA,GAAA;AAAA,KAC3B;AAEA,IAAI,IAAA,GAAA,GAAM,cAAe,CAAA,OAAA,GAAU,QAAU,EAAA;AAC3C,MAAO,MAAA,EAAA;AAAA,KACF,MAAA;AACL,MAAA,IAAI,cAAe,CAAA,OAAA,EAA8B,oBAAA,CAAA,cAAA,CAAe,OAAO,CAAA;AACvE,MAAe,cAAA,CAAA,OAAA,GAAU,sBAAsB,MAAM,CAAA;AAAA;AAGvD,IAAA,OAAO,MAAM;AACX,MAAA,IAAI,cAAe,CAAA,OAAA,EAA8B,oBAAA,CAAA,cAAA,CAAe,OAAO,CAAA;AAAA,KACzE;AAAA,GACC,EAAA,CAAC,QAAU,EAAA,QAAQ,CAAC,CAAA;AAEvB,EAAO,OAAA,gBAAA;AACT;;;;"}
|
|
@@ -43,7 +43,7 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
43
43
|
}, [currentConversation, conversationId]);
|
|
44
44
|
const { data: conversationsData = [], ...queryProps } = useFetchConversationMessages(currentConversation);
|
|
45
45
|
React__default.useEffect(() => {
|
|
46
|
-
if (!Array.isArray(conversationsData) || conversationsData.length === 0)
|
|
46
|
+
if (!Array.isArray(conversationsData) || conversationsData.length === 0 && conversationId !== TEMP_CONVERSATION_ID)
|
|
47
47
|
return;
|
|
48
48
|
if (conversations) {
|
|
49
49
|
const _conversations = {
|
|
@@ -92,7 +92,7 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
92
92
|
streamingConversations
|
|
93
93
|
]);
|
|
94
94
|
const handleInputPrompt = React__default.useCallback(
|
|
95
|
-
async (prompt) => {
|
|
95
|
+
async (prompt, attachments = []) => {
|
|
96
96
|
let newConversationId = "";
|
|
97
97
|
const conversationTuple = [
|
|
98
98
|
createUserMessage({
|
|
@@ -123,7 +123,7 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
123
123
|
};
|
|
124
124
|
});
|
|
125
125
|
setTimeout(() => {
|
|
126
|
-
scrollToBottomRef.current?.
|
|
126
|
+
scrollToBottomRef.current?.scrollToBottom();
|
|
127
127
|
}, 0);
|
|
128
128
|
const finalMessages = [];
|
|
129
129
|
let buffer = "";
|
|
@@ -131,7 +131,8 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
131
131
|
const reader = await createMessage({
|
|
132
132
|
prompt,
|
|
133
133
|
selectedModel,
|
|
134
|
-
currentConversation
|
|
134
|
+
currentConversation,
|
|
135
|
+
attachments
|
|
135
136
|
});
|
|
136
137
|
const decoder = new TextDecoder("utf-8");
|
|
137
138
|
const keepGoing = true;
|
|
@@ -182,6 +183,35 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
182
183
|
};
|
|
183
184
|
});
|
|
184
185
|
}
|
|
186
|
+
if (event === "end") {
|
|
187
|
+
const documents = data?.referenced_documents || [];
|
|
188
|
+
setConversations((prevConversations) => {
|
|
189
|
+
const conversation = prevConversations[currentConversation] ?? [];
|
|
190
|
+
const lastMessageIndex = conversation.length - 1;
|
|
191
|
+
const lastMessage = conversation.length === 0 ? createBotMessage({
|
|
192
|
+
content: "",
|
|
193
|
+
timestamp: getTimestamp(Date.now())
|
|
194
|
+
}) : { ...conversation[lastMessageIndex] };
|
|
195
|
+
if (documents.length) {
|
|
196
|
+
lastMessage.sources = {
|
|
197
|
+
sources: documents.map(
|
|
198
|
+
(doc) => ({
|
|
199
|
+
title: doc.doc_title,
|
|
200
|
+
link: doc.doc_url
|
|
201
|
+
})
|
|
202
|
+
)
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
const updatedConversation = [
|
|
206
|
+
...conversation.slice(0, lastMessageIndex),
|
|
207
|
+
lastMessage
|
|
208
|
+
];
|
|
209
|
+
return {
|
|
210
|
+
...prevConversations,
|
|
211
|
+
[currentConversation]: updatedConversation
|
|
212
|
+
};
|
|
213
|
+
});
|
|
214
|
+
}
|
|
185
215
|
} catch (error) {
|
|
186
216
|
console.warn("Error parsing JSON:", error);
|
|
187
217
|
if (typeof onComplete === "function") {
|