index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. 'use client'
  2. import React, { FC, useEffect, useState, useRef } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  5. import cn from 'classnames'
  6. import { useBoolean, useClickAway } from 'ahooks'
  7. import { useContext } from 'use-context-selector'
  8. import ConfigScence from '@/app/components/share/text-generation/config-scence'
  9. import NoData from '@/app/components/share/text-generation/no-data'
  10. // import History from '@/app/components/share/text-generation/history'
  11. import { fetchAppInfo, fetchAppParams, sendCompletionMessage, updateFeedback, saveMessage, fetchSavedMessage as doFetchSavedMessage, removeMessage } from '@/service/share'
  12. import type { SiteInfo } from '@/models/share'
  13. import type { PromptConfig, MoreLikeThisConfig, SavedMessage } from '@/models/debug'
  14. import Toast from '@/app/components/base/toast'
  15. import { Feedbacktype } from '@/app/components/app/chat'
  16. import { changeLanguage } from '@/i18n/i18next-config'
  17. import Loading from '@/app/components/base/loading'
  18. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  19. import TextGenerationRes from '@/app/components/app/text-generate/item'
  20. import SavedItems from '@/app/components/app/text-generate/saved-items'
  21. import TabHeader from '../../base/tab-header'
  22. import { XMarkIcon } from '@heroicons/react/24/outline'
  23. import s from './style.module.css'
  24. import Button from '../../base/button'
  25. import { App } from '@/types/app'
  26. import { InstalledApp } from '@/models/explore'
  27. export type IMainProps = {
  28. isInstalledApp?: boolean,
  29. installedAppInfo? : InstalledApp
  30. }
  31. const TextGeneration: FC<IMainProps> = ({
  32. isInstalledApp = false,
  33. installedAppInfo
  34. }) => {
  35. const { t } = useTranslation()
  36. const media = useBreakpoints()
  37. const isPC = media === MediaType.pc
  38. const isTablet = media === MediaType.tablet
  39. const isMoble = media === MediaType.mobile
  40. const [currTab, setCurrTab] = useState<string>('create')
  41. const [inputs, setInputs] = useState<Record<string, any>>({})
  42. const [appId, setAppId] = useState<string>('')
  43. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>(null)
  44. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  45. const [moreLikeThisConifg, setMoreLikeThisConifg] = useState<MoreLikeThisConfig | null>(null)
  46. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  47. const [query, setQuery] = useState('')
  48. const [completionRes, setCompletionRes] = useState('')
  49. const { notify } = Toast
  50. const isNoData = !completionRes
  51. const [messageId, setMessageId] = useState<string | null>(null)
  52. const [feedback, setFeedback] = useState<Feedbacktype>({
  53. rating: null
  54. })
  55. const handleFeedback = async (feedback: Feedbacktype) => {
  56. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  57. setFeedback(feedback)
  58. }
  59. const [savedMessages, setSavedMessages] = useState<SavedMessage[]>([])
  60. const fetchSavedMessage = async () => {
  61. const res: any = await doFetchSavedMessage(isInstalledApp, installedAppInfo?.id)
  62. setSavedMessages(res.data)
  63. }
  64. useEffect(() => {
  65. fetchSavedMessage()
  66. }, [])
  67. const handleSaveMessage = async (messageId: string) => {
  68. await saveMessage(messageId, isInstalledApp, installedAppInfo?.id)
  69. notify({ type: 'success', message: t('common.api.saved') })
  70. fetchSavedMessage()
  71. }
  72. const handleRemoveSavedMessage = async (messageId: string) => {
  73. await removeMessage(messageId, isInstalledApp, installedAppInfo?.id)
  74. notify({ type: 'success', message: t('common.api.remove') })
  75. fetchSavedMessage()
  76. }
  77. const logError = (message: string) => {
  78. notify({ type: 'error', message })
  79. }
  80. const checkCanSend = () => {
  81. const prompt_variables = promptConfig?.prompt_variables
  82. if (!prompt_variables || prompt_variables?.length === 0) {
  83. return true
  84. }
  85. let hasEmptyInput = false
  86. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  87. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  88. return res
  89. }) || [] // compatible with old version
  90. requiredVars.forEach(({ key }) => {
  91. if (hasEmptyInput) {
  92. return
  93. }
  94. if (!inputs[key]) {
  95. hasEmptyInput = true
  96. }
  97. })
  98. if (hasEmptyInput) {
  99. logError(t('appDebug.errorMessage.valueOfVarRequired'))
  100. return false
  101. }
  102. return !hasEmptyInput
  103. }
  104. const handleSend = async () => {
  105. if (isResponsing) {
  106. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  107. return false
  108. }
  109. if (!checkCanSend())
  110. return
  111. if (!query) {
  112. logError(t('appDebug.errorMessage.queryRequired'))
  113. return false
  114. }
  115. const data = {
  116. inputs,
  117. query,
  118. }
  119. setMessageId(null)
  120. setFeedback({
  121. rating: null
  122. })
  123. setCompletionRes('')
  124. const res: string[] = []
  125. let tempMessageId = ''
  126. if (!isPC) {
  127. showResSidebar()
  128. }
  129. setResponsingTrue()
  130. sendCompletionMessage(data, {
  131. onData: (data: string, _isFirstMessage: boolean, { messageId }: any) => {
  132. tempMessageId = messageId
  133. res.push(data)
  134. setCompletionRes(res.join(''))
  135. },
  136. onCompleted: () => {
  137. setResponsingFalse()
  138. setMessageId(tempMessageId)
  139. },
  140. onError() {
  141. setResponsingFalse()
  142. }
  143. }, isInstalledApp, installedAppInfo?.id)
  144. }
  145. const fetchInitData = () => {
  146. return Promise.all([isInstalledApp ? {
  147. app_id: installedAppInfo?.id,
  148. site: {
  149. title: installedAppInfo?.app.name,
  150. prompt_public: false,
  151. copyright: ''
  152. },
  153. plan: 'basic',
  154. }: fetchAppInfo(), fetchAppParams(isInstalledApp, installedAppInfo?.id)])
  155. }
  156. useEffect(() => {
  157. (async () => {
  158. const [appData, appParams]: any = await fetchInitData()
  159. const { app_id: appId, site: siteInfo } = appData
  160. setAppId(appId)
  161. setSiteInfo(siteInfo as SiteInfo)
  162. changeLanguage(siteInfo.default_language)
  163. const { user_input_form, more_like_this }: any = appParams
  164. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  165. setPromptConfig({
  166. prompt_template: '', // placeholder for feture
  167. prompt_variables,
  168. } as PromptConfig)
  169. setMoreLikeThisConifg(more_like_this)
  170. })()
  171. }, [])
  172. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  173. useEffect(() => {
  174. if (siteInfo?.title)
  175. document.title = `${siteInfo.title} - Powered by Dify`
  176. }, [siteInfo?.title])
  177. const [isShowResSidebar, { setTrue: showResSidebar, setFalse: hideResSidebar }] = useBoolean(false)
  178. const resRef = useRef<HTMLDivElement>(null)
  179. useClickAway(() => {
  180. hideResSidebar();
  181. }, resRef)
  182. const renderRes = (
  183. <div
  184. ref={resRef}
  185. className={
  186. cn(
  187. "flex flex-col h-full shrink-0",
  188. isPC ? 'px-10 py-8' : 'bg-gray-50',
  189. isTablet && 'p-6', isMoble && 'p-4')
  190. }
  191. >
  192. <>
  193. <div className='shrink-0 flex items-center justify-between'>
  194. <div className='flex items-center space-x-3'>
  195. <div className={s.starIcon}></div>
  196. <div className='text-lg text-gray-800 font-semibold'>{t('share.generation.title')}</div>
  197. </div>
  198. {!isPC && (
  199. <div
  200. className='flex items-center justify-center cursor-pointer'
  201. onClick={hideResSidebar}
  202. >
  203. <XMarkIcon className='w-4 h-4 text-gray-800' />
  204. </div>
  205. )}
  206. </div>
  207. <div className='grow'>
  208. {(isResponsing && !completionRes) ? (
  209. <div className='flex h-full w-full justify-center items-center'>
  210. <Loading type='area' />
  211. </div>) : (
  212. <>
  213. {isNoData
  214. ? <NoData />
  215. : (
  216. <TextGenerationRes
  217. className='mt-3'
  218. content={completionRes}
  219. messageId={messageId}
  220. isInWebApp
  221. moreLikeThis={moreLikeThisConifg?.enabled}
  222. onFeedback={handleFeedback}
  223. feedback={feedback}
  224. onSave={handleSaveMessage}
  225. isMobile={isMoble}
  226. isInstalledApp={isInstalledApp}
  227. installedAppId={installedAppInfo?.id}
  228. />
  229. )
  230. }
  231. </>
  232. )}
  233. </div>
  234. </>
  235. </div>
  236. )
  237. if (!appId || !siteInfo || !promptConfig)
  238. return <Loading type='app' />
  239. return (
  240. <>
  241. <div className={cn(
  242. isPC && 'flex',
  243. isInstalledApp ? s.installedApp : 'h-screen',
  244. 'bg-gray-50'
  245. )}>
  246. {/* Left */}
  247. <div className={cn(
  248. isPC ? 'w-[600px] max-w-[50%] p-8' : 'p-4',
  249. isInstalledApp && 'rounded-l-2xl',
  250. "shrink-0 relative flex flex-col pb-10 h-full border-r border-gray-100 bg-white"
  251. )}>
  252. <div className='mb-6'>
  253. <div className='flex justify-between items-center'>
  254. <div className='flex items-center space-x-3'>
  255. <div className={cn(s.appIcon, 'shrink-0')}></div>
  256. <div className='text-lg text-gray-800 font-semibold'>{siteInfo.title}</div>
  257. </div>
  258. {!isPC && (
  259. <Button
  260. className='shrink-0 !h-8 !px-3 ml-2'
  261. onClick={showResSidebar}
  262. >
  263. <div className='flex items-center space-x-2 text-primary-600 text-[13px] font-medium'>
  264. <div className={s.starIcon}></div>
  265. <span>{t('share.generation.title')}</span>
  266. </div>
  267. </Button>
  268. )}
  269. </div>
  270. {siteInfo.description && (
  271. <div className='mt-2 text-xs text-gray-500'>{siteInfo.description}</div>
  272. )}
  273. </div>
  274. <TabHeader
  275. items={[
  276. { id: 'create', name: t('share.generation.tabs.create') },
  277. {
  278. id: 'saved', name: t('share.generation.tabs.saved'), extra: savedMessages.length > 0 ? (
  279. <div className='ml-1 flext items-center h-5 px-1.5 rounded-md border border-gray-200 text-gray-500 text-xs font-medium'>
  280. {savedMessages.length}
  281. </div>
  282. ) : null
  283. }
  284. ]}
  285. value={currTab}
  286. onChange={setCurrTab}
  287. />
  288. <div className='grow h-20 overflow-y-auto'>
  289. {currTab === 'create' && (
  290. <ConfigScence
  291. siteInfo={siteInfo}
  292. inputs={inputs}
  293. onInputsChange={setInputs}
  294. promptConfig={promptConfig}
  295. query={query}
  296. onQueryChange={setQuery}
  297. onSend={handleSend}
  298. />
  299. )}
  300. {currTab === 'saved' && (
  301. <SavedItems
  302. className='mt-4'
  303. list={savedMessages}
  304. onRemove={handleRemoveSavedMessage}
  305. onStartCreateContent={() => setCurrTab('create')}
  306. />
  307. )}
  308. </div>
  309. {/* copyright */}
  310. <div className={cn(
  311. isInstalledApp ? 'left-[248px]' : 'left-8',
  312. 'fixed bottom-4 flex space-x-2 text-gray-400 font-normal text-xs'
  313. )}>
  314. <div className="">© {siteInfo.copyright || siteInfo.title} {(new Date()).getFullYear()}</div>
  315. {siteInfo.privacy_policy && (
  316. <>
  317. <div>·</div>
  318. <div>{t('share.chat.privacyPolicyLeft')}
  319. <a
  320. className='text-gray-500'
  321. href={siteInfo.privacy_policy}
  322. target='_blank'>{t('share.chat.privacyPolicyMiddle')}</a>
  323. {t('share.chat.privacyPolicyRight')}
  324. </div>
  325. </>
  326. )}
  327. </div>
  328. </div>
  329. {/* Result */}
  330. {isPC && (
  331. <div className='grow h-full'>
  332. {renderRes}
  333. </div>
  334. )}
  335. {(!isPC && isShowResSidebar) && (
  336. <div
  337. className={cn('fixed z-50 inset-0', isTablet ? 'pl-[128px]' : 'pl-6')}
  338. style={{
  339. background: 'rgba(35, 56, 118, 0.2)'
  340. }}
  341. >
  342. {renderRes}
  343. </div>
  344. )}
  345. </div>
  346. </>
  347. )
  348. }
  349. export default TextGeneration