PageEditor.jsx 12 KB

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