PageEditor.js 10 KB

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