PageEditor.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. }
  132. /**
  133. * the scroll event handler from codemirror
  134. * @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).
  135. * see https://codemirror.net/doc/manual.html#events
  136. */
  137. onEditorScroll(data) {
  138. const rate = data.top / (data.height - data.clientHeight)
  139. const top = this.getScrollTop(this.previewElement, rate);
  140. this.previewElement.scrollTop = top;
  141. }
  142. /**
  143. * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
  144. * @param {*} dom
  145. */
  146. getMaxScrollTop(dom) {
  147. var rect = dom.getBoundingClientRect();
  148. return dom.scrollHeight - rect.height;
  149. };
  150. /**
  151. * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
  152. * @param {*} dom
  153. */
  154. getScrollTop(dom, rate) {
  155. var maxScrollTop = this.getMaxScrollTop(dom);
  156. var top = maxScrollTop * rate;
  157. return top;
  158. };
  159. restoreDraft() {
  160. // restore draft when the first time to edit
  161. const draft = this.props.crowi.findDraft(this.props.pagePath);
  162. if (!this.props.revisionId && draft != null) {
  163. this.setState({markdown: draft});
  164. }
  165. }
  166. saveDraft() {
  167. // only when the first time to edit
  168. if (!this.state.revisionId) {
  169. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  170. }
  171. }
  172. clearDraft() {
  173. this.props.crowi.clearDraft(this.props.pagePath);
  174. }
  175. pageSavedHandler(page) {
  176. // update states
  177. this.setState({
  178. revisionId: page.revision._id,
  179. markdown: page.revision.body
  180. })
  181. // clear draft
  182. this.clearDraft();
  183. // dispatch onSaveSuccess event
  184. if (this.props.onSaveSuccess != null) {
  185. this.props.onSaveSuccess(page);
  186. }
  187. }
  188. apiErrorHandler(error) {
  189. console.error(error);
  190. toastr.error(error.message, 'Error occured', {
  191. closeButton: true,
  192. progressBar: true,
  193. newestOnTop: false,
  194. showDuration: "100",
  195. hideDuration: "100",
  196. timeOut: "3000",
  197. });
  198. }
  199. renderPreview() {
  200. const config = this.props.crowi.config;
  201. // generate options obj
  202. const rendererOptions = {
  203. // see: https://www.npmjs.com/package/marked
  204. marked: {
  205. breaks: config.isEnabledLineBreaks,
  206. }
  207. };
  208. // render html
  209. var context = {
  210. markdown: this.state.markdown,
  211. dom: this.previewElement,
  212. currentPagePath: decodeURIComponent(location.pathname)
  213. };
  214. this.props.crowi.interceptorManager.process('preRenderPreview', context)
  215. .then(() => crowi.interceptorManager.process('prePreProcess', context))
  216. .then(() => {
  217. context.markdown = crowiRenderer.preProcess(context.markdown, context.dom);
  218. })
  219. .then(() => crowi.interceptorManager.process('postPreProcess', context))
  220. .then(() => {
  221. var parsedHTML = crowiRenderer.render(context.markdown, context.dom, rendererOptions);
  222. context['parsedHTML'] = parsedHTML;
  223. })
  224. .then(() => crowi.interceptorManager.process('postRenderPreview', context))
  225. .then(() => crowi.interceptorManager.process('preRenderPreviewHtml', context))
  226. .then(() => {
  227. this.setState({html: context.parsedHTML});
  228. // set html to the hidden input (for submitting to save)
  229. $('#form-body').val(this.state.markdown);
  230. })
  231. // process interceptors for post rendering
  232. .then(() => crowi.interceptorManager.process('postRenderPreviewHtml', context));
  233. }
  234. render() {
  235. return (
  236. <div className="row">
  237. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  238. <Editor ref="editor" value={this.state.markdown}
  239. isUploadable={this.state.isUploadable}
  240. isUploadableFile={this.state.isUploadableFile}
  241. onScroll={this.onEditorScroll}
  242. onChange={this.onMarkdownChanged}
  243. onSave={this.onSave}
  244. onUpload={this.onUpload}
  245. />
  246. </div>
  247. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  248. <Preview html={this.state.html} inputRef={el => this.previewElement = el} />
  249. </div>
  250. </div>
  251. )
  252. }
  253. }
  254. PageEditor.propTypes = {
  255. crowi: PropTypes.object.isRequired,
  256. markdown: PropTypes.string.isRequired,
  257. pageId: PropTypes.string,
  258. revisionId: PropTypes.string,
  259. pagePath: PropTypes.string,
  260. onSaveSuccess: PropTypes.func,
  261. };