index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useContext } from 'use-context-selector'
  6. import TemplateVarPanel, { PanelTitle, VarOpBtnGroup } from '../value-panel'
  7. import s from './style.module.css'
  8. import { AppInfo, ChatBtn, EditBtn, FootLogo, PromptTemplate } from './massive-component'
  9. import type { SiteInfo } from '@/models/share'
  10. import type { PromptConfig } from '@/models/debug'
  11. import { ToastContext } from '@/app/components/base/toast'
  12. import Select from '@/app/components/base/select'
  13. import { DEFAULT_VALUE_MAX_LEN } from '@/config'
  14. // regex to match the {{}} and replace it with a span
  15. const regex = /\{\{([^}]+)\}\}/g
  16. export type IWelcomeProps = {
  17. // conversationName: string
  18. hasSetInputs: boolean
  19. isPublicVersion: boolean
  20. siteInfo: SiteInfo
  21. promptConfig: PromptConfig
  22. onStartChat: (inputs: Record<string, any>) => void
  23. canEditInputs: boolean
  24. savedInputs: Record<string, any>
  25. onInputsChange: (inputs: Record<string, any>) => void
  26. plan: string
  27. canReplaceLogo?: boolean
  28. }
  29. const Welcome: FC<IWelcomeProps> = ({
  30. // conversationName,
  31. hasSetInputs,
  32. isPublicVersion,
  33. siteInfo,
  34. plan,
  35. promptConfig,
  36. onStartChat,
  37. canEditInputs,
  38. savedInputs,
  39. onInputsChange,
  40. canReplaceLogo,
  41. }) => {
  42. const { t } = useTranslation()
  43. const hasVar = promptConfig.prompt_variables.length > 0
  44. const [isFold, setIsFold] = useState<boolean>(true)
  45. const [inputs, setInputs] = useState<Record<string, any>>((() => {
  46. if (hasSetInputs)
  47. return savedInputs
  48. const res: Record<string, any> = {}
  49. if (promptConfig) {
  50. promptConfig.prompt_variables.forEach((item) => {
  51. res[item.key] = ''
  52. })
  53. }
  54. // debugger
  55. return res
  56. })())
  57. useEffect(() => {
  58. if (!savedInputs) {
  59. const res: Record<string, any> = {}
  60. if (promptConfig) {
  61. promptConfig.prompt_variables.forEach((item) => {
  62. res[item.key] = ''
  63. })
  64. }
  65. setInputs(res)
  66. }
  67. else {
  68. setInputs(savedInputs)
  69. }
  70. }, [savedInputs])
  71. const highLightPromoptTemplate = (() => {
  72. if (!promptConfig)
  73. return ''
  74. const res = promptConfig.prompt_template.replace(regex, (match, p1) => {
  75. return `<span class='text-gray-800 font-bold'>${inputs?.[p1] ? inputs?.[p1] : match}</span>`
  76. })
  77. return res
  78. })()
  79. const { notify } = useContext(ToastContext)
  80. const logError = (message: string) => {
  81. notify({ type: 'error', message, duration: 3000 })
  82. }
  83. // const renderHeader = () => {
  84. // return (
  85. // <div className='absolute top-0 left-0 right-0 flex items-center justify-between border-b border-gray-100 mobile:h-12 tablet:h-16 px-8 bg-white'>
  86. // <div className='text-gray-900'>{conversationName}</div>
  87. // </div>
  88. // )
  89. // }
  90. const renderInputs = () => {
  91. return (
  92. <div className='space-y-3'>
  93. {promptConfig.prompt_variables.map(item => (
  94. <div className='tablet:flex items-start mobile:space-y-2 tablet:space-y-0 mobile:text-xs tablet:text-sm' key={item.key}>
  95. <label className={`flex-shrink-0 flex items-center tablet:leading-9 mobile:text-gray-700 tablet:text-gray-900 mobile:font-medium pc:font-normal ${s.formLabel}`}>{item.name}</label>
  96. {item.type === 'select'
  97. && (
  98. <Select
  99. className='w-full'
  100. defaultValue={inputs?.[item.key]}
  101. onSelect={(i) => { setInputs({ ...inputs, [item.key]: i.value }) }}
  102. items={(item.options || []).map(i => ({ name: i, value: i }))}
  103. allowSearch={false}
  104. bgClassName='bg-gray-50'
  105. />
  106. )
  107. }
  108. {item.type === 'string' && (
  109. <input
  110. placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
  111. value={inputs?.[item.key] || ''}
  112. onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}
  113. className={'w-full flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50'}
  114. maxLength={item.max_length || DEFAULT_VALUE_MAX_LEN}
  115. />
  116. )}
  117. {item.type === 'paragraph' && (
  118. <textarea
  119. className="w-full h-[104px] flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50"
  120. placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
  121. value={inputs?.[item.key] || ''}
  122. onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}
  123. />
  124. )}
  125. </div>
  126. ))}
  127. </div>
  128. )
  129. }
  130. const canChat = () => {
  131. const prompt_variables = promptConfig?.prompt_variables
  132. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  133. return true
  134. let hasEmptyInput = ''
  135. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  136. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  137. return res
  138. }) || [] // compatible with old version
  139. requiredVars.forEach(({ key, name }) => {
  140. if (hasEmptyInput)
  141. return
  142. if (!inputs?.[key])
  143. hasEmptyInput = name
  144. })
  145. if (hasEmptyInput) {
  146. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  147. return false
  148. }
  149. return !hasEmptyInput
  150. }
  151. const handleChat = () => {
  152. if (!canChat())
  153. return
  154. onStartChat(inputs)
  155. }
  156. const renderNoVarPanel = () => {
  157. if (isPublicVersion) {
  158. return (
  159. <div>
  160. <AppInfo siteInfo={siteInfo} />
  161. <TemplateVarPanel
  162. isFold={false}
  163. header={
  164. <>
  165. <PanelTitle
  166. title={t('share.chat.publicPromptConfigTitle')}
  167. className='mb-1'
  168. />
  169. <PromptTemplate html={highLightPromoptTemplate} />
  170. </>
  171. }
  172. >
  173. <ChatBtn onClick={handleChat} />
  174. </TemplateVarPanel>
  175. </div>
  176. )
  177. }
  178. // private version
  179. return (
  180. <TemplateVarPanel
  181. isFold={false}
  182. header={
  183. <AppInfo siteInfo={siteInfo} />
  184. }
  185. >
  186. <ChatBtn onClick={handleChat} />
  187. </TemplateVarPanel>
  188. )
  189. }
  190. const renderVarPanel = () => {
  191. return (
  192. <TemplateVarPanel
  193. isFold={false}
  194. header={
  195. <AppInfo siteInfo={siteInfo} />
  196. }
  197. >
  198. {renderInputs()}
  199. <ChatBtn
  200. className='mt-3 mobile:ml-0 tablet:ml-[128px]'
  201. onClick={handleChat}
  202. />
  203. </TemplateVarPanel>
  204. )
  205. }
  206. const renderVarOpBtnGroup = () => {
  207. return (
  208. <VarOpBtnGroup
  209. onConfirm={() => {
  210. if (!canChat())
  211. return
  212. onInputsChange(inputs)
  213. setIsFold(true)
  214. }}
  215. onCancel={() => {
  216. setInputs(savedInputs)
  217. setIsFold(true)
  218. }}
  219. />
  220. )
  221. }
  222. const renderHasSetInputsPublic = () => {
  223. if (!canEditInputs) {
  224. return (
  225. <TemplateVarPanel
  226. isFold={false}
  227. header={
  228. <>
  229. <PanelTitle
  230. title={t('share.chat.publicPromptConfigTitle')}
  231. className='mb-1'
  232. />
  233. <PromptTemplate html={highLightPromoptTemplate} />
  234. </>
  235. }
  236. />
  237. )
  238. }
  239. return (
  240. <TemplateVarPanel
  241. isFold={isFold}
  242. header={
  243. <>
  244. <PanelTitle
  245. title={t('share.chat.publicPromptConfigTitle')}
  246. className='mb-1'
  247. />
  248. <PromptTemplate html={highLightPromoptTemplate} />
  249. {isFold && (
  250. <div className='flex items-center justify-between mt-3 border-t border-indigo-100 pt-4 text-xs text-indigo-600'>
  251. <span className='text-gray-700'>{t('share.chat.configStatusDes')}</span>
  252. <EditBtn onClick={() => setIsFold(false)} />
  253. </div>
  254. )}
  255. </>
  256. }
  257. >
  258. {renderInputs()}
  259. {renderVarOpBtnGroup()}
  260. </TemplateVarPanel>
  261. )
  262. }
  263. const renderHasSetInputsPrivate = () => {
  264. if (!canEditInputs || !hasVar)
  265. return null
  266. return (
  267. <TemplateVarPanel
  268. isFold={isFold}
  269. header={
  270. <div className='flex items-center justify-between text-indigo-600'>
  271. <PanelTitle
  272. title={!isFold ? t('share.chat.privatePromptConfigTitle') : t('share.chat.configStatusDes')}
  273. />
  274. {isFold && (
  275. <EditBtn onClick={() => setIsFold(false)} />
  276. )}
  277. </div>
  278. }
  279. >
  280. {renderInputs()}
  281. {renderVarOpBtnGroup()}
  282. </TemplateVarPanel>
  283. )
  284. }
  285. const renderHasSetInputs = () => {
  286. if ((!isPublicVersion && !canEditInputs) || !hasVar)
  287. return null
  288. return (
  289. <div
  290. className='pt-[88px] mb-5'
  291. >
  292. {isPublicVersion ? renderHasSetInputsPublic() : renderHasSetInputsPrivate()}
  293. </div>)
  294. }
  295. return (
  296. <div className='relative tablet:min-h-[64px]'>
  297. {/* {hasSetInputs && renderHeader()} */}
  298. <div className='mx-auto pc:w-[794px] max-w-full mobile:w-full px-3.5'>
  299. {/* Has't set inputs */}
  300. {
  301. !hasSetInputs && (
  302. <div className='mobile:pt-[72px] tablet:pt-[128px] pc:pt-[200px]'>
  303. {hasVar
  304. ? (
  305. renderVarPanel()
  306. )
  307. : (
  308. renderNoVarPanel()
  309. )}
  310. </div>
  311. )
  312. }
  313. {/* Has set inputs */}
  314. {hasSetInputs && renderHasSetInputs()}
  315. {/* foot */}
  316. {!hasSetInputs && (
  317. <div className='mt-4 flex justify-between items-center h-8 text-xs text-gray-400'>
  318. {siteInfo.privacy_policy
  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. : <div>
  327. </div>}
  328. {!canReplaceLogo && <a className='flex items-center pr-3 space-x-3' href="https://dify.ai/" target="_blank">
  329. <span className='uppercase'>{t('share.chat.powerBy')}</span>
  330. <FootLogo />
  331. </a>}
  332. </div>
  333. )}
  334. </div>
  335. </div >
  336. )
  337. }
  338. export default React.memo(Welcome)