File size: 12,116 Bytes
4304c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
'use client'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import TemplateVarPanel, { PanelTitle, VarOpBtnGroup } from '../value-panel'
import s from './style.module.css'
import { AppInfo, ChatBtn, EditBtn, FootLogo, PromptTemplate } from './massive-component'
import type { SiteInfo } from '@/models/share'
import type { PromptConfig } from '@/models/debug'
import { ToastContext } from '@/app/components/base/toast'
import Select from '@/app/components/base/select'
import { DEFAULT_VALUE_MAX_LEN } from '@/config'

// regex to match the {{}} and replace it with a span
const regex = /\{\{([^}]+)\}\}/g

export type IWelcomeProps = {
  // conversationName: string
  hasSetInputs: boolean
  isPublicVersion: boolean
  siteInfo: SiteInfo
  promptConfig: PromptConfig
  onStartChat: (inputs: Record<string, any>) => void
  canEditInputs: boolean
  savedInputs: Record<string, any>
  onInputsChange: (inputs: Record<string, any>) => void
  plan: string
  canReplaceLogo?: boolean
  customConfig?: {
    remove_webapp_brand?: boolean
    replace_webapp_logo?: string
  }
}

const Welcome: FC<IWelcomeProps> = ({

  // conversationName,

  hasSetInputs,

  isPublicVersion,

  siteInfo,

  promptConfig,

  onStartChat,

  canEditInputs,

  savedInputs,

  onInputsChange,

  customConfig,

}) => {
  const { t } = useTranslation()
  const hasVar = promptConfig.prompt_variables.length > 0
  const [isFold, setIsFold] = useState<boolean>(true)
  const [inputs, setInputs] = useState<Record<string, any>>((() => {
    if (hasSetInputs)
      return savedInputs

    const res: Record<string, any> = {}
    if (promptConfig) {
      promptConfig.prompt_variables.forEach((item) => {
        res[item.key] = ''
      })
    }
    // debugger
    return res
  })())
  useEffect(() => {
    if (!savedInputs) {
      const res: Record<string, any> = {}
      if (promptConfig) {
        promptConfig.prompt_variables.forEach((item) => {
          res[item.key] = ''
        })
      }
      setInputs(res)
    }
    else {
      setInputs(savedInputs)
    }
  }, [savedInputs])

  const highLightPromoptTemplate = (() => {
    if (!promptConfig)
      return ''
    const res = promptConfig.prompt_template.replace(regex, (match, p1) => {
      return `<span class='text-gray-800 font-bold'>${inputs?.[p1] ? inputs?.[p1] : match}</span>`
    })
    return res
  })()

  const { notify } = useContext(ToastContext)
  const logError = (message: string) => {
    notify({ type: 'error', message, duration: 3000 })
  }

  // const renderHeader = () => {
  //   return (
  //     <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'>
  //       <div className='text-gray-900'>{conversationName}</div>
  //     </div>
  //   )
  // }

  const renderInputs = () => {
    return (
      <div className='space-y-3'>

        {promptConfig.prompt_variables.map(item => (

          <div className='tablet:flex items-start  mobile:space-y-2 tablet:space-y-0 mobile:text-xs tablet:text-sm' key={item.key}>

            <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>

            {item.type === 'select'

              && (

                <Select

                  className='w-full'

                  defaultValue={inputs?.[item.key]}

                  onSelect={(i) => { setInputs({ ...inputs, [item.key]: i.value }) }}

                  items={(item.options || []).map(i => ({ name: i, value: i }))}

                  allowSearch={false}

                  bgClassName='bg-gray-50'

                />

              )

            }

            {item.type === 'string' && (

              <input

                placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}

                value={inputs?.[item.key] || ''}

                onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}

                className={'w-full flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50'}

                maxLength={item.max_length || DEFAULT_VALUE_MAX_LEN}

              />

            )}

            {item.type === 'paragraph' && (

              <textarea

                className="w-full h-[104px] flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50"

                placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}

                value={inputs?.[item.key] || ''}

                onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}

              />

            )}

            {item.type === 'number' && (

              <input

                type='number'

                placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}

                value={inputs?.[item.key] || ''}

                onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}

                className={'w-full flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50'}

              />

            )}

          </div>

        ))}

      </div>
    )
  }

  const canChat = () => {
    const prompt_variables = promptConfig?.prompt_variables
    if (!inputs || !prompt_variables || prompt_variables?.length === 0)
      return true

    let hasEmptyInput = ''
    const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
      const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
      return res
    }) || [] // compatible with old version
    requiredVars.forEach(({ key, name }) => {
      if (hasEmptyInput)
        return

      if (!inputs?.[key])
        hasEmptyInput = name
    })

    if (hasEmptyInput) {
      logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
      return false
    }
    return !hasEmptyInput
  }

  const handleChat = () => {
    if (!canChat())
      return

    onStartChat(inputs)
  }

  const renderNoVarPanel = () => {
    if (isPublicVersion) {
      return (
        <div>

          <AppInfo siteInfo={siteInfo} />

          <TemplateVarPanel

            isFold={false}

            header={

              <>

                <PanelTitle

                  title={t('share.chat.publicPromptConfigTitle')}

                  className='mb-1'

                />

                <PromptTemplate html={highLightPromoptTemplate} />

              </>

            }

          >

            <ChatBtn onClick={handleChat} />

          </TemplateVarPanel>
        </div>
      )
    }
    // private version
    return (
      <TemplateVarPanel

        isFold={false}

        header={

          <AppInfo siteInfo={siteInfo} />

        }

      >

        <ChatBtn onClick={handleChat} />

      </TemplateVarPanel>
    )
  }

  const renderVarPanel = () => {
    return (
      <TemplateVarPanel

        isFold={false}

        header={

          <AppInfo siteInfo={siteInfo} />

        }

      >

        {renderInputs()}

        <ChatBtn

          className='mt-3 mobile:ml-0 tablet:ml-[128px]'

          onClick={handleChat}

        />

      </TemplateVarPanel>
    )
  }

  const renderVarOpBtnGroup = () => {
    return (
      <VarOpBtnGroup

        onConfirm={() => {

          if (!canChat())

            return



          onInputsChange(inputs)

          setIsFold(true)

        }}

        onCancel={() => {

          setInputs(savedInputs)

          setIsFold(true)

        }}

      />
    )
  }

  const renderHasSetInputsPublic = () => {
    if (!canEditInputs) {
      return (
        <TemplateVarPanel

          isFold={false}

          header={

            <>

              <PanelTitle

                title={t('share.chat.publicPromptConfigTitle')}

                className='mb-1'

              />

              <PromptTemplate html={highLightPromoptTemplate} />

            </>
          }
        />
      )
    }

    return (
      <TemplateVarPanel

        isFold={isFold}

        header={

          <>

            <PanelTitle

              title={t('share.chat.publicPromptConfigTitle')}

              className='mb-1'

            />

            <PromptTemplate html={highLightPromoptTemplate} />

            {isFold && (

              <div className='flex items-center justify-between mt-3 border-t border-indigo-100 pt-4 text-xs text-indigo-600'>

                <span className='text-gray-700'>{t('share.chat.configStatusDes')}</span>

                <EditBtn onClick={() => setIsFold(false)} />

              </div>

            )}

          </>
        }
      >
        {renderInputs()}
        {renderVarOpBtnGroup()}
      </TemplateVarPanel>
    )
  }

  const renderHasSetInputsPrivate = () => {
    if (!canEditInputs || !hasVar)
      return null

    return (
      <TemplateVarPanel

        isFold={isFold}

        header={

          <div className='flex items-center justify-between text-indigo-600'>

            <PanelTitle

              title={!isFold ? t('share.chat.privatePromptConfigTitle') : t('share.chat.configStatusDes')}

            />

            {isFold && (

              <EditBtn onClick={() => setIsFold(false)} />

            )}

          </div>

        }

      >

        {renderInputs()}

        {renderVarOpBtnGroup()}

      </TemplateVarPanel>
    )
  }

  const renderHasSetInputs = () => {
    if ((!isPublicVersion && !canEditInputs) || !hasVar)
      return null

    return (
      <div

        className='pt-[88px] mb-5'

      >

        {isPublicVersion ? renderHasSetInputsPublic() : renderHasSetInputsPrivate()}

      </div>)
  }

  return (
    <div className='relative tablet:min-h-[64px]'>

      {/* {hasSetInputs && renderHeader()} */}

      <div className='mx-auto pc:w-[794px] max-w-full mobile:w-full px-3.5'>

        {/*  Has't set inputs  */}

        {

          !hasSetInputs && (

            <div className='mobile:pt-[72px] tablet:pt-[128px] pc:pt-[200px]'>

              {hasVar

                ? (

                  renderVarPanel()

                )

                : (

                  renderNoVarPanel()

                )}

            </div>

          )

        }



        {/* Has set inputs */}

        {hasSetInputs && renderHasSetInputs()}



        {/* foot */}

        {!hasSetInputs && (

          <div className='mt-4 flex justify-between items-center h-8 text-xs text-gray-400'>



            {siteInfo.privacy_policy

              ? <div>{t('share.chat.privacyPolicyLeft')}

                <a

                  className='text-gray-500 px-1'

                  href={siteInfo.privacy_policy}

                  target='_blank' rel='noopener noreferrer'>{t('share.chat.privacyPolicyMiddle')}</a>

                {t('share.chat.privacyPolicyRight')}

              </div>

              : <div>

              </div>}

            {

              customConfig?.remove_webapp_brand

                ? null

                : (

                  <a className='flex items-center pr-3 space-x-3' href="https://dify.ai/" target="_blank">

                    <span className='uppercase'>{t('share.chat.powerBy')}</span>

                    {

                      customConfig?.replace_webapp_logo

                        ? <img src={customConfig?.replace_webapp_logo} alt='logo' className='block w-auto h-5' />

                        : <FootLogo />

                    }

                  </a>

                )

            }

          </div>

        )}

      </div>

    </div >

  )

}



export default React.memo(Welcome)