HtmlDocument.jsx 14KB

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