PageEditor.js 8.5 KB

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