PageEditor.js 10 KB

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