index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import React, { useCallback, useMemo, useRef, useState } from 'react'
  2. import styles from './index.module.scss'
  3. // 引入编辑器组件
  4. // 安装---npm install braft-editor --save --force
  5. // npm install braft-utils --save --force
  6. import { ContentUtils } from 'braft-utils'
  7. import BraftEditor from 'braft-editor'
  8. // 引入编辑器样式
  9. import 'braft-editor/dist/index.css'
  10. import classNames from 'classnames'
  11. import { MessageFu } from '@/utils/message'
  12. import { fileDomInitialFu } from '@/utils/domShow'
  13. import { baseURL } from '@/utils/http'
  14. import { forwardRef, useImperativeHandle } from 'react'
  15. import { API_upFile } from '@/store/action/layout'
  16. import ZupAudio, { ZupAudioType } from '../ZupAudio'
  17. import { Button, Checkbox, Input } from 'antd'
  18. import { ArrowDownOutlined, DeleteOutlined, ArrowUpOutlined } from '@ant-design/icons'
  19. import MyPopconfirm from '../MyPopconfirm'
  20. export type SectionArrType = {
  21. id: number
  22. name: string
  23. txt: any
  24. fileInfo: ZupAudioType
  25. }
  26. type Props = {
  27. check: boolean //表单校验,为fasle表示不校验
  28. dirCode: string //文件的code码
  29. isLook: boolean //是否是查看进来
  30. ref: any //当前自己的ref,给父组件调用
  31. myUrl: string //上传的api地址
  32. isOne?: boolean //只显示单个富文本
  33. upAudioBtnNone?: boolean //是否能上传无障碍音频
  34. }
  35. function ZRichTexts(
  36. { check, dirCode, isLook, myUrl, isOne = false, upAudioBtnNone = false }: Props,
  37. ref: any
  38. ) {
  39. const [sectionArr, setSectionArr] = useState<SectionArrType[]>([
  40. {
  41. id: Date.now(),
  42. name: '',
  43. txt: BraftEditor.createEditorState(''),
  44. fileInfo: { fileName: '', filePath: '' }
  45. }
  46. ])
  47. // 是否按章节发布
  48. const [isSection, setIsSection] = useState(false)
  49. // 当前上传 图片 视频的索引
  50. const nowIndexRef = useRef(0)
  51. // 判断 富文本是否为空
  52. const isTxtFlag = useMemo(() => {
  53. let flag = false
  54. // 不是按章节发布,检查第一个富文本
  55. if (!isSection) {
  56. const txt = sectionArr[0].txt.toHTML()
  57. const txtRes = txt.replaceAll(' ', '').replaceAll('</p><p>', '')
  58. if (txtRes.split('></p>').length - 1 === 1 || txtRes === '') flag = true
  59. } else {
  60. // 按章节发布 检查 所有的 标题 和富文本
  61. sectionArr.forEach((v, i) => {
  62. if (!v.name) flag = true
  63. const txt: string = v.txt.toHTML()
  64. const txtRes = txt.replaceAll(' ', '').replaceAll('</p><p>', '')
  65. if (txtRes.split('></p>').length - 1 === 1 || txtRes === '') flag = true
  66. })
  67. }
  68. return flag
  69. }, [isSection, sectionArr])
  70. const myInput = useRef<HTMLInputElement>(null)
  71. // 上传图片、视频
  72. const handeUpPhoto = useCallback(
  73. async (e: React.ChangeEvent<HTMLInputElement>) => {
  74. if (e.target.files) {
  75. // 拿到files信息
  76. const filesInfo = e.target.files[0]
  77. let type = ['image/jpeg', 'image/png', 'video/mp4']
  78. let size = 5
  79. let txt = '图片只支持png、jpg和jpeg格式!'
  80. let txt2 = '图片最大支持5M!'
  81. const isVideoFlag = filesInfo.name.endsWith('.mp4') || filesInfo.name.endsWith('.MP4')
  82. if (isVideoFlag) {
  83. // 上传视频
  84. size = 500
  85. txt = '视频只支持mp4格式!'
  86. txt2 = '视频最大支持500M!'
  87. }
  88. // 校验格式
  89. if (!type.includes(filesInfo.type)) {
  90. e.target.value = ''
  91. return MessageFu.warning(txt)
  92. }
  93. // 校验大小
  94. if (filesInfo.size > size * 1024 * 1024) {
  95. e.target.value = ''
  96. return MessageFu.warning(txt2)
  97. }
  98. // 创建FormData对象
  99. const fd = new FormData()
  100. // 把files添加进FormData对象(‘photo’为后端需要的字段)
  101. fd.append('type', isVideoFlag ? 'video' : 'img')
  102. fd.append('dirCode', dirCode)
  103. fd.append('file', filesInfo)
  104. e.target.value = ''
  105. try {
  106. const res = await API_upFile(fd, myUrl)
  107. if (res.code === 0) {
  108. MessageFu.success('上传成功!')
  109. // 在光标位置插入图片
  110. const newTxt = ContentUtils.insertMedias(sectionArr[nowIndexRef.current].txt, [
  111. {
  112. type: isVideoFlag ? 'VIDEO' : 'IMAGE',
  113. url: baseURL + res.data.filePath
  114. }
  115. ])
  116. const arr = [...sectionArr]
  117. arr[nowIndexRef.current].txt = newTxt
  118. setSectionArr(arr)
  119. }
  120. fileDomInitialFu()
  121. } catch (error) {
  122. fileDomInitialFu()
  123. }
  124. }
  125. },
  126. [dirCode, myUrl, sectionArr]
  127. )
  128. // 让父组件调用的 回显 富文本
  129. const ritxtShowFu = useCallback((val: any) => {
  130. if (val) {
  131. setIsSection(val.isSection || false)
  132. if (val.txtArr) {
  133. const arr = val.txtArr.map((v: any) => ({
  134. ...v,
  135. txt: BraftEditor.createEditorState(v.txt)
  136. }))
  137. setSectionArr(arr)
  138. }
  139. }
  140. }, [])
  141. // 让父组件调用的返回 富文本信息 和 表单校验 isTxtFlag为ture表示未通过校验
  142. const fatherBtnOkFu = useCallback(() => {
  143. const arr: any[] = []
  144. sectionArr.forEach((v, i) => {
  145. arr.push({
  146. ...v,
  147. txt: v.txt.toHTML()
  148. })
  149. })
  150. const obj = {
  151. isSection: isSection, //是否按章节发布
  152. txtArr: arr
  153. }
  154. return { val: obj, flag: isTxtFlag }
  155. }, [isSection, isTxtFlag, sectionArr])
  156. // 可以让父组件调用子组件的方法
  157. useImperativeHandle(ref, () => ({
  158. ritxtShowFu,
  159. fatherBtnOkFu
  160. }))
  161. // 点击新增章节
  162. const addSectionFu = useCallback(() => {
  163. if (sectionArr.length >= 20) return MessageFu.warning('最多存在20个章节')
  164. setSectionArr([
  165. ...sectionArr,
  166. {
  167. id: Date.now(),
  168. name: '',
  169. txt: BraftEditor.createEditorState(''),
  170. fileInfo: { fileName: '', filePath: '' }
  171. }
  172. ])
  173. }, [sectionArr])
  174. // 章节音频上传成功
  175. const upSectionFu = useCallback(
  176. (info: ZupAudioType, index: number) => {
  177. const arr = [...sectionArr]
  178. arr[index].fileInfo = info
  179. setSectionArr(arr)
  180. },
  181. [sectionArr]
  182. )
  183. // 章节音频删除
  184. const delSectionFu = useCallback(
  185. (index: number) => {
  186. // console.log("ppppppppp", index);
  187. const arr = [...sectionArr]
  188. arr[index].fileInfo = { fileName: '', filePath: '' }
  189. setSectionArr(arr)
  190. },
  191. [sectionArr]
  192. )
  193. // 整个章节的删除
  194. const delSectionAllFu = useCallback(
  195. (id: number) => {
  196. setSectionArr(sectionArr.filter(v => v.id !== id))
  197. },
  198. [sectionArr]
  199. )
  200. // 整个章节的位移
  201. const moveSectionFu = useCallback(
  202. (index: number, num: number) => {
  203. const arr = [...sectionArr]
  204. const temp = arr[index]
  205. arr[index] = arr[index + num]
  206. arr[index + num] = temp
  207. setSectionArr(arr)
  208. },
  209. [sectionArr]
  210. )
  211. // 单个富文本是否输入完整
  212. const isOneTxtFlag = useCallback(
  213. (name: string, txt: any) => {
  214. let flag = false
  215. if (!name && isSection) flag = true
  216. const txtRes: string = txt.toHTML()
  217. if (txtRes.replaceAll('<p>', '').replaceAll('</p>', '').replaceAll(' ', '') === '')
  218. flag = true
  219. return flag
  220. },
  221. [isSection]
  222. )
  223. return (
  224. <div className={styles.ZRichTexts}>
  225. <input
  226. id='upInput'
  227. type='file'
  228. accept='.png,.jpg,.jpeg,.mp4'
  229. ref={myInput}
  230. onChange={e => handeUpPhoto(e)}
  231. />
  232. <div className={classNames('formRightZW', isLook ? 'formRightZWLook' : '')}>
  233. {isOne ? (
  234. <div></div>
  235. ) : (
  236. <Checkbox checked={isSection} onChange={e => setIsSection(e.target.checked)}>
  237. 按章节发布
  238. </Checkbox>
  239. )}
  240. {isSection ? (
  241. <Button hidden={isLook} type='primary' onClick={addSectionFu}>
  242. 新增章节
  243. </Button>
  244. ) : (
  245. <div className='formRightZWRR'>
  246. {upAudioBtnNone ? null : (
  247. <ZupAudio
  248. fileInfo={sectionArr[0].fileInfo}
  249. upDataFu={info => upSectionFu(info, 0)}
  250. delFu={() => delSectionFu(0)}
  251. dirCode={dirCode}
  252. myUrl={myUrl}
  253. isLook={isLook}
  254. />
  255. )}
  256. <div hidden={isLook} style={{ marginLeft: 20 }}>
  257. <Button
  258. onClick={() => {
  259. nowIndexRef.current = 0
  260. myInput.current?.click()
  261. }}
  262. >
  263. 上传图片/视频
  264. </Button>
  265. </div>
  266. </div>
  267. )}
  268. </div>
  269. <div className={classNames('txtBox', isLook ? 'txtBoxLook' : '')}>
  270. {sectionArr.map((item, index) => (
  271. <div
  272. className={classNames(
  273. 'zztxtRow',
  274. isOneTxtFlag(item.name, item.txt) && check ? 'zztxtRowErr' : ''
  275. )}
  276. key={item.id}
  277. hidden={!isSection && index > 0}
  278. >
  279. {/* 顶部 */}
  280. <div className='zztxtRow1' hidden={!isSection && index === 0}>
  281. <div className='zztxtRow1_1'>
  282. <div className='zztxtRow1_1_1'>章节 {index + 1}</div>
  283. <div className='zztxtRow1_1_2'>
  284. 标题:
  285. <Input
  286. readOnly={isLook}
  287. value={item.name}
  288. placeholder='请输入内容'
  289. maxLength={100}
  290. showCount
  291. style={{ width: 400 }}
  292. onChange={e => {
  293. const arr = [...sectionArr]
  294. arr[index].name = e.target.value.replace(/\s+/g, '')
  295. setSectionArr(arr)
  296. }}
  297. />
  298. &emsp;
  299. <Button
  300. hidden={isLook}
  301. onClick={() => {
  302. nowIndexRef.current = index
  303. myInput.current?.click()
  304. }}
  305. >
  306. 上传图片/视频
  307. </Button>
  308. </div>
  309. </div>
  310. <div className='zztxtRow1_2'>
  311. <ZupAudio
  312. fileInfo={item.fileInfo}
  313. upDataFu={info => upSectionFu(info, index)}
  314. delFu={() => delSectionFu(index)}
  315. dirCode={dirCode}
  316. myUrl={myUrl}
  317. isLook={isLook}
  318. />
  319. &emsp;
  320. <div
  321. hidden={isLook}
  322. className={classNames('zztxtRow1_2Icon', index === 0 ? 'zztxtRow1_2IconNo' : '')}
  323. onClick={() => moveSectionFu(index, -1)}
  324. >
  325. <ArrowUpOutlined title='上移' />
  326. </div>
  327. &emsp;
  328. <div
  329. hidden={isLook}
  330. className={classNames(
  331. 'zztxtRow1_2Icon',
  332. index === sectionArr.length - 1 ? 'zztxtRow1_2IconNo' : ''
  333. )}
  334. onClick={() => moveSectionFu(index, 1)}
  335. >
  336. <ArrowDownOutlined title='下移' />
  337. </div>
  338. &emsp;
  339. {isLook || sectionArr.length <= 1 ? null : (
  340. <MyPopconfirm
  341. txtK='删除'
  342. onConfirm={() => delSectionAllFu(item.id)}
  343. Dom={<DeleteOutlined title='删除' className='ZTbox2X' />}
  344. />
  345. )}
  346. </div>
  347. </div>
  348. {/* 主体 */}
  349. <BraftEditor
  350. readOnly={isLook}
  351. placeholder='请输入内容'
  352. value={item.txt}
  353. onChange={e => {
  354. const arr = [...sectionArr]
  355. arr[index].txt = e
  356. setSectionArr(arr)
  357. }}
  358. imageControls={['remove']}
  359. />
  360. </div>
  361. ))}
  362. </div>
  363. <div className={classNames('noUpThumb', check && isTxtFlag ? 'noUpThumbAc' : '')}>
  364. {`请完整输入${isSection ? '标题/' : ''}正文!`}
  365. </div>
  366. </div>
  367. )
  368. }
  369. export default forwardRef(ZRichTexts)