PageEditor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { throttle, debounce } from 'throttle-debounce';
  4. import GrowiRenderer from '../util/GrowiRenderer';
  5. import { EditorOptions, PreviewOptions } from './PageEditor/OptionsSelector';
  6. import Editor from './PageEditor/Editor';
  7. import Preview from './PageEditor/Preview';
  8. import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
  9. import { promise } from 'when';
  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. pageId: this.props.pageId,
  19. revisionId: this.props.revisionId,
  20. markdown: this.props.markdown,
  21. isUploadable,
  22. isUploadableFile,
  23. isMathJaxEnabled,
  24. editorOptions: this.props.editorOptions,
  25. previewOptions: this.props.previewOptions,
  26. };
  27. this.growiRenderer = new GrowiRenderer(this.props.crowi, this.props.crowiRenderer, {mode: 'editor'});
  28. this.setCaretLine = this.setCaretLine.bind(this);
  29. this.focusToEditor = this.focusToEditor.bind(this);
  30. this.onMarkdownChanged = this.onMarkdownChanged.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.onPreviewScroll = this.onPreviewScroll.bind(this);
  35. this.saveDraft = this.saveDraft.bind(this);
  36. this.clearDraft = this.clearDraft.bind(this);
  37. // for scrolling
  38. this.lastScrolledDateWithCursor = null;
  39. this.isOriginOfScrollSyncEditor = false;
  40. this.isOriginOfScrollSyncEditor = false;
  41. // create throttled function
  42. this.scrollPreviewByEditorLineWithThrottle = throttle(20, this.scrollPreviewByEditorLine);
  43. this.scrollPreviewByCursorMovingWithThrottle = throttle(20, this.scrollPreviewByCursorMoving);
  44. this.scrollEditorByPreviewScrollWithThrottle = throttle(20, this.scrollEditorByPreviewScroll);
  45. this.renderPreviewWithDebounce = debounce(50, throttle(100, this.renderPreview));
  46. this.saveDraftWithDebounce = debounce(800, this.saveDraft);
  47. }
  48. componentWillMount() {
  49. // initial rendering
  50. this.renderPreview(this.state.markdown);
  51. }
  52. getMarkdown() {
  53. return this.state.markdown;
  54. }
  55. setMarkdown(markdown, updateEditorValue = true) {
  56. this.setState({ markdown });
  57. if (updateEditorValue) {
  58. this.refs.editor.setValue(markdown);
  59. }
  60. }
  61. focusToEditor() {
  62. this.refs.editor.forceToFocus();
  63. }
  64. /**
  65. * set caret position of editor
  66. * @param {number} line
  67. */
  68. setCaretLine(line) {
  69. this.refs.editor.setCaretLine(line);
  70. scrollSyncHelper.scrollPreview(this.previewElement, line);
  71. }
  72. /**
  73. * set options (used from the outside)
  74. * @param {object} editorOptions
  75. */
  76. setEditorOptions(editorOptions) {
  77. this.setState({ editorOptions });
  78. }
  79. /**
  80. * set options (used from the outside)
  81. * @param {object} previewOptions
  82. */
  83. setPreviewOptions(previewOptions) {
  84. this.setState({ previewOptions });
  85. }
  86. /**
  87. * the change event handler for `markdown` state
  88. * @param {string} value
  89. */
  90. onMarkdownChanged(value) {
  91. this.renderPreviewWithDebounce(value);
  92. this.saveDraftWithDebounce();
  93. }
  94. /**
  95. * the upload event handler
  96. * @param {any} files
  97. */
  98. async onUpload(file) {
  99. const res = await this.props.crowi.apiGet('/attachments.limit', {_csrf: this.props.crowi.csrfToken});
  100. if (file.size > res.usableCapacity) {
  101. throw new Error('mongoDB for file uploading reaches limit');
  102. }
  103. else {
  104. const endpoint = '/attachments.add';
  105. // create a FromData instance
  106. const formData = new FormData();
  107. formData.append('_csrf', this.props.crowi.csrfToken);
  108. formData.append('file', file);
  109. formData.append('path', this.props.pagePath);
  110. formData.append('page_id', this.state.pageId || 0);
  111. // post
  112. this.props.crowi.apiPost(endpoint, formData)
  113. .then((res) => {
  114. const url = res.url;
  115. const attachment = res.attachment;
  116. const fileName = attachment.originalName;
  117. let insertText = `[${fileName}](${url})`;
  118. // when image
  119. if (attachment.fileFormat.startsWith('image/')) {
  120. // modify to "![fileName](url)" syntax
  121. insertText = '!' + insertText;
  122. }
  123. this.refs.editor.insertText(insertText);
  124. // when if created newly
  125. if (res.pageCreated) {
  126. // do nothing
  127. }
  128. })
  129. .catch(this.apiErrorHandler)
  130. // finally
  131. .then(() => {
  132. this.refs.editor.terminateUploadingState();
  133. });
  134. }
  135. }
  136. /**
  137. * the scroll event handler from codemirror
  138. * @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).
  139. * And data.line is also available that is added by Editor component
  140. * @see https://codemirror.net/doc/manual.html#events
  141. */
  142. onEditorScroll(data) {
  143. // prevent scrolling
  144. // if the elapsed time from last scroll with cursor is shorter than 40ms
  145. const now = new Date();
  146. if (now - this.lastScrolledDateWithCursor < 40) {
  147. return;
  148. }
  149. this.scrollPreviewByEditorLineWithThrottle(data.line);
  150. }
  151. /**
  152. * the scroll event handler from codemirror
  153. * @param {number} line
  154. * @see https://codemirror.net/doc/manual.html#events
  155. */
  156. onEditorScrollCursorIntoView(line) {
  157. // record date
  158. this.lastScrolledDateWithCursor = new Date();
  159. this.scrollPreviewByCursorMovingWithThrottle(line);
  160. }
  161. /**
  162. * scroll Preview element by scroll event
  163. * @param {number} line
  164. */
  165. scrollPreviewByEditorLine(line) {
  166. if (this.previewElement == null) {
  167. return;
  168. }
  169. // prevent circular invocation
  170. if (this.isOriginOfScrollSyncPreview) {
  171. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  172. return;
  173. }
  174. // turn on the flag
  175. this.isOriginOfScrollSyncEditor = true;
  176. scrollSyncHelper.scrollPreview(this.previewElement, line);
  177. }
  178. /**
  179. * scroll Preview element by cursor moving
  180. * @param {number} line
  181. */
  182. scrollPreviewByCursorMoving(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.scrollPreviewToRevealOverflowing(this.previewElement, line);
  194. }
  195. /**
  196. * the scroll event handler from Preview component
  197. * @param {number} offset
  198. */
  199. onPreviewScroll(offset) {
  200. this.scrollEditorByPreviewScrollWithThrottle(offset);
  201. }
  202. /**
  203. * scroll Editor component by scroll event of Preview component
  204. * @param {number} offset
  205. */
  206. scrollEditorByPreviewScroll(offset) {
  207. if (this.previewElement == null) {
  208. return;
  209. }
  210. // prevent circular invocation
  211. if (this.isOriginOfScrollSyncEditor) {
  212. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  213. return;
  214. }
  215. // turn on the flag
  216. this.isOriginOfScrollSyncPreview = true;
  217. scrollSyncHelper.scrollEditor(this.refs.editor, this.previewElement, offset);
  218. }
  219. saveDraft() {
  220. // only when the first time to edit
  221. if (!this.state.revisionId) {
  222. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  223. }
  224. }
  225. clearDraft() {
  226. this.props.crowi.clearDraft(this.props.pagePath);
  227. }
  228. renderPreview(value) {
  229. this.setState({ markdown: value });
  230. // render html
  231. const context = {
  232. markdown: this.state.markdown,
  233. dom: this.previewElement,
  234. currentPagePath: decodeURIComponent(location.pathname)
  235. };
  236. const growiRenderer = this.growiRenderer;
  237. const interceptorManager = this.props.crowi.interceptorManager;
  238. interceptorManager.process('preRenderPreview', context)
  239. .then(() => interceptorManager.process('prePreProcess', context))
  240. .then(() => {
  241. context.markdown = growiRenderer.preProcess(context.markdown);
  242. })
  243. .then(() => interceptorManager.process('postPreProcess', context))
  244. .then(() => {
  245. const parsedHTML = growiRenderer.process(context.markdown);
  246. context['parsedHTML'] = parsedHTML;
  247. })
  248. .then(() => interceptorManager.process('prePostProcess', context))
  249. .then(() => {
  250. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML, context.dom);
  251. })
  252. .then(() => interceptorManager.process('postPostProcess', context))
  253. .then(() => interceptorManager.process('preRenderPreviewHtml', context))
  254. .then(() => {
  255. this.setState({ html: context.parsedHTML });
  256. })
  257. // process interceptors for post rendering
  258. .then(() => interceptorManager.process('postRenderPreviewHtml', context));
  259. }
  260. render() {
  261. const emojiStrategy = this.props.crowi.getEmojiStrategy();
  262. return (
  263. <div className="row">
  264. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  265. <Editor ref="editor" value={this.state.markdown}
  266. editorOptions={this.state.editorOptions}
  267. isMobile={this.props.crowi.isMobile}
  268. isUploadable={this.state.isUploadable}
  269. isUploadableFile={this.state.isUploadableFile}
  270. emojiStrategy={emojiStrategy}
  271. onScroll={this.onEditorScroll}
  272. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  273. onChange={this.onMarkdownChanged}
  274. onUpload={this.onUpload}
  275. onSave={() => {
  276. this.props.onSaveWithShortcut(this.state.markdown);
  277. }}
  278. />
  279. </div>
  280. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  281. <Preview html={this.state.html}
  282. inputRef={el => this.previewElement = el}
  283. isMathJaxEnabled={this.state.isMathJaxEnabled}
  284. renderMathJaxOnInit={false}
  285. previewOptions={this.state.previewOptions}
  286. onScroll={this.onPreviewScroll}
  287. />
  288. </div>
  289. </div>
  290. );
  291. }
  292. }
  293. PageEditor.propTypes = {
  294. crowi: PropTypes.object.isRequired,
  295. crowiRenderer: PropTypes.object.isRequired,
  296. onSaveWithShortcut: PropTypes.func.isRequired,
  297. markdown: PropTypes.string.isRequired,
  298. pageId: PropTypes.string,
  299. revisionId: PropTypes.string,
  300. pagePath: PropTypes.string,
  301. editorOptions: PropTypes.instanceOf(EditorOptions),
  302. previewOptions: PropTypes.instanceOf(PreviewOptions),
  303. };