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