PageEditor.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import * as toastr from 'toastr';
  4. import {debounce} from 'throttle-debounce';
  5. import Editor from './PageEditor/Editor';
  6. import Preview from './PageEditor/Preview';
  7. export default class PageEditor extends React.Component {
  8. constructor(props) {
  9. super(props);
  10. const config = this.props.crowi.getConfig();
  11. const isUploadable = config.upload.image || config.upload.file;
  12. const isUploadableFile = config.upload.file;
  13. this.state = {
  14. revisionId: this.props.revisionId,
  15. markdown: this.props.markdown,
  16. isUploadable,
  17. isUploadableFile,
  18. };
  19. this.setCaretLine = this.setCaretLine.bind(this);
  20. this.focusToEditor = this.focusToEditor.bind(this);
  21. this.onMarkdownChanged = this.onMarkdownChanged.bind(this);
  22. this.onSave = this.onSave.bind(this);
  23. this.onUpload = this.onUpload.bind(this);
  24. this.onEditorScroll = this.onEditorScroll.bind(this);
  25. this.getMaxScrollTop = this.getMaxScrollTop.bind(this);
  26. this.getScrollTop = this.getScrollTop.bind(this);
  27. this.saveDraft = this.saveDraft.bind(this);
  28. this.clearDraft = this.clearDraft.bind(this);
  29. this.pageSavedHandler = this.pageSavedHandler.bind(this);
  30. this.apiErrorHandler = this.apiErrorHandler.bind(this);
  31. // create debounced function
  32. this.saveDraftWithDebounce = debounce(300, this.saveDraft);
  33. }
  34. componentWillMount() {
  35. // restore draft
  36. this.restoreDraft();
  37. // initial preview
  38. this.renderPreview();
  39. }
  40. focusToEditor() {
  41. this.refs.editor.forceToFocus();
  42. }
  43. /**
  44. * set caret position of editor
  45. * @param {number} line
  46. */
  47. setCaretLine(line) {
  48. this.refs.editor.setCaretLine(line);
  49. }
  50. /**
  51. * the change event handler for `markdown` state
  52. * @param {string} value
  53. */
  54. onMarkdownChanged(value) {
  55. this.setState({
  56. markdown: value,
  57. });
  58. this.renderPreview();
  59. this.saveDraftWithDebounce()
  60. }
  61. /**
  62. * the save event handler
  63. */
  64. onSave() {
  65. let endpoint;
  66. let data;
  67. // update
  68. if (this.props.pageId != null) {
  69. endpoint = '/pages.update';
  70. data = {
  71. page_id: this.props.pageId,
  72. revision_id: this.state.revisionId,
  73. body: this.state.markdown,
  74. };
  75. }
  76. // create
  77. else {
  78. endpoint = '/pages.create';
  79. data = {
  80. path: this.props.pagePath,
  81. body: this.state.markdown,
  82. };
  83. }
  84. this.props.crowi.apiPost(endpoint, data)
  85. .then((res) => {
  86. // show toastr
  87. toastr.success(undefined, 'Saved successfully', {
  88. closeButton: true,
  89. progressBar: true,
  90. newestOnTop: false,
  91. showDuration: "100",
  92. hideDuration: "100",
  93. timeOut: "1200",
  94. extendedTimeOut: "150",
  95. });
  96. this.pageSavedHandler(res.page);
  97. })
  98. .catch(this.apiErrorHandler)
  99. }
  100. /**
  101. * the upload event handler
  102. * @param {any} files
  103. */
  104. onUpload(file) {
  105. const endpoint = '/attachments.add';
  106. // create a FromData instance
  107. const formData = new FormData();
  108. formData.append('_csrf', this.props.crowi.csrfToken);
  109. formData.append('file', file);
  110. formData.append('path', this.props.pagePath);
  111. formData.append('page_id', this.props.pageId || 0);
  112. // post
  113. this.props.crowi.apiPost(endpoint, formData)
  114. .then((res) => {
  115. const url = res.url;
  116. const attachment = res.attachment;
  117. const fileName = attachment.originalName;
  118. let insertText = `[${fileName}](${url})`;
  119. // when image
  120. if (attachment.fileFormat.startsWith('image/')) {
  121. // modify to "![fileName](url)" syntax
  122. insertText = '!' + insertText;
  123. }
  124. this.refs.editor.insertText(insertText);
  125. // update page information if created
  126. if (res.pageCreated) {
  127. this.pageSavedHandler(res.page);
  128. }
  129. })
  130. .catch(this.apiErrorHandler)
  131. // finally
  132. .then(() => {
  133. this.refs.editor.terminateUploadingState();
  134. });
  135. }
  136. /**
  137. * the scroll event handler from codemirror
  138. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position, the size of the scrollable area, and the size of the visible area (minus scrollbars).
  139. * see https://codemirror.net/doc/manual.html#events
  140. */
  141. onEditorScroll(data) {
  142. const rate = data.top / (data.height - data.clientHeight)
  143. const top = this.getScrollTop(this.previewElement, rate);
  144. this.previewElement.scrollTop = top;
  145. }
  146. /**
  147. * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
  148. * @param {*} dom
  149. */
  150. getMaxScrollTop(dom) {
  151. var rect = dom.getBoundingClientRect();
  152. return dom.scrollHeight - rect.height;
  153. };
  154. /**
  155. * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
  156. * @param {*} dom
  157. */
  158. getScrollTop(dom, rate) {
  159. var maxScrollTop = this.getMaxScrollTop(dom);
  160. var top = maxScrollTop * rate;
  161. return top;
  162. };
  163. restoreDraft() {
  164. // restore draft when the first time to edit
  165. const draft = this.props.crowi.findDraft(this.props.pagePath);
  166. if (!this.props.revisionId && draft != null) {
  167. this.setState({markdown: draft});
  168. }
  169. }
  170. saveDraft() {
  171. // only when the first time to edit
  172. if (!this.state.revisionId) {
  173. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  174. }
  175. }
  176. clearDraft() {
  177. this.props.crowi.clearDraft(this.props.pagePath);
  178. }
  179. pageSavedHandler(page) {
  180. // update states
  181. this.setState({
  182. revisionId: page.revision._id,
  183. markdown: page.revision.body
  184. })
  185. // clear draft
  186. this.clearDraft();
  187. // dispatch onSaveSuccess event
  188. if (this.props.onSaveSuccess != null) {
  189. this.props.onSaveSuccess(page);
  190. }
  191. }
  192. apiErrorHandler(error) {
  193. console.error(error);
  194. toastr.error(error.message, 'Error occured', {
  195. closeButton: true,
  196. progressBar: true,
  197. newestOnTop: false,
  198. showDuration: "100",
  199. hideDuration: "100",
  200. timeOut: "3000",
  201. });
  202. }
  203. renderPreview() {
  204. const config = this.props.crowi.config;
  205. // generate options obj
  206. const rendererOptions = {
  207. // see: https://www.npmjs.com/package/marked
  208. marked: {
  209. breaks: config.isEnabledLineBreaks,
  210. }
  211. };
  212. // render html
  213. var context = {
  214. markdown: this.state.markdown,
  215. dom: this.previewElement,
  216. currentPagePath: decodeURIComponent(location.pathname)
  217. };
  218. this.props.crowi.interceptorManager.process('preRenderPreview', context)
  219. .then(() => crowi.interceptorManager.process('prePreProcess', context))
  220. .then(() => {
  221. context.markdown = crowiRenderer.preProcess(context.markdown, context.dom);
  222. })
  223. .then(() => crowi.interceptorManager.process('postPreProcess', context))
  224. .then(() => {
  225. var parsedHTML = crowiRenderer.render(context.markdown, context.dom, rendererOptions);
  226. context['parsedHTML'] = parsedHTML;
  227. })
  228. .then(() => crowi.interceptorManager.process('postRenderPreview', context))
  229. .then(() => crowi.interceptorManager.process('preRenderPreviewHtml', context))
  230. .then(() => {
  231. this.setState({html: context.parsedHTML});
  232. // set html to the hidden input (for submitting to save)
  233. $('#form-body').val(this.state.markdown);
  234. })
  235. // process interceptors for post rendering
  236. .then(() => crowi.interceptorManager.process('postRenderPreviewHtml', context));
  237. }
  238. render() {
  239. return (
  240. <div className="row">
  241. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  242. <Editor ref="editor" value={this.state.markdown}
  243. isUploadable={this.state.isUploadable}
  244. isUploadableFile={this.state.isUploadableFile}
  245. onScroll={this.onEditorScroll}
  246. onChange={this.onMarkdownChanged}
  247. onSave={this.onSave}
  248. onUpload={this.onUpload}
  249. />
  250. </div>
  251. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  252. <Preview html={this.state.html} inputRef={el => this.previewElement = el} />
  253. </div>
  254. </div>
  255. )
  256. }
  257. }
  258. PageEditor.propTypes = {
  259. crowi: PropTypes.object.isRequired,
  260. markdown: PropTypes.string.isRequired,
  261. pageId: PropTypes.string,
  262. revisionId: PropTypes.string,
  263. pagePath: PropTypes.string,
  264. onSaveSuccess: PropTypes.func,
  265. };