PageEditor.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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(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. formData.append('_csrf', appContainer.csrfToken);
  126. formData.append('file', file);
  127. formData.append('path', pageContainer.state.path);
  128. formData.append('page_id', pageContainer.state.pageId);
  129. res = await appContainer.apiPost('/attachments.add', formData);
  130. const attachment = res.attachment;
  131. const fileName = attachment.originalName;
  132. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  133. // when image
  134. if (attachment.fileFormat.startsWith('image/')) {
  135. // modify to "![fileName](url)" syntax
  136. insertText = `!${insertText}`;
  137. }
  138. this.editor.insertText(insertText);
  139. // when if created newly
  140. if (res.pageCreated) {
  141. logger.info('Page is created', res.pageCreated._id);
  142. }
  143. }
  144. catch (e) {
  145. logger.error('failed to upload', e);
  146. pageContainer.showErrorToastr(e);
  147. }
  148. finally {
  149. this.editor.terminateUploadingState();
  150. }
  151. }
  152. /**
  153. * the scroll event handler from codemirror
  154. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  155. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  156. * And data.line is also available that is added by Editor component
  157. * @see https://codemirror.net/doc/manual.html#events
  158. */
  159. onEditorScroll(data) {
  160. // prevent scrolling
  161. // if the elapsed time from last scroll with cursor is shorter than 40ms
  162. const now = new Date();
  163. if (now - this.lastScrolledDateWithCursor < 40) {
  164. return;
  165. }
  166. this.scrollPreviewByEditorLineWithThrottle(data.line);
  167. }
  168. /**
  169. * the scroll event handler from codemirror
  170. * @param {number} line
  171. * @see https://codemirror.net/doc/manual.html#events
  172. */
  173. onEditorScrollCursorIntoView(line) {
  174. // record date
  175. this.lastScrolledDateWithCursor = new Date();
  176. this.scrollPreviewByCursorMovingWithThrottle(line);
  177. }
  178. /**
  179. * scroll Preview element by scroll event
  180. * @param {number} line
  181. */
  182. scrollPreviewByEditorLine(line) {
  183. if (this.previewElement == null) {
  184. return;
  185. }
  186. // prevent circular invocation
  187. if (this.isOriginOfScrollSyncPreview) {
  188. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  189. return;
  190. }
  191. // turn on the flag
  192. this.isOriginOfScrollSyncEditor = true;
  193. scrollSyncHelper.scrollPreview(this.previewElement, line);
  194. }
  195. /**
  196. * scroll Preview element by cursor moving
  197. * @param {number} line
  198. */
  199. scrollPreviewByCursorMoving(line) {
  200. if (this.previewElement == null) {
  201. return;
  202. }
  203. // prevent circular invocation
  204. if (this.isOriginOfScrollSyncPreview) {
  205. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  206. return;
  207. }
  208. // turn on the flag
  209. this.isOriginOfScrollSyncEditor = true;
  210. scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
  211. }
  212. /**
  213. * the scroll event handler from Preview component
  214. * @param {number} offset
  215. */
  216. onPreviewScroll(offset) {
  217. this.scrollEditorByPreviewScrollWithThrottle(offset);
  218. }
  219. /**
  220. * scroll Editor component by scroll event of Preview component
  221. * @param {number} offset
  222. */
  223. scrollEditorByPreviewScroll(offset) {
  224. if (this.previewElement == null) {
  225. return;
  226. }
  227. // prevent circular invocation
  228. if (this.isOriginOfScrollSyncEditor) {
  229. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  230. return;
  231. }
  232. // turn on the flag
  233. this.isOriginOfScrollSyncPreview = true;
  234. scrollSyncHelper.scrollEditor(this.editor, this.previewElement, offset);
  235. }
  236. saveDraft() {
  237. const { pageContainer, editorContainer } = this.props;
  238. // only when the first time to edit
  239. if (!pageContainer.state.revisionId) {
  240. editorContainer.saveDraft(pageContainer.state.path, this.state.markdown);
  241. }
  242. }
  243. clearDraft() {
  244. this.props.editorContainer.clearDraft(this.props.pageContainer.state.path);
  245. }
  246. renderPreview(value) {
  247. this.setState({ markdown: value });
  248. // render html
  249. const context = {
  250. markdown: this.state.markdown,
  251. currentPagePath: decodeURIComponent(window.location.pathname),
  252. };
  253. const growiRenderer = this.growiRenderer;
  254. const interceptorManager = this.props.appContainer.interceptorManager;
  255. interceptorManager.process('preRenderPreview', context)
  256. .then(() => { return interceptorManager.process('prePreProcess', context) })
  257. .then(() => {
  258. context.markdown = growiRenderer.preProcess(context.markdown);
  259. })
  260. .then(() => { return interceptorManager.process('postPreProcess', context) })
  261. .then(() => {
  262. const parsedHTML = growiRenderer.process(context.markdown);
  263. context.parsedHTML = parsedHTML;
  264. })
  265. .then(() => { return interceptorManager.process('prePostProcess', context) })
  266. .then(() => {
  267. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  268. })
  269. .then(() => { return interceptorManager.process('postPostProcess', context) })
  270. .then(() => { return interceptorManager.process('preRenderPreviewHtml', context) })
  271. .then(() => {
  272. this.setState({ html: context.parsedHTML });
  273. })
  274. // process interceptors for post rendering
  275. .then(() => { return interceptorManager.process('postRenderPreviewHtml', context) });
  276. }
  277. render() {
  278. const config = this.props.appContainer.getConfig();
  279. const noCdn = !!config.env.NO_CDN;
  280. const emojiStrategy = this.props.appContainer.getEmojiStrategy();
  281. return (
  282. <div className="row">
  283. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  284. <Editor
  285. ref={(c) => { this.editor = c }}
  286. value={this.state.markdown}
  287. noCdn={noCdn}
  288. isMobile={this.props.appContainer.isMobile}
  289. isUploadable={this.state.isUploadable}
  290. isUploadableFile={this.state.isUploadableFile}
  291. emojiStrategy={emojiStrategy}
  292. onScroll={this.onEditorScroll}
  293. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  294. onChange={this.onMarkdownChanged}
  295. onUpload={this.onUpload}
  296. onSave={this.onSaveWithShortcut}
  297. />
  298. </div>
  299. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  300. <Preview
  301. html={this.state.html}
  302. // eslint-disable-next-line no-return-assign
  303. inputRef={(el) => { return this.previewElement = el }}
  304. isMathJaxEnabled={this.state.isMathJaxEnabled}
  305. renderMathJaxOnInit={false}
  306. onScroll={this.onPreviewScroll}
  307. />
  308. </div>
  309. </div>
  310. );
  311. }
  312. }
  313. /**
  314. * Wrapper component for using unstated
  315. */
  316. const PageEditorWrapper = (props) => {
  317. return createSubscribedElement(PageEditor, props, [AppContainer, PageContainer, EditorContainer]);
  318. };
  319. PageEditor.propTypes = {
  320. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  321. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  322. editorContainer: PropTypes.instanceOf(EditorContainer).isRequired,
  323. };
  324. export default PageEditorWrapper;