index.tsx 13 KB

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