index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useState } from 'react'
  4. import { PencilIcon } from '@heroicons/react/24/outline'
  5. import { useTranslation } from 'react-i18next'
  6. import { useContext } from 'use-context-selector'
  7. import { get } from 'lodash-es'
  8. import { DocumentContext } from '../index'
  9. import s from './style.module.css'
  10. import cn from '@/utils/classnames'
  11. import Input from '@/app/components/base/input'
  12. import Button from '@/app/components/base/button'
  13. import Tooltip from '@/app/components/base/tooltip'
  14. import Radio from '@/app/components/base/radio'
  15. import Divider from '@/app/components/base/divider'
  16. import { ToastContext } from '@/app/components/base/toast'
  17. import { SimpleSelect } from '@/app/components/base/select'
  18. import Loading from '@/app/components/base/loading'
  19. import AutoHeightTextarea from '@/app/components/base/auto-height-textarea'
  20. import { asyncRunSafe, getTextWidthWithCanvas } from '@/utils'
  21. import { modifyDocMetadata } from '@/service/datasets'
  22. import type { CommonResponse } from '@/models/common'
  23. import type { DocType, FullDocumentDetail } from '@/models/datasets'
  24. import { CUSTOMIZABLE_DOC_TYPES } from '@/models/datasets'
  25. import type { inputType, metadataType } from '@/hooks/use-metadata'
  26. import { useBookCategories, useBusinessDocCategories, useLanguages, useMetadataMap, usePersonalDocCategories } from '@/hooks/use-metadata'
  27. const map2Options = (map: { [key: string]: string }) => {
  28. return Object.keys(map).map(key => ({ value: key, name: map[key] }))
  29. }
  30. type IFieldInfoProps = {
  31. label: string
  32. value?: string
  33. displayedValue?: string
  34. defaultValue?: string
  35. showEdit?: boolean
  36. inputType?: inputType
  37. selectOptions?: Array<{ value: string; name: string }>
  38. onUpdate?: (v: any) => void
  39. }
  40. export const FieldInfo: FC<IFieldInfoProps> = ({
  41. label,
  42. value = '',
  43. displayedValue = '',
  44. defaultValue,
  45. showEdit = false,
  46. inputType = 'input',
  47. selectOptions = [],
  48. onUpdate,
  49. }) => {
  50. const { t } = useTranslation()
  51. const textNeedWrap = getTextWidthWithCanvas(displayedValue) > 190
  52. const editAlignTop = showEdit && inputType === 'textarea'
  53. const readAlignTop = !showEdit && textNeedWrap
  54. return (
  55. <div className={cn(s.fieldInfo, editAlignTop && '!items-start', readAlignTop && '!items-start pt-1')}>
  56. <div className={cn(s.label, editAlignTop && 'pt-1')}>{label}</div>
  57. <div className={s.value}>
  58. {!showEdit
  59. ? displayedValue
  60. : inputType === 'select'
  61. ? <SimpleSelect
  62. onSelect={({ value }) => onUpdate && onUpdate(value as string)}
  63. items={selectOptions}
  64. defaultValue={value}
  65. className={s.select}
  66. wrapperClassName={s.selectWrapper}
  67. placeholder={`${t('datasetDocuments.metadata.placeholder.select')}${label}`}
  68. />
  69. : inputType === 'textarea'
  70. ? <AutoHeightTextarea
  71. onChange={e => onUpdate && onUpdate(e.target.value)}
  72. value={value}
  73. className={s.textArea}
  74. placeholder={`${t('datasetDocuments.metadata.placeholder.add')}${label}`}
  75. />
  76. : <Input
  77. onChange={e => onUpdate?.(e.target.value)}
  78. value={value}
  79. defaultValue={defaultValue}
  80. placeholder={`${t('datasetDocuments.metadata.placeholder.add')}${label}`}
  81. />
  82. }
  83. </div>
  84. </div>
  85. )
  86. }
  87. const TypeIcon: FC<{ iconName: string; className?: string }> = ({ iconName, className = '' }) => {
  88. return <div className={cn(s.commonIcon, s[`${iconName}Icon`], className)}
  89. />
  90. }
  91. const IconButton: FC<{
  92. type: DocType
  93. isChecked: boolean
  94. }> = ({ type, isChecked = false }) => {
  95. const metadataMap = useMetadataMap()
  96. return (
  97. <Tooltip
  98. popupContent={metadataMap[type].text}
  99. >
  100. <button className={cn(s.iconWrapper, 'group', isChecked ? s.iconCheck : '')}>
  101. <TypeIcon
  102. iconName={metadataMap[type].iconName || ''}
  103. className={`group-hover:bg-primary-600 ${isChecked ? '!bg-primary-600' : ''}`}
  104. />
  105. </button>
  106. </Tooltip>
  107. )
  108. }
  109. type IMetadataProps = {
  110. docDetail?: FullDocumentDetail
  111. loading: boolean
  112. onUpdate: () => void
  113. }
  114. const Metadata: FC<IMetadataProps> = ({ docDetail, loading, onUpdate }) => {
  115. const { doc_metadata = {} } = docDetail || {}
  116. const doc_type = docDetail?.doc_type || ''
  117. const { t } = useTranslation()
  118. const metadataMap = useMetadataMap()
  119. const languageMap = useLanguages()
  120. const bookCategoryMap = useBookCategories()
  121. const personalDocCategoryMap = usePersonalDocCategories()
  122. const businessDocCategoryMap = useBusinessDocCategories()
  123. const [editStatus, setEditStatus] = useState(!doc_type) // if no documentType, in editing status by default
  124. // the initial values are according to the documentType
  125. const [metadataParams, setMetadataParams] = useState<{
  126. documentType?: DocType | ''
  127. metadata: { [key: string]: string }
  128. }>(
  129. doc_type
  130. ? {
  131. documentType: doc_type,
  132. metadata: doc_metadata || {},
  133. }
  134. : { metadata: {} })
  135. const [showDocTypes, setShowDocTypes] = useState(!doc_type) // whether show doc types
  136. const [tempDocType, setTempDocType] = useState<DocType | undefined | ''>('') // for remember icon click
  137. const [saveLoading, setSaveLoading] = useState(false)
  138. const { notify } = useContext(ToastContext)
  139. const { datasetId = '', documentId = '' } = useContext(DocumentContext)
  140. useEffect(() => {
  141. if (docDetail?.doc_type) {
  142. setEditStatus(false)
  143. setShowDocTypes(false)
  144. setTempDocType(docDetail?.doc_type)
  145. setMetadataParams({
  146. documentType: docDetail?.doc_type,
  147. metadata: docDetail?.doc_metadata || {},
  148. })
  149. }
  150. }, [docDetail?.doc_type])
  151. // confirm doc type
  152. const confirmDocType = () => {
  153. if (!tempDocType)
  154. return
  155. setMetadataParams({
  156. documentType: tempDocType,
  157. metadata: tempDocType === metadataParams.documentType ? metadataParams.metadata : {}, // change doc type, clear metadata
  158. })
  159. setEditStatus(true)
  160. setShowDocTypes(false)
  161. }
  162. // cancel doc type
  163. const cancelDocType = () => {
  164. setTempDocType(metadataParams.documentType)
  165. setEditStatus(true)
  166. setShowDocTypes(false)
  167. }
  168. // show doc type select
  169. const renderSelectDocType = () => {
  170. const { documentType } = metadataParams
  171. return (
  172. <>
  173. {!doc_type && !documentType && <>
  174. <div className={s.desc}>{t('datasetDocuments.metadata.desc')}</div>
  175. </>}
  176. <div className={s.operationWrapper}>
  177. {!doc_type && !documentType && <>
  178. <span className={s.title}>{t('datasetDocuments.metadata.docTypeSelectTitle')}</span>
  179. </>}
  180. {documentType && <>
  181. <span className={s.title}>{t('datasetDocuments.metadata.docTypeChangeTitle')}</span>
  182. <span className={s.changeTip}>{t('datasetDocuments.metadata.docTypeSelectWarning')}</span>
  183. </>}
  184. <Radio.Group value={tempDocType ?? documentType} onChange={setTempDocType} className={s.radioGroup}>
  185. {CUSTOMIZABLE_DOC_TYPES.map((type, index) => {
  186. const currValue = tempDocType ?? documentType
  187. return <Radio key={index} value={type} className={`${s.radio} ${currValue === type ? 'shadow-none' : ''}`}>
  188. <IconButton
  189. type={type}
  190. isChecked={currValue === type}
  191. />
  192. </Radio>
  193. })}
  194. </Radio.Group>
  195. {!doc_type && !documentType && (
  196. <Button variant='primary'
  197. onClick={confirmDocType}
  198. disabled={!tempDocType}
  199. >
  200. {t('datasetDocuments.metadata.firstMetaAction')}
  201. </Button>
  202. )}
  203. {documentType && <div className={s.opBtnWrapper}>
  204. <Button onClick={confirmDocType} className={`${s.opBtn} ${s.opSaveBtn}`} variant='primary' >{t('common.operation.save')}</Button>
  205. <Button onClick={cancelDocType} className={`${s.opBtn} ${s.opCancelBtn}`}>{t('common.operation.cancel')}</Button>
  206. </div>}
  207. </div >
  208. </>
  209. )
  210. }
  211. // show metadata info and edit
  212. const renderFieldInfos = ({ mainField = 'book', canEdit }: { mainField?: metadataType | ''; canEdit?: boolean }) => {
  213. if (!mainField)
  214. return null
  215. const fieldMap = metadataMap[mainField]?.subFieldsMap
  216. const sourceData = ['originInfo', 'technicalParameters'].includes(mainField) ? docDetail : metadataParams.metadata
  217. const getTargetMap = (field: string) => {
  218. if (field === 'language')
  219. return languageMap
  220. if (field === 'category' && mainField === 'book')
  221. return bookCategoryMap
  222. if (field === 'document_type') {
  223. if (mainField === 'personal_document')
  224. return personalDocCategoryMap
  225. if (mainField === 'business_document')
  226. return businessDocCategoryMap
  227. }
  228. return {} as any
  229. }
  230. const getTargetValue = (field: string) => {
  231. const val = get(sourceData, field, '')
  232. if (!val && val !== 0)
  233. return '-'
  234. if (fieldMap[field]?.inputType === 'select')
  235. return getTargetMap(field)[val]
  236. if (fieldMap[field]?.render)
  237. return fieldMap[field]?.render?.(val, field === 'hit_count' ? get(sourceData, 'segment_count', 0) as number : undefined)
  238. return val
  239. }
  240. return <div className='flex flex-col gap-1'>
  241. {Object.keys(fieldMap).map((field) => {
  242. return <FieldInfo
  243. key={fieldMap[field]?.label}
  244. label={fieldMap[field]?.label}
  245. displayedValue={getTargetValue(field)}
  246. value={get(sourceData, field, '')}
  247. inputType={fieldMap[field]?.inputType || 'input'}
  248. showEdit={canEdit}
  249. onUpdate={(val) => {
  250. setMetadataParams(pre => ({ ...pre, metadata: { ...pre.metadata, [field]: val } }))
  251. }}
  252. selectOptions={map2Options(getTargetMap(field))}
  253. />
  254. })}
  255. </div>
  256. }
  257. const enabledEdit = () => {
  258. setEditStatus(true)
  259. }
  260. const onCancel = () => {
  261. setMetadataParams({ documentType: doc_type || '', metadata: { ...(docDetail?.doc_metadata || {}) } })
  262. setEditStatus(!doc_type)
  263. if (!doc_type)
  264. setShowDocTypes(true)
  265. }
  266. const onSave = async () => {
  267. setSaveLoading(true)
  268. const [e] = await asyncRunSafe<CommonResponse>(modifyDocMetadata({
  269. datasetId,
  270. documentId,
  271. body: {
  272. doc_type: metadataParams.documentType || doc_type || '',
  273. doc_metadata: metadataParams.metadata,
  274. },
  275. }) as Promise<CommonResponse>)
  276. if (!e)
  277. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  278. else
  279. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  280. onUpdate?.()
  281. setEditStatus(false)
  282. setSaveLoading(false)
  283. }
  284. return (
  285. <div className={`${s.main} ${editStatus ? 'bg-white' : 'bg-gray-25'}`}>
  286. {loading
  287. ? (<Loading type='app' />)
  288. : (
  289. <>
  290. <div className={s.titleWrapper}>
  291. <span className={s.title}>{t('datasetDocuments.metadata.title')}</span>
  292. {!editStatus
  293. ? <Button onClick={enabledEdit} className={`${s.opBtn} ${s.opEditBtn}`}>
  294. <PencilIcon className={s.opIcon} />
  295. {t('common.operation.edit')}
  296. </Button>
  297. : showDocTypes
  298. ? null
  299. : <div className={s.opBtnWrapper}>
  300. <Button onClick={onCancel} className={`${s.opBtn} ${s.opCancelBtn}`}>{t('common.operation.cancel')}</Button>
  301. <Button onClick={onSave}
  302. className={`${s.opBtn} ${s.opSaveBtn}`}
  303. variant='primary'
  304. loading={saveLoading}
  305. >
  306. {t('common.operation.save')}
  307. </Button>
  308. </div>}
  309. </div>
  310. {/* show selected doc type and changing entry */}
  311. {!editStatus
  312. ? <div className={s.documentTypeShow}>
  313. <TypeIcon iconName={metadataMap[doc_type || 'book']?.iconName || ''} className={s.iconShow} />
  314. {metadataMap[doc_type || 'book'].text}
  315. </div>
  316. : showDocTypes
  317. ? null
  318. : <div className={s.documentTypeShow}>
  319. {metadataParams.documentType && <>
  320. <TypeIcon iconName={metadataMap[metadataParams.documentType || 'book'].iconName || ''} className={s.iconShow} />
  321. {metadataMap[metadataParams.documentType || 'book'].text}
  322. {editStatus && <div className='inline-flex items-center gap-1 ml-1'>
  323. ·
  324. <div
  325. onClick={() => { setShowDocTypes(true) }}
  326. className='cursor-pointer hover:text-[#155EEF]'
  327. >
  328. {t('common.operation.change')}
  329. </div>
  330. </div>}
  331. </>}
  332. </div>
  333. }
  334. {(!doc_type && showDocTypes) ? null : <Divider />}
  335. {showDocTypes ? renderSelectDocType() : renderFieldInfos({ mainField: metadataParams.documentType, canEdit: editStatus })}
  336. {/* show fixed fields */}
  337. <Divider />
  338. {renderFieldInfos({ mainField: 'originInfo', canEdit: false })}
  339. <div className={`${s.title} mt-8`}>{metadataMap.technicalParameters.text}</div>
  340. <Divider />
  341. {renderFieldInfos({ mainField: 'technicalParameters', canEdit: false })}
  342. </>
  343. )}
  344. </div>
  345. )
  346. }
  347. export default Metadata