PageEditor.js 12 KB

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