index.tsx 12 KB

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