PageEditor.js 8.5 KB

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