PageEditor.js 8.4 KB

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