PageEditor.js 10 KB

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