index.tsx 13 KB

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