HtmlDocument.jsx 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import React from 'react'
  2. import HtmlDocumentComponent from '../component/HtmlDocument.jsx'
  3. import { translate } from 'react-i18next'
  4. import i18n from '../i18n.js'
  5. import {
  6. addAllResourceI18n,
  7. handleFetchResult,
  8. generateAvatarFromPublicName,
  9. PopinFixed,
  10. PopinFixedHeader,
  11. PopinFixedOption,
  12. PopinFixedContent,
  13. Timeline,
  14. NewVersionBtn,
  15. ArchiveDeleteContent,
  16. SelectStatus
  17. } from 'tracim_frontend_lib'
  18. import { MODE, debug } from '../helper.js'
  19. import {
  20. getHtmlDocContent,
  21. getHtmlDocComment,
  22. getHtmlDocRevision,
  23. postHtmlDocNewComment,
  24. putHtmlDocContent,
  25. putHtmlDocStatus,
  26. putHtmlDocIsArchived,
  27. putHtmlDocIsDeleted,
  28. putHtmlDocRestoreArchived,
  29. putHtmlDocRestoreDeleted
  30. } from '../action.async.js'
  31. class HtmlDocument extends React.Component {
  32. constructor (props) {
  33. super(props)
  34. this.state = {
  35. appName: 'html-document',
  36. isVisible: true,
  37. config: props.data ? props.data.config : debug.config,
  38. loggedUser: props.data ? props.data.loggedUser : debug.loggedUser,
  39. content: props.data ? props.data.content : debug.content,
  40. rawContentBeforeEdit: '',
  41. timeline: props.data ? [] : [], // debug.timeline,
  42. newComment: '',
  43. timelineWysiwyg: false,
  44. mode: MODE.VIEW
  45. }
  46. // i18n has been init, add resources from frontend
  47. addAllResourceI18n(i18n, this.state.config.translation)
  48. i18n.changeLanguage(this.state.loggedUser.lang)
  49. document.addEventListener('appCustomEvent', this.customEventReducer)
  50. }
  51. customEventReducer = ({ detail: { type, data } }) => { // action: { type: '', data: {} }
  52. switch (type) {
  53. case 'html-document_showApp':
  54. console.log('%c<HtmlDocument> Custom event', 'color: #28a745', type, data)
  55. this.setState({isVisible: true})
  56. break
  57. case 'html-document_hideApp':
  58. console.log('%c<HtmlDocument> Custom event', 'color: #28a745', type, data)
  59. this.setState({isVisible: false})
  60. break
  61. case 'html-document_reloadContent':
  62. console.log('%c<HtmlDocument> Custom event', 'color: #28a745', type, data)
  63. this.setState(prev => ({content: {...prev.content, ...data}, isVisible: true}))
  64. break
  65. case 'allApp_changeLang':
  66. console.log('%c<HtmlDocument> Custom event', 'color: #28a745', type, data)
  67. this.setState(prev => ({
  68. loggedUser: {
  69. ...prev.loggedUser,
  70. lang: data
  71. }
  72. }))
  73. i18n.changeLanguage(data)
  74. break
  75. }
  76. }
  77. componentDidMount () {
  78. console.log('%c<HtmlDocument> did mount', `color: ${this.state.config.hexcolor}`)
  79. this.loadContent()
  80. }
  81. componentDidUpdate (prevProps, prevState) {
  82. const { state } = this
  83. console.log('%c<HtmlDocument> did update', `color: ${this.state.config.hexcolor}`, prevState, state)
  84. if (!prevState.content || !state.content) return
  85. if (prevState.content.content_id !== state.content.content_id) this.loadContent()
  86. if (state.mode === MODE.EDIT && prevState.mode !== state.mode) {
  87. tinymce.remove('#wysiwygNewVersion')
  88. wysiwyg('#wysiwygNewVersion', this.handleChangeText)
  89. }
  90. if (!prevState.timelineWysiwyg && state.timelineWysiwyg) wysiwyg('#wysiwygTimelineComment', this.handleChangeNewComment)
  91. else if (prevState.timelineWysiwyg && !state.timelineWysiwyg) tinymce.remove('#wysiwygTimelineComment')
  92. }
  93. componentWillUnmount () {
  94. console.log('%c<HtmlDocument> will Unmount', `color: ${this.state.config.hexcolor}`)
  95. document.removeEventListener('appCustomEvent', this.customEventReducer)
  96. }
  97. loadContent = async () => {
  98. const { loggedUser, content, config } = this.state
  99. const fetchResultHtmlDocument = getHtmlDocContent(loggedUser, config.apiUrl, content.workspace_id, content.content_id)
  100. const fetchResultComment = getHtmlDocComment(loggedUser, config.apiUrl, content.workspace_id, content.content_id)
  101. const fetchResultRevision = getHtmlDocRevision(loggedUser, config.apiUrl, content.workspace_id, content.content_id)
  102. handleFetchResult(await fetchResultHtmlDocument)
  103. .then(resHtmlDocument => this.setState({content: resHtmlDocument.body}))
  104. .catch(e => console.log('Error loading content.', e))
  105. Promise.all([
  106. handleFetchResult(await fetchResultComment),
  107. handleFetchResult(await fetchResultRevision)
  108. ])
  109. .then(([resComment, resRevision]) => {
  110. const resCommentWithProperDateAndAvatar = resComment.body.map(c => ({
  111. ...c,
  112. created: (new Date(c.created)).toLocaleString(),
  113. author: {
  114. ...c.author,
  115. avatar_url: c.author.avatar_url
  116. ? c.author.avatar_url
  117. : generateAvatarFromPublicName(c.author.public_name)
  118. }
  119. }))
  120. const revisionWithComment = resRevision.body
  121. .map((r, i) => ({
  122. ...r,
  123. created: (new Date(r.created)).toLocaleString(),
  124. timelineType: 'revision',
  125. commentList: r.comment_ids.map(ci => ({
  126. timelineType: 'comment',
  127. ...resCommentWithProperDateAndAvatar.find(c => c.content_id === ci)
  128. })),
  129. number: i + 1
  130. }))
  131. .reduce((acc, rev) => [
  132. ...acc,
  133. rev,
  134. ...rev.commentList.map(comment => ({
  135. ...comment,
  136. customClass: '',
  137. loggedUser: this.state.config.loggedUser
  138. }))
  139. ], [])
  140. this.setState({
  141. timeline: revisionWithComment,
  142. mode: resRevision.body.length === 1 ? MODE.EDIT : MODE.VIEW // first time editing the doc, open in edit mode
  143. })
  144. })
  145. .catch(e => {
  146. console.log('Error loading Timeline.', e)
  147. this.setState({timeline: []})
  148. })
  149. }
  150. handleClickBtnCloseApp = () => {
  151. this.setState({ isVisible: false })
  152. GLOBAL_dispatchEvent({type: 'appClosed', data: {}}) // handled by tracim_front::src/container/WorkspaceContent.jsx
  153. }
  154. handleSaveEditTitle = async newTitle => {
  155. const { loggedUser, config, content } = this.state
  156. const fetchResultSaveHtmlDoc = putHtmlDocContent(loggedUser, config.apiUrl, content.workspace_id, content.content_id, newTitle, content.raw_content)
  157. handleFetchResult(await fetchResultSaveHtmlDoc)
  158. .then(resSave => {
  159. if (resSave.apiResponse.status === 200) {
  160. this.loadContent()
  161. GLOBAL_dispatchEvent({ type: 'refreshContentList', data: {} })
  162. } else {
  163. console.warn('Error saving html-document. Result:', resSave, 'content:', content, 'config:', config)
  164. }
  165. })
  166. }
  167. handleClickNewVersion = () => this.setState(prev => ({
  168. rawContentBeforeEdit: prev.content.raw_content,
  169. mode: MODE.EDIT
  170. }))
  171. handleCloseNewVersion = () => {
  172. tinymce.remove('#wysiwygNewVersion')
  173. this.setState(prev => ({
  174. content: {
  175. ...prev.content,
  176. raw_content: prev.rawContentBeforeEdit
  177. },
  178. mode: MODE.VIEW
  179. }))
  180. }
  181. handleSaveHtmlDocument = async () => {
  182. const { loggedUser, content, config } = this.state
  183. const fetchResultSaveHtmlDoc = putHtmlDocContent(loggedUser, config.apiUrl, content.workspace_id, content.content_id, content.label, content.raw_content)
  184. handleFetchResult(await fetchResultSaveHtmlDoc)
  185. .then(resSave => {
  186. if (resSave.apiResponse.status === 200) {
  187. this.handleCloseNewVersion()
  188. this.loadContent()
  189. } else {
  190. console.warn('Error saving html-document. Result:', resSave, 'content:', content, 'config:', config)
  191. }
  192. })
  193. }
  194. handleChangeText = e => {
  195. const newText = e.target.value // because SyntheticEvent is pooled (react specificity)
  196. this.setState(prev => ({content: {...prev.content, raw_content: newText}}))
  197. }
  198. handleChangeNewComment = e => {
  199. const newComment = e.target.value
  200. this.setState({newComment})
  201. }
  202. handleClickValidateNewCommentBtn = async () => {
  203. const { loggedUser, config, content, newComment } = this.state
  204. const fetchResultSaveNewComment = await postHtmlDocNewComment(loggedUser, config.apiUrl, content.workspace_id, content.content_id, newComment)
  205. handleFetchResult(await fetchResultSaveNewComment)
  206. .then(resSave => {
  207. if (resSave.apiResponse.status === 200) {
  208. this.setState({newComment: ''})
  209. if (this.state.timelineWysiwyg) tinymce.get('wysiwygTimelineComment').setContent('')
  210. this.loadContent()
  211. } else {
  212. console.warn('Error saving html-document comment. Result:', resSave, 'content:', content, 'config:', config)
  213. }
  214. })
  215. }
  216. handleToggleWysiwyg = () => this.setState(prev => ({timelineWysiwyg: !prev.timelineWysiwyg}))
  217. handleChangeStatus = async newStatus => {
  218. const { loggedUser, config, content } = this.state
  219. const fetchResultSaveEditStatus = putHtmlDocStatus(loggedUser, config.apiUrl, content.workspace_id, content.content_id, newStatus)
  220. handleFetchResult(await fetchResultSaveEditStatus)
  221. .then(resSave => {
  222. if (resSave.status !== 204) { // 204 no content so dont take status from resSave.apiResponse.status
  223. console.warn('Error saving html-document comment. Result:', resSave, 'content:', content, 'config:', config)
  224. } else {
  225. this.loadContent()
  226. }
  227. })
  228. }
  229. handleClickArchive = async () => {
  230. const { loggedUser, config, content } = this.state
  231. const fetchResultArchive = await putHtmlDocIsArchived(loggedUser, config.apiUrl, content.workspace_id, content.content_id)
  232. switch (fetchResultArchive.status) {
  233. case 204: this.setState(prev => ({content: {...prev.content, is_archived: true}})); break
  234. default: GLOBAL_dispatchEvent({
  235. type: 'addFlashMsg',
  236. data: {
  237. msg: this.props.t('Error while archiving document'),
  238. type: 'warning',
  239. delay: undefined
  240. }
  241. })
  242. }
  243. }
  244. handleClickDelete = async () => {
  245. const { loggedUser, config, content } = this.state
  246. const fetchResultArchive = await putHtmlDocIsDeleted(loggedUser, config.apiUrl, content.workspace_id, content.content_id)
  247. switch (fetchResultArchive.status) {
  248. case 204: this.setState(prev => ({content: {...prev.content, is_deleted: true}})); break
  249. default: GLOBAL_dispatchEvent({
  250. type: 'addFlashMsg',
  251. data: {
  252. msg: this.props.t('Error while deleting document'),
  253. type: 'warning',
  254. delay: undefined
  255. }
  256. })
  257. }
  258. }
  259. handleClickRestoreArchived = async () => {
  260. const { loggedUser, config, content } = this.state
  261. const fetchResultRestore = await putHtmlDocRestoreArchived(loggedUser, config.apiUrl, content.workspace_id, content.content_id)
  262. switch (fetchResultRestore.status) {
  263. case 204: this.setState(prev => ({content: {...prev.content, is_archived: false}})); break
  264. default: GLOBAL_dispatchEvent({
  265. type: 'addFlashMsg',
  266. data: {
  267. msg: this.props.t('Error while restoring document'),
  268. type: 'warning',
  269. delay: undefined
  270. }
  271. })
  272. }
  273. }
  274. handleClickRestoreDeleted = async () => {
  275. const { loggedUser, config, content } = this.state
  276. const fetchResultRestore = await putHtmlDocRestoreDeleted(loggedUser, config.apiUrl, content.workspace_id, content.content_id)
  277. switch (fetchResultRestore.status) {
  278. case 204: this.setState(prev => ({content: {...prev.content, is_deleted: false}})); break
  279. default: GLOBAL_dispatchEvent({
  280. type: 'addFlashMsg',
  281. data: {
  282. msg: this.props.t('Error while restoring document'),
  283. type: 'warning',
  284. delay: undefined
  285. }
  286. })
  287. }
  288. }
  289. handleClickShowRevision = revision => {
  290. const { mode, timeline } = this.state
  291. const revisionArray = timeline.filter(t => t.timelineType === 'revision')
  292. const isLastRevision = revision.revision_id === revisionArray[revisionArray.length - 1].revision_id
  293. if (mode === MODE.REVISION && isLastRevision) {
  294. this.handleClickLastVersion()
  295. return
  296. }
  297. if (mode === MODE.VIEW && isLastRevision) return
  298. this.setState(prev => ({
  299. content: {
  300. ...prev.content,
  301. label: revision.label,
  302. raw_content: revision.raw_content,
  303. number: revision.number,
  304. status: revision.status,
  305. is_archived: prev.is_archived, // archived and delete should always be taken from last version
  306. is_deleted: prev.is_deleted
  307. },
  308. mode: MODE.REVISION
  309. }))
  310. }
  311. handleClickLastVersion = () => {
  312. this.loadContent()
  313. this.setState({mode: MODE.VIEW})
  314. }
  315. render () {
  316. const { isVisible, loggedUser, content, timeline, newComment, timelineWysiwyg, config, mode } = this.state
  317. const { t } = this.props
  318. if (!isVisible) return null
  319. return (
  320. <PopinFixed
  321. customClass={`${config.slug}`}
  322. customColor={config.hexcolor}
  323. >
  324. <PopinFixedHeader
  325. customClass={`${config.slug}`}
  326. customColor={config.hexcolor}
  327. faIcon={config.faIcon}
  328. title={content.label}
  329. onClickCloseBtn={this.handleClickBtnCloseApp}
  330. onValidateChangeTitle={this.handleSaveEditTitle}
  331. />
  332. <PopinFixedOption
  333. customColor={config.hexcolor}
  334. customClass={`${config.slug}`}
  335. i18n={i18n}
  336. >
  337. <div /* this div in display flex, justify-content space-between */>
  338. <div className='d-flex'>
  339. <NewVersionBtn
  340. customColor={config.hexcolor}
  341. onClickNewVersionBtn={this.handleClickNewVersion}
  342. disabled={mode !== MODE.VIEW}
  343. />
  344. {mode === MODE.REVISION &&
  345. <button
  346. className='wsContentGeneric__option__menu__lastversion html-document__lastversionbtn btn'
  347. onClick={this.handleClickLastVersion}
  348. style={{backgroundColor: config.hexcolor, color: '#fdfdfd'}}
  349. >
  350. <i className='fa fa-code-fork' />
  351. {t('Last version')}
  352. </button>
  353. }
  354. </div>
  355. <div className='d-flex'>
  356. <SelectStatus
  357. selectedStatus={config.availableStatuses.find(s => s.slug === content.status)}
  358. availableStatus={config.availableStatuses}
  359. onChangeStatus={this.handleChangeStatus}
  360. disabled={mode === MODE.REVISION}
  361. />
  362. <ArchiveDeleteContent
  363. customColor={config.hexcolor}
  364. onClickArchiveBtn={this.handleClickArchive}
  365. onClickDeleteBtn={this.handleClickDelete}
  366. disabled={mode === MODE.REVISION}
  367. />
  368. </div>
  369. </div>
  370. </PopinFixedOption>
  371. <PopinFixedContent
  372. customClass={`${config.slug}__contentpage`}
  373. showRightPartOnLoad={mode === MODE.VIEW}
  374. >
  375. <HtmlDocumentComponent
  376. mode={mode}
  377. customColor={config.hexcolor}
  378. wysiwygNewVersion={'wysiwygNewVersion'}
  379. onClickCloseEditMode={this.handleCloseNewVersion}
  380. onClickValidateBtn={this.handleSaveHtmlDocument}
  381. version={content.number}
  382. lastVersion={timeline.filter(t => t.timelineType === 'revision').length}
  383. text={content.raw_content}
  384. onChangeText={this.handleChangeText}
  385. isArchived={content.is_archived}
  386. isDeleted={content.is_deleted}
  387. onClickRestoreArchived={this.handleClickRestoreArchived}
  388. onClickRestoreDeleted={this.handleClickRestoreDeleted}
  389. key={'html-document'}
  390. />
  391. <Timeline
  392. customClass={`${config.slug}__contentpage`}
  393. customColor={config.hexcolor}
  394. loggedUser={loggedUser}
  395. timelineData={timeline}
  396. newComment={newComment}
  397. disableComment={mode === MODE.REVISION}
  398. wysiwyg={timelineWysiwyg}
  399. onChangeNewComment={this.handleChangeNewComment}
  400. onClickValidateNewCommentBtn={this.handleClickValidateNewCommentBtn}
  401. onClickWysiwygBtn={this.handleToggleWysiwyg}
  402. onClickRevisionBtn={this.handleClickShowRevision}
  403. shouldScrollToBottom={mode !== MODE.REVISION}
  404. />
  405. </PopinFixedContent>
  406. </PopinFixed>
  407. )
  408. }
  409. }
  410. export default translate()(HtmlDocument)