PageEditor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { throttle, debounce } from 'throttle-debounce';
  4. import * as toastr from 'toastr';
  5. import GrowiRenderer from '../util/GrowiRenderer';
  6. import { EditorOptions, PreviewOptions } from './PageEditor/OptionsSelector';
  7. import Editor from './PageEditor/Editor';
  8. import Preview from './PageEditor/Preview';
  9. import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
  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.editor.setValue(markdown);
  60. }
  61. }
  62. focusToEditor() {
  63. this.editor.forceToFocus();
  64. }
  65. /**
  66. * set caret position of editor
  67. * @param {number} line
  68. */
  69. setCaretLine(line) {
  70. this.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.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.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,
  146. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  147. * And data.line is also available that is added by Editor component
  148. * @see https://codemirror.net/doc/manual.html#events
  149. */
  150. onEditorScroll(data) {
  151. // prevent scrolling
  152. // if the elapsed time from last scroll with cursor is shorter than 40ms
  153. const now = new Date();
  154. if (now - this.lastScrolledDateWithCursor < 40) {
  155. return;
  156. }
  157. this.scrollPreviewByEditorLineWithThrottle(data.line);
  158. }
  159. /**
  160. * the scroll event handler from codemirror
  161. * @param {number} line
  162. * @see https://codemirror.net/doc/manual.html#events
  163. */
  164. onEditorScrollCursorIntoView(line) {
  165. // record date
  166. this.lastScrolledDateWithCursor = new Date();
  167. this.scrollPreviewByCursorMovingWithThrottle(line);
  168. }
  169. /**
  170. * scroll Preview element by scroll event
  171. * @param {number} line
  172. */
  173. scrollPreviewByEditorLine(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.scrollPreview(this.previewElement, line);
  185. }
  186. /**
  187. * scroll Preview element by cursor moving
  188. * @param {number} line
  189. */
  190. scrollPreviewByCursorMoving(line) {
  191. if (this.previewElement == null) {
  192. return;
  193. }
  194. // prevent circular invocation
  195. if (this.isOriginOfScrollSyncPreview) {
  196. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  197. return;
  198. }
  199. // turn on the flag
  200. this.isOriginOfScrollSyncEditor = true;
  201. scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
  202. }
  203. /**
  204. * the scroll event handler from Preview component
  205. * @param {number} offset
  206. */
  207. onPreviewScroll(offset) {
  208. this.scrollEditorByPreviewScrollWithThrottle(offset);
  209. }
  210. /**
  211. * scroll Editor component by scroll event of Preview component
  212. * @param {number} offset
  213. */
  214. scrollEditorByPreviewScroll(offset) {
  215. if (this.previewElement == null) {
  216. return;
  217. }
  218. // prevent circular invocation
  219. if (this.isOriginOfScrollSyncEditor) {
  220. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  221. return;
  222. }
  223. // turn on the flag
  224. this.isOriginOfScrollSyncPreview = true;
  225. scrollSyncHelper.scrollEditor(this.editor, this.previewElement, offset);
  226. }
  227. saveDraft() {
  228. // only when the first time to edit
  229. if (!this.state.revisionId) {
  230. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  231. }
  232. }
  233. clearDraft() {
  234. this.props.crowi.clearDraft(this.props.pagePath);
  235. }
  236. renderPreview(value) {
  237. this.setState({ markdown: value });
  238. // render html
  239. const context = {
  240. markdown: this.state.markdown,
  241. currentPagePath: decodeURIComponent(window.location.pathname),
  242. };
  243. const growiRenderer = this.growiRenderer;
  244. const interceptorManager = this.props.crowi.interceptorManager;
  245. interceptorManager.process('preRenderPreview', context)
  246. .then(() => { return interceptorManager.process('prePreProcess', context) })
  247. .then(() => {
  248. context.markdown = growiRenderer.preProcess(context.markdown);
  249. })
  250. .then(() => { return interceptorManager.process('postPreProcess', context) })
  251. .then(() => {
  252. const parsedHTML = growiRenderer.process(context.markdown);
  253. context.parsedHTML = parsedHTML;
  254. })
  255. .then(() => { return interceptorManager.process('prePostProcess', context) })
  256. .then(() => {
  257. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  258. })
  259. .then(() => { return interceptorManager.process('postPostProcess', context) })
  260. .then(() => { return interceptorManager.process('preRenderPreviewHtml', context) })
  261. .then(() => {
  262. this.setState({ html: context.parsedHTML });
  263. })
  264. // process interceptors for post rendering
  265. .then(() => { return interceptorManager.process('postRenderPreviewHtml', context) });
  266. }
  267. apiErrorHandler(error) {
  268. toastr.error(error.message, 'Error occured', {
  269. closeButton: true,
  270. progressBar: true,
  271. newestOnTop: false,
  272. showDuration: '100',
  273. hideDuration: '100',
  274. timeOut: '3000',
  275. });
  276. }
  277. render() {
  278. const config = this.props.crowi.getConfig();
  279. const noCdn = !!config.env.NO_CDN;
  280. const emojiStrategy = this.props.crowi.getEmojiStrategy();
  281. return (
  282. <div className="row">
  283. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  284. <Editor
  285. ref={(c) => { this.editor = c }}
  286. value={this.state.markdown}
  287. editorOptions={this.state.editorOptions}
  288. noCdn={noCdn}
  289. isMobile={this.props.crowi.isMobile}
  290. isUploadable={this.state.isUploadable}
  291. isUploadableFile={this.state.isUploadableFile}
  292. emojiStrategy={emojiStrategy}
  293. onScroll={this.onEditorScroll}
  294. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  295. onChange={this.onMarkdownChanged}
  296. onUpload={this.onUpload}
  297. onSave={() => {
  298. this.props.onSaveWithShortcut(this.state.markdown);
  299. }}
  300. />
  301. </div>
  302. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  303. <Preview
  304. html={this.state.html}
  305. // eslint-disable-next-line no-return-assign
  306. inputRef={(el) => { return this.previewElement = el }}
  307. isMathJaxEnabled={this.state.isMathJaxEnabled}
  308. renderMathJaxOnInit={false}
  309. previewOptions={this.state.previewOptions}
  310. onScroll={this.onPreviewScroll}
  311. />
  312. </div>
  313. </div>
  314. );
  315. }
  316. }
  317. PageEditor.propTypes = {
  318. crowi: PropTypes.object.isRequired,
  319. crowiRenderer: PropTypes.object.isRequired,
  320. onSaveWithShortcut: PropTypes.func.isRequired,
  321. markdown: PropTypes.string.isRequired,
  322. pageId: PropTypes.string,
  323. revisionId: PropTypes.string,
  324. pagePath: PropTypes.string,
  325. editorOptions: PropTypes.instanceOf(EditorOptions),
  326. previewOptions: PropTypes.instanceOf(PreviewOptions),
  327. };