PageEditor.js 10 KB

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