PageEditor.jsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import loggerFactory from '@alias/logger';
  4. import { throttle, debounce } from 'throttle-debounce';
  5. import AppContainer from '../services/AppContainer';
  6. import PageContainer from '../services/PageContainer';
  7. import { createSubscribedElement } from './UnstatedUtils';
  8. import Editor from './PageEditor/Editor';
  9. import Preview from './PageEditor/Preview';
  10. import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
  11. import EditorContainer from '../services/EditorContainer';
  12. const logger = loggerFactory('growi:PageEditor');
  13. class PageEditor extends React.Component {
  14. constructor(props) {
  15. super(props);
  16. const config = this.props.appContainer.getConfig();
  17. const isUploadable = config.upload.image || config.upload.file;
  18. const isUploadableFile = config.upload.file;
  19. const isMathJaxEnabled = !!config.env.MATHJAX;
  20. this.state = {
  21. markdown: this.props.pageContainer.state.markdown,
  22. isUploadable,
  23. isUploadableFile,
  24. isMathJaxEnabled,
  25. };
  26. this.setCaretLine = this.setCaretLine.bind(this);
  27. this.focusToEditor = this.focusToEditor.bind(this);
  28. this.onMarkdownChanged = this.onMarkdownChanged.bind(this);
  29. this.onSaveWithShortcut = this.onSaveWithShortcut.bind(this);
  30. this.onUpload = this.onUpload.bind(this);
  31. this.onEditorScroll = this.onEditorScroll.bind(this);
  32. this.onEditorScrollCursorIntoView = this.onEditorScrollCursorIntoView.bind(this);
  33. this.onPreviewScroll = this.onPreviewScroll.bind(this);
  34. this.saveDraft = this.saveDraft.bind(this);
  35. this.clearDraft = this.clearDraft.bind(this);
  36. // get renderer
  37. this.growiRenderer = this.props.appContainer.getRenderer('editor');
  38. // for scrolling
  39. this.lastScrolledDateWithCursor = null;
  40. this.isOriginOfScrollSyncEditor = false;
  41. this.isOriginOfScrollSyncEditor = false;
  42. // create throttled function
  43. this.scrollPreviewByEditorLineWithThrottle = throttle(20, this.scrollPreviewByEditorLine);
  44. this.scrollPreviewByCursorMovingWithThrottle = throttle(20, this.scrollPreviewByCursorMoving);
  45. this.scrollEditorByPreviewScrollWithThrottle = throttle(20, this.scrollEditorByPreviewScroll);
  46. this.renderPreviewWithDebounce = debounce(50, throttle(100, this.renderPreview));
  47. this.saveDraftWithDebounce = debounce(800, this.saveDraft);
  48. }
  49. componentWillMount() {
  50. this.props.appContainer.registerComponentInstance('PageEditor', this);
  51. // initial rendering
  52. this.renderPreview(this.state.markdown);
  53. }
  54. getMarkdown() {
  55. return this.state.markdown;
  56. }
  57. updateEditorValue(markdown) {
  58. this.editor.setValue(markdown);
  59. }
  60. focusToEditor() {
  61. this.editor.forceToFocus();
  62. }
  63. /**
  64. * set caret position of editor
  65. * @param {number} line
  66. */
  67. setCaretLine(line) {
  68. this.editor.setCaretLine(line);
  69. scrollSyncHelper.scrollPreview(this.previewElement, line);
  70. }
  71. /**
  72. * the change event handler for `markdown` state
  73. * @param {string} value
  74. */
  75. onMarkdownChanged(value) {
  76. this.renderPreviewWithDebounce(value);
  77. this.saveDraftWithDebounce();
  78. }
  79. /**
  80. * save and update state of containers
  81. */
  82. async onSaveWithShortcut() {
  83. const { pageContainer, editorContainer } = this.props;
  84. const optionsToSave = editorContainer.getCurrentOptionsToSave();
  85. try {
  86. // disable unsaved warning
  87. editorContainer.disableUnsavedWarning();
  88. // eslint-disable-next-line no-unused-vars
  89. const { page, tags } = await pageContainer.save(this.state.markdown, optionsToSave);
  90. logger.debug('success to save');
  91. pageContainer.showSuccessToastr();
  92. // update state of EditorContainer
  93. editorContainer.setState({ tags });
  94. }
  95. catch (error) {
  96. logger.error('failed to save', error);
  97. pageContainer.showErrorToastr(error);
  98. }
  99. }
  100. /**
  101. * the upload event handler
  102. * @param {any} file
  103. */
  104. async onUpload(file) {
  105. const { appContainer, pageContainer } = this.props;
  106. try {
  107. let res = await appContainer.apiGet('/attachments.limit', {
  108. fileSize: file.size,
  109. });
  110. if (!res.isUploadable) {
  111. throw new Error(res.errorMessage);
  112. }
  113. const formData = new FormData();
  114. const { pageId, path } = pageContainer.state;
  115. formData.append('_csrf', appContainer.csrfToken);
  116. formData.append('file', file);
  117. formData.append('path', path);
  118. if (pageId != null) {
  119. formData.append('page_id', pageContainer.state.pageId);
  120. }
  121. res = await appContainer.apiPost('/attachments.add', formData);
  122. const attachment = res.attachment;
  123. const fileName = attachment.originalName;
  124. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  125. // when image
  126. if (attachment.fileFormat.startsWith('image/')) {
  127. // modify to "![fileName](url)" syntax
  128. insertText = `!${insertText}`;
  129. }
  130. this.editor.insertText(insertText);
  131. // when if created newly
  132. if (res.pageCreated) {
  133. logger.info('Page is created', res.pageCreated._id);
  134. }
  135. }
  136. catch (e) {
  137. logger.error('failed to upload', e);
  138. pageContainer.showErrorToastr(e);
  139. }
  140. finally {
  141. this.editor.terminateUploadingState();
  142. }
  143. }
  144. /**
  145. * the scroll event handler from codemirror
  146. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  147. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  148. * And data.line is also available that is added by Editor component
  149. * @see https://codemirror.net/doc/manual.html#events
  150. */
  151. onEditorScroll(data) {
  152. // prevent scrolling
  153. // if the elapsed time from last scroll with cursor is shorter than 40ms
  154. const now = new Date();
  155. if (now - this.lastScrolledDateWithCursor < 40) {
  156. return;
  157. }
  158. this.scrollPreviewByEditorLineWithThrottle(data.line);
  159. }
  160. /**
  161. * the scroll event handler from codemirror
  162. * @param {number} line
  163. * @see https://codemirror.net/doc/manual.html#events
  164. */
  165. onEditorScrollCursorIntoView(line) {
  166. // record date
  167. this.lastScrolledDateWithCursor = new Date();
  168. this.scrollPreviewByCursorMovingWithThrottle(line);
  169. }
  170. /**
  171. * scroll Preview element by scroll event
  172. * @param {number} line
  173. */
  174. scrollPreviewByEditorLine(line) {
  175. if (this.previewElement == null) {
  176. return;
  177. }
  178. // prevent circular invocation
  179. if (this.isOriginOfScrollSyncPreview) {
  180. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  181. return;
  182. }
  183. // turn on the flag
  184. this.isOriginOfScrollSyncEditor = true;
  185. scrollSyncHelper.scrollPreview(this.previewElement, line);
  186. }
  187. /**
  188. * scroll Preview element by cursor moving
  189. * @param {number} line
  190. */
  191. scrollPreviewByCursorMoving(line) {
  192. if (this.previewElement == null) {
  193. return;
  194. }
  195. // prevent circular invocation
  196. if (this.isOriginOfScrollSyncPreview) {
  197. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  198. return;
  199. }
  200. // turn on the flag
  201. this.isOriginOfScrollSyncEditor = true;
  202. scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
  203. }
  204. /**
  205. * the scroll event handler from Preview component
  206. * @param {number} offset
  207. */
  208. onPreviewScroll(offset) {
  209. this.scrollEditorByPreviewScrollWithThrottle(offset);
  210. }
  211. /**
  212. * scroll Editor component by scroll event of Preview component
  213. * @param {number} offset
  214. */
  215. scrollEditorByPreviewScroll(offset) {
  216. if (this.previewElement == null) {
  217. return;
  218. }
  219. // prevent circular invocation
  220. if (this.isOriginOfScrollSyncEditor) {
  221. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  222. return;
  223. }
  224. // turn on the flag
  225. this.isOriginOfScrollSyncPreview = true;
  226. scrollSyncHelper.scrollEditor(this.editor, this.previewElement, offset);
  227. }
  228. saveDraft() {
  229. const { pageContainer, editorContainer } = this.props;
  230. // only when the first time to edit
  231. if (!pageContainer.state.revisionId) {
  232. editorContainer.saveDraft(pageContainer.state.path, this.state.markdown);
  233. }
  234. editorContainer.enableUnsavedWarning();
  235. }
  236. clearDraft() {
  237. this.props.editorContainer.clearDraft(this.props.pageContainer.state.path);
  238. }
  239. renderPreview(value) {
  240. this.setState({ markdown: value });
  241. // render html
  242. const context = {
  243. markdown: this.state.markdown,
  244. currentPagePath: decodeURIComponent(window.location.pathname),
  245. };
  246. const growiRenderer = this.growiRenderer;
  247. const interceptorManager = this.props.appContainer.interceptorManager;
  248. interceptorManager.process('preRenderPreview', context)
  249. .then(() => { return interceptorManager.process('prePreProcess', context) })
  250. .then(() => {
  251. context.markdown = growiRenderer.preProcess(context.markdown);
  252. })
  253. .then(() => { return interceptorManager.process('postPreProcess', context) })
  254. .then(() => {
  255. const parsedHTML = growiRenderer.process(context.markdown);
  256. context.parsedHTML = parsedHTML;
  257. })
  258. .then(() => { return interceptorManager.process('prePostProcess', context) })
  259. .then(() => {
  260. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  261. })
  262. .then(() => { return interceptorManager.process('postPostProcess', context) })
  263. .then(() => { return interceptorManager.process('preRenderPreviewHtml', context) })
  264. .then(() => {
  265. this.setState({ html: context.parsedHTML });
  266. })
  267. // process interceptors for post rendering
  268. .then(() => { return interceptorManager.process('postRenderPreviewHtml', context) });
  269. }
  270. render() {
  271. const config = this.props.appContainer.getConfig();
  272. const noCdn = !!config.env.NO_CDN;
  273. const emojiStrategy = this.props.appContainer.getEmojiStrategy();
  274. return (
  275. <div className="row">
  276. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  277. <Editor
  278. ref={(c) => { this.editor = c }}
  279. value={this.state.markdown}
  280. noCdn={noCdn}
  281. isMobile={this.props.appContainer.isMobile}
  282. isUploadable={this.state.isUploadable}
  283. isUploadableFile={this.state.isUploadableFile}
  284. emojiStrategy={emojiStrategy}
  285. onScroll={this.onEditorScroll}
  286. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  287. onChange={this.onMarkdownChanged}
  288. onUpload={this.onUpload}
  289. onSave={this.onSaveWithShortcut}
  290. />
  291. </div>
  292. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  293. <Preview
  294. html={this.state.html}
  295. // eslint-disable-next-line no-return-assign
  296. inputRef={(el) => { return this.previewElement = el }}
  297. isMathJaxEnabled={this.state.isMathJaxEnabled}
  298. renderMathJaxOnInit={false}
  299. onScroll={this.onPreviewScroll}
  300. />
  301. </div>
  302. </div>
  303. );
  304. }
  305. }
  306. /**
  307. * Wrapper component for using unstated
  308. */
  309. const PageEditorWrapper = (props) => {
  310. return createSubscribedElement(PageEditor, props, [AppContainer, PageContainer, EditorContainer]);
  311. };
  312. PageEditor.propTypes = {
  313. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  314. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  315. editorContainer: PropTypes.instanceOf(EditorContainer).isRequired,
  316. };
  317. export default PageEditorWrapper;