PageEditor.js 7.9 KB

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