PageEditor.js 11 KB

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