PageEditor.js 9.7 KB

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