HtmlDocument.jsx 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import React from 'react'
  2. import HtmlDocumentComponent from '../component/HtmlDocument.jsx'
  3. import {
  4. handleFetchResult,
  5. PopinFixed,
  6. PopinFixedHeader,
  7. PopinFixedOption,
  8. PopinFixedContent,
  9. Timeline
  10. } from 'tracim_lib'
  11. import { FETCH_CONFIG, MODE, debug } from '../helper.js'
  12. import i18n from '../i18n.js'
  13. class HtmlDocument extends React.Component {
  14. constructor (props) {
  15. super(props)
  16. this.state = {
  17. appName: 'html-documents',
  18. isVisible: true,
  19. config: props.data ? props.data.config : debug.config,
  20. loggedUser: props.data ? props.data.loggedUser : debug.loggedUser,
  21. content: props.data ? props.data.content : debug.content,
  22. timeline: props.data ? [] : [], // debug.timeline,
  23. newComment: '',
  24. timelineWysiwyg: false,
  25. mode: MODE.VIEW
  26. }
  27. document.addEventListener('appCustomEvent', this.customEventReducer)
  28. }
  29. customEventReducer = ({ detail: { type, data } }) => { // action: { type: '', data: {} }
  30. switch (type) {
  31. case 'html-documents_showApp':
  32. this.setState({isVisible: true})
  33. break
  34. case 'html-documents_hideApp':
  35. this.setState({isVisible: false})
  36. break
  37. case 'html-documents_reloadContent':
  38. this.setState({content: data})
  39. }
  40. }
  41. componentDidMount () {
  42. console.log('HtmlDocument did mount')
  43. this.loadContent()
  44. }
  45. componentDidUpdate (prevProps, prevState) {
  46. const { state } = this
  47. console.log('HtmlDocument did update', prevState, state)
  48. if (!prevState.content || !state.content) return
  49. if (prevState.content.content_id !== state.content.content_id) this.loadContent()
  50. if (state.mode === MODE.EDIT) wysiwyg('#wysiwygNewVersion', this.handleChangeText)
  51. if (!prevState.timelineWysiwyg && state.timelineWysiwyg) wysiwyg('#wysiwygTimelineComment', this.handleChangeNewComment)
  52. else if (prevState.timelineWysiwyg && !state.timelineWysiwyg) tinymce.remove('#wysiwygTimelineComment')
  53. }
  54. loadContent = async () => {
  55. const { content, config } = this.state
  56. const fetchResultHtmlDocument = await fetch(`${config.apiUrl}/workspaces/${content.workspace_id}/html-documents/${content.content_id}`, { // ${content.workspace_id} ${content.content_id}
  57. ...FETCH_CONFIG,
  58. method: 'GET'
  59. })
  60. const fetchResultComment = await fetch(`${config.apiUrl}/workspaces/${content.workspace_id}/contents/${content.content_id}/comments`, { // ${content.workspace_id} ${content.content_id}
  61. ...FETCH_CONFIG,
  62. method: 'GET'
  63. })
  64. const fetchResultRevision = await fetch(`${config.apiUrl}/workspaces/${content.workspace_id}/html-documents/${content.content_id}/revisions`, { // ${content.workspace_id} ${content.content_id}
  65. ...FETCH_CONFIG,
  66. method: 'GET'
  67. })
  68. handleFetchResult(fetchResultHtmlDocument)
  69. .then(resHtmlDocument => this.setState({content: resHtmlDocument.body}))
  70. .catch(e => console.log('Error loading content.', e))
  71. Promise.all([
  72. handleFetchResult(fetchResultComment),
  73. handleFetchResult(fetchResultRevision)
  74. ])
  75. .then(([resComment, resRevision]) => {
  76. const resCommentWithProperDate = resComment.body.map(c => ({...c, created: (new Date(c.created)).toLocaleString()}))
  77. const revisionWithComment = resRevision.body
  78. .map(r => ({
  79. ...r,
  80. created: (new Date(r.created)).toLocaleString(),
  81. timelineType: 'revision',
  82. commentList: r.comments_ids.map(ci => ({
  83. timelineType: 'comment',
  84. ...resCommentWithProperDate.find(c => c.content_id === ci)
  85. }))
  86. }))
  87. .reduce((acc, rev) => [
  88. ...acc,
  89. rev,
  90. ...rev.commentList.map(comment => ({
  91. ...comment,
  92. customClass: '',
  93. loggedUser: this.state.config.loggedUser
  94. }))
  95. ], [])
  96. console.log(revisionWithComment)
  97. this.setState({timeline: revisionWithComment})
  98. })
  99. .catch(e => {
  100. console.log('Error loading Timeline.', e)
  101. this.setState({timeline: []})
  102. })
  103. }
  104. saveEditHtmlDocument = (label, rawContent) =>
  105. fetch(`${this.state.config.apiUrl}/workspaces/${this.state.content.workspace_id}/html-documents/${this.state.content.content_id}`, {
  106. ...FETCH_CONFIG,
  107. method: 'PUT',
  108. body: JSON.stringify({label: label, raw_content: rawContent})
  109. })
  110. handleClickBtnCloseApp = () => {
  111. this.setState({ isVisible: false })
  112. GLOBAL_dispatchEvent({type: 'appClosed', data: {}})
  113. }
  114. handleSaveEditTitle = async newTitle => {
  115. const fetchResultSaveHtmlDoc = await this.saveEditHtmlDocument(newTitle, this.state.content.raw_content)
  116. handleFetchResult(fetchResultSaveHtmlDoc)
  117. .then(resSave => {
  118. if (resSave.apiResponse.status === 200) this.loadContent()
  119. else console.warn('Error saving html-document. Result:', resSave, 'content:', this.state.content, 'config:', this.state.config)
  120. })
  121. }
  122. handleClickNewVersion = () => this.setState({ mode: MODE.EDIT })
  123. handleCloseNewVersion = () => {
  124. tinymce.remove('#wysiwygNewVersion')
  125. this.setState({ mode: MODE.VIEW })
  126. }
  127. handleSaveHtmlDocument = async () => {
  128. const { content, config } = this.state
  129. const fetchResultSaveHtmlDoc = await this.saveEditHtmlDocument(content.label, content.raw_content)
  130. handleFetchResult(fetchResultSaveHtmlDoc)
  131. .then(resSave => {
  132. if (resSave.apiResponse.status === 200) {
  133. this.handleCloseNewVersion()
  134. this.loadContent()
  135. } else {
  136. console.warn('Error saving html-document. Result:', resSave, 'content:', content, 'config:', config)
  137. }
  138. })
  139. }
  140. handleChangeText = e => {
  141. const newText = e.target.value // because SyntheticEvent is pooled (react specificity)
  142. this.setState(prev => ({content: {...prev.content, raw_content: newText}}))
  143. }
  144. handleChangeNewComment = e => {
  145. const newComment = e.target.value
  146. this.setState({newComment})
  147. }
  148. handleClickValidateNewCommentBtn = async () => {
  149. const { config, content, newComment } = this.state
  150. const fetchResultSaveNewComment = await fetch(`${config.apiUrl}/workspaces/${content.workspace_id}/contents/${content.content_id}/comments`, {
  151. ...FETCH_CONFIG,
  152. method: 'POST',
  153. body: JSON.stringify({
  154. raw_content: newComment
  155. })
  156. })
  157. handleFetchResult(fetchResultSaveNewComment)
  158. .then(resSave => {
  159. if (resSave.apiResponse.status === 200) {
  160. this.setState({newComment: ''})
  161. if (this.state.timelineWysiwyg) tinymce.get('wysiwygTimelineComment').setContent('')
  162. this.loadContent()
  163. } else {
  164. console.warn('Error saving html-document comment. Result:', resSave, 'content:', content, 'config:', config)
  165. }
  166. })
  167. }
  168. handleToggleWysiwyg = () => this.setState(prev => ({timelineWysiwyg: !prev.timelineWysiwyg}))
  169. handleChangeStatus = async newStatus => {
  170. const { config, content } = this.state
  171. const fetchResultSaveEditStatus = await fetch(`${config.apiUrl}/workspaces/${content.workspace_id}/html-documents/${content.content_id}/status`, {
  172. ...FETCH_CONFIG,
  173. method: 'PUT',
  174. body: JSON.stringify({
  175. status: newStatus
  176. })
  177. })
  178. handleFetchResult(fetchResultSaveEditStatus)
  179. .then(resSave => {
  180. if (resSave.status !== 204) { // 204 no content so dont take status from resSave.apiResponse.status
  181. console.warn('Error saving html-document comment. Result:', resSave, 'content:', content, 'config:', config)
  182. } else {
  183. this.loadContent()
  184. }
  185. })
  186. }
  187. handleClickArchive = async () => {
  188. console.log('archive')
  189. // const { config, content } = this.state
  190. //
  191. // const fetchResultArchive = await fetch(`${config.apiUrl}/workspaces/${content.workspace_id}/contents/${content.content_id}/archive`, {
  192. // ...FETCH_CONFIG,
  193. // method: 'PUT'
  194. // })
  195. }
  196. handleClickDelete = async () => {
  197. console.log('delete')
  198. // const { config, content } = this.state
  199. // const fetchResultDelete = await fetch(`${config.apiUrl}/workspaces/${content.workspace_id}/contents/${content.content_id}/delete`, {
  200. // ...FETCH_CONFIG,
  201. // method: 'PUT'
  202. // })
  203. }
  204. render () {
  205. const { isVisible, loggedUser, content, timeline, newComment, timelineWysiwyg, config } = this.state
  206. if (!isVisible) return null
  207. return (
  208. <PopinFixed customClass={`${config.slug}`}>
  209. <PopinFixedHeader
  210. customClass={`${config.slug}`}
  211. faIcon={config.faIcon}
  212. title={content.label}
  213. onClickCloseBtn={this.handleClickBtnCloseApp}
  214. onValidateChangeTitle={this.handleSaveEditTitle}
  215. />
  216. <PopinFixedOption
  217. customClass={`${config.slug}`}
  218. availableStatus={config.availableStatuses}
  219. onClickNewVersionBtn={this.handleClickNewVersion}
  220. onChangeStatus={this.handleChangeStatus}
  221. selectedStatus={config.availableStatuses.find(s => s.slug === content.status)} // might be empty while api hasn't responded yet
  222. onClickArchive={this.handleClickArchive}
  223. onClickDelete={this.handleClickDelete}
  224. i18n={i18n}
  225. />
  226. <PopinFixedContent customClass={`${config.slug}__contentpage`}>
  227. <HtmlDocumentComponent
  228. mode={this.state.mode}
  229. wysiwygNewVersion={'wysiwygNewVersion'}
  230. onClickCloseEditMode={this.handleCloseNewVersion}
  231. onClickValidateBtn={this.handleSaveHtmlDocument}
  232. version={timeline.filter(t => t.timelineType === 'revision').length}
  233. text={content.raw_content}
  234. onChangeText={this.handleChangeText}
  235. key={'html-documents'}
  236. />
  237. <Timeline
  238. customClass={`${config.slug}__contentpage`}
  239. loggedUser={loggedUser}
  240. timelineData={timeline}
  241. newComment={newComment}
  242. wysiwyg={timelineWysiwyg}
  243. onChangeNewComment={this.handleChangeNewComment}
  244. onClickValidateNewCommentBtn={this.handleClickValidateNewCommentBtn}
  245. onClickWysiwygBtn={this.handleToggleWysiwyg}
  246. />
  247. </PopinFixedContent>
  248. </PopinFixed>
  249. )
  250. }
  251. }
  252. export default HtmlDocument