Feat/explore (#198)

This commit is contained in:
Joel
2023-05-25 16:59:47 +08:00
committed by GitHub
parent b6cca59517
commit 33b3eaf324
38 changed files with 1312 additions and 97 deletions

View File

@@ -23,16 +23,19 @@ import { replaceStringWithValues } from '@/app/components/app/configuration/prom
import AppUnavailable from '../../base/app-unavailable'
import { userInputsFormToPromptVariables } from '@/utils/model-config'
import { SuggestedQuestionsAfterAnswerConfig } from '@/models/debug'
import { InstalledApp } from '@/models/explore'
import s from './style.module.css'
export type IMainProps = {
params: {
locale: string
appId: string
conversationId: string
token: string
}
isInstalledApp?: boolean,
installedAppInfo? : InstalledApp
}
const Main: FC<IMainProps> = () => {
const Main: FC<IMainProps> = ({
isInstalledApp = false,
installedAppInfo
}) => {
const { t } = useTranslation()
const media = useBreakpoints()
const isMobile = media === MediaType.mobile
@@ -80,6 +83,11 @@ const Main: FC<IMainProps> = () => {
setNewConversationInfo,
setExistConversationInfo
} = useConversation()
const [hasMore, setHasMore] = useState<boolean>(false)
const onMoreLoaded = ({ data: conversations, has_more }: any) => {
setHasMore(has_more)
setConversationList([...conversationList, ...conversations])
}
const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
const [conversationIdChangeBecauseOfNew, setConversationIdChangeBecauseOfNew, getConversationIdChangeBecauseOfNew] = useGetState(false)
@@ -129,7 +137,7 @@ const Main: FC<IMainProps> = () => {
// update chat list of current conversation
if (!isNewConversation && !conversationIdChangeBecauseOfNew && !isResponsing) {
fetchChatList(currConversationId).then((res: any) => {
fetchChatList(currConversationId, isInstalledApp, installedAppInfo?.id).then((res: any) => {
const { data } = res
const newChatList: IChatItem[] = generateNewChatListWithOpenstatement(notSyncToStateIntroduction, notSyncToStateInputs)
@@ -222,28 +230,41 @@ const Main: FC<IMainProps> = () => {
return []
}
const fetchInitData = () => {
return Promise.all([isInstalledApp ? {
app_id: installedAppInfo?.id,
site: {
title: installedAppInfo?.app.name,
prompt_public: false,
copyright: ''
},
plan: 'basic',
}: fetchAppInfo(), fetchConversations(isInstalledApp, installedAppInfo?.id), fetchAppParams(isInstalledApp, installedAppInfo?.id)])
}
// init
useEffect(() => {
(async () => {
try {
const [appData, conversationData, appParams] = await Promise.all([fetchAppInfo(), fetchConversations(), fetchAppParams()])
const { app_id: appId, site: siteInfo, model_config, plan }: any = appData
const [appData, conversationData, appParams]: any = await fetchInitData()
const { app_id: appId, site: siteInfo, plan }: any = appData
setAppId(appId)
setPlan(plan)
const tempIsPublicVersion = siteInfo.prompt_public
setIsPublicVersion(tempIsPublicVersion)
const prompt_template = tempIsPublicVersion ? model_config.pre_prompt : ''
const prompt_template = ''
// handle current conversation id
const { data: conversations } = conversationData as { data: ConversationItem[] }
const { data: conversations, has_more } = conversationData as { data: ConversationItem[], has_more: boolean }
const _conversationId = getConversationIdFromStorage(appId)
const isNotNewConversation = conversations.some(item => item.id === _conversationId)
setHasMore(has_more)
// fetch new conversation info
const { user_input_form, opening_statement: introduction, suggested_questions_after_answer }: any = appParams
const prompt_variables = userInputsFormToPromptVariables(user_input_form)
changeLanguage(siteInfo.default_language)
if(siteInfo.default_language) {
changeLanguage(siteInfo.default_language)
}
setNewConversationInfo({
name: t('share.chat.newChatDefaultName'),
introduction,
@@ -379,7 +400,8 @@ const Main: FC<IMainProps> = () => {
}
let currChatList = conversationList
if (getConversationIdChangeBecauseOfNew()) {
const { data: conversations }: any = await fetchConversations()
const { data: conversations, has_more }: any = await fetchConversations(isInstalledApp, installedAppInfo?.id)
setHasMore(has_more)
setConversationList(conversations as ConversationItem[])
currChatList = conversations
}
@@ -388,7 +410,7 @@ const Main: FC<IMainProps> = () => {
setChatNotStarted()
setCurrConversationId(tempNewConversationId, appId, true)
if (suggestedQuestionsAfterAnswerConfig?.enabled) {
const { data }: any = await fetchSuggestedQuestions(responseItem.id)
const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
setSuggestQuestions(data)
setIsShowSuggestion(true)
}
@@ -400,11 +422,11 @@ const Main: FC<IMainProps> = () => {
draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
}))
},
})
}, isInstalledApp, installedAppInfo?.id)
}
const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } })
await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
const newChatList = chatList.map((item) => {
if (item.id === messageId) {
return {
@@ -424,9 +446,14 @@ const Main: FC<IMainProps> = () => {
return (
<Sidebar
list={conversationList}
onMoreLoaded={onMoreLoaded}
isNoMore={!hasMore}
onCurrentIdChange={handleConversationIdChange}
currentId={currConversationId}
copyRight={siteInfo.copyright || siteInfo.title}
isInstalledApp={isInstalledApp}
installedAppId={installedAppInfo?.id}
siteInfo={siteInfo}
/>
)
}
@@ -439,18 +466,29 @@ const Main: FC<IMainProps> = () => {
return (
<div className='bg-gray-100'>
<Header
title={siteInfo.title}
icon={siteInfo.icon || ''}
icon_background={siteInfo.icon_background || '#FFEAD5'}
isMobile={isMobile}
onShowSideBar={showSidebar}
onCreateNewChat={() => handleConversationIdChange('-1')}
/>
{!isInstalledApp && (
<Header
title={siteInfo.title}
icon={siteInfo.icon || ''}
icon_background={siteInfo.icon_background}
isMobile={isMobile}
onShowSideBar={showSidebar}
onCreateNewChat={() => handleConversationIdChange('-1')}
/>
)}
{/* {isNewConversation ? 'new' : 'exist'}
{JSON.stringify(newConversationInputs ? newConversationInputs : {})}
{JSON.stringify(existConversationInputs ? existConversationInputs : {})} */}
<div className="flex rounded-t-2xl bg-white overflow-hidden">
<div
className={cn(
"flex rounded-t-2xl bg-white overflow-hidden",
isInstalledApp && 'rounded-b-2xl',
)}
style={isInstalledApp ? {
boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)'
} : {}}
>
{/* sidebar */}
{!isMobile && renderSidebar()}
{isMobile && isShowSidebar && (
@@ -464,7 +502,11 @@ const Main: FC<IMainProps> = () => {
</div>
)}
{/* main */}
<div className='flex-grow flex flex-col h-[calc(100vh_-_3rem)] overflow-y-auto'>
<div className={cn(
isInstalledApp ? s.installedApp : 'h-[calc(100vh_-_3rem)]',
'flex-grow flex flex-col overflow-y-auto'
)
}>
<ConfigSence
conversationName={conversationName}
hasSetInputs={hasSetInputs}

View File

@@ -0,0 +1,27 @@
'use client'
import React, { FC } from 'react'
import cn from 'classnames'
import { appDefaultIconBackground } from '@/config/index'
import AppIcon from '@/app/components/base/app-icon'
export interface IAppInfoProps {
className?: string
icon: string
icon_background?: string
name: string
}
const AppInfo: FC<IAppInfoProps> = ({
className,
icon,
icon_background,
name
}) => {
return (
<div className={cn(className, 'flex items-center space-x-3')}>
<AppIcon size="small" icon={icon} background={icon_background || appDefaultIconBackground} />
<div className='w-0 grow text-sm font-semibold text-gray-800 overflow-hidden text-ellipsis whitespace-nowrap'>{name}</div>
</div>
)
}
export default React.memo(AppInfo)

View File

@@ -1,4 +1,4 @@
import React from 'react'
import React, { useEffect, useRef } from 'react'
import type { FC } from 'react'
import { useTranslation } from 'react-i18next'
import {
@@ -7,43 +7,89 @@ import {
} from '@heroicons/react/24/outline'
import { ChatBubbleOvalLeftEllipsisIcon as ChatBubbleOvalLeftEllipsisSolidIcon, } from '@heroicons/react/24/solid'
import Button from '../../../base/button'
import AppInfo from '@/app/components/share/chat/sidebar/app-info'
// import Card from './card'
import type { ConversationItem } from '@/models/share'
import type { ConversationItem, SiteInfo } from '@/models/share'
import { useInfiniteScroll } from 'ahooks'
import { fetchConversations } from '@/service/share'
function classNames(...classes: any[]) {
return classes.filter(Boolean).join(' ')
}
const MAX_CONVERSATION_LENTH = 20
export type ISidebarProps = {
copyRight: string
currentId: string
onCurrentIdChange: (id: string) => void
list: ConversationItem[]
isInstalledApp: boolean
installedAppId?: string
siteInfo: SiteInfo
onMoreLoaded: (res: {data: ConversationItem[], has_more: boolean}) => void
isNoMore: boolean
}
const Sidebar: FC<ISidebarProps> = ({
copyRight,
currentId,
onCurrentIdChange,
list }) => {
list,
isInstalledApp,
installedAppId,
siteInfo,
onMoreLoaded,
isNoMore,
}) => {
const { t } = useTranslation()
const listRef = useRef<HTMLDivElement>(null)
useInfiniteScroll(
async () => {
if(!isNoMore) {
const lastId = list[list.length - 1].id
const { data: conversations, has_more }: any = await fetchConversations(isInstalledApp, installedAppId, lastId)
onMoreLoaded({ data: conversations, has_more })
}
return {list: []}
},
{
target: listRef,
isNoMore: () => {
return isNoMore
},
reloadDeps: [isNoMore]
},
)
return (
<div
className="shrink-0 flex flex-col overflow-y-auto bg-white pc:w-[244px] tablet:w-[192px] mobile:w-[240px] border-r border-gray-200 tablet:h-[calc(100vh_-_3rem)] mobile:h-screen"
className={
classNames(
isInstalledApp ? 'tablet:h-[calc(100vh_-_74px)]' : 'tablet:h-[calc(100vh_-_3rem)]',
"shrink-0 flex flex-col bg-white pc:w-[244px] tablet:w-[192px] mobile:w-[240px] border-r border-gray-200 mobile:h-screen"
)
}
>
{list.length < MAX_CONVERSATION_LENTH && (
<div className="flex flex-shrink-0 p-4 !pb-0">
<Button
onClick={() => { onCurrentIdChange('-1') }}
className="group block w-full flex-shrink-0 !justify-start !h-9 text-primary-600 items-center text-sm">
<PencilSquareIcon className="mr-2 h-4 w-4" /> {t('share.chat.newChat')}
</Button>
</div>
{isInstalledApp && (
<AppInfo
className='my-4 px-4'
name={siteInfo.title || ''}
icon={siteInfo.icon || ''}
icon_background={siteInfo.icon_background}
/>
)}
<div className="flex flex-shrink-0 p-4 !pb-0">
<Button
onClick={() => { onCurrentIdChange('-1') }}
className="group block w-full flex-shrink-0 !justify-start !h-9 text-primary-600 items-center text-sm">
<PencilSquareIcon className="mr-2 h-4 w-4" /> {t('share.chat.newChat')}
</Button>
</div>
<nav className="mt-4 flex-1 space-y-1 bg-white p-4 !pt-0">
<nav
ref={listRef}
className="mt-4 flex-1 space-y-1 bg-white p-4 !pt-0 overflow-y-auto"
>
{list.map((item) => {
const isCurrent = item.id === currentId
const ItemIcon

View File

@@ -0,0 +1,3 @@
.installedApp {
height: calc(100vh - 74px);
}