index.tsx 11 KB

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