PageEditor.js 8.1 KB

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