PageEditor.js 10 KB

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