PageEditor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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} file
  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. throw new Error(res.errorMessage);
  104. }
  105. const formData = new FormData();
  106. formData.append('_csrf', this.props.crowi.csrfToken);
  107. formData.append('file', file);
  108. formData.append('path', this.props.pagePath);
  109. formData.append('page_id', this.state.pageId || 0);
  110. res = await this.props.crowi.apiPost('/attachments.add', formData);
  111. const attachment = res.attachment;
  112. const fileName = attachment.originalName;
  113. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  114. // when image
  115. if (attachment.fileFormat.startsWith('image/')) {
  116. // modify to "![fileName](url)" syntax
  117. insertText = `!${insertText}`;
  118. }
  119. this.editor.insertText(insertText);
  120. // when if created newly
  121. if (res.pageCreated) {
  122. // do nothing
  123. }
  124. }
  125. catch (e) {
  126. this.apiErrorHandler(e);
  127. }
  128. finally {
  129. this.editor.terminateUploadingState();
  130. }
  131. }
  132. /**
  133. * the scroll event handler from codemirror
  134. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  135. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  136. * And data.line is also available that is added by Editor component
  137. * @see https://codemirror.net/doc/manual.html#events
  138. */
  139. onEditorScroll(data) {
  140. // prevent scrolling
  141. // if the elapsed time from last scroll with cursor is shorter than 40ms
  142. const now = new Date();
  143. if (now - this.lastScrolledDateWithCursor < 40) {
  144. return;
  145. }
  146. this.scrollPreviewByEditorLineWithThrottle(data.line);
  147. }
  148. /**
  149. * the scroll event handler from codemirror
  150. * @param {number} line
  151. * @see https://codemirror.net/doc/manual.html#events
  152. */
  153. onEditorScrollCursorIntoView(line) {
  154. // record date
  155. this.lastScrolledDateWithCursor = new Date();
  156. this.scrollPreviewByCursorMovingWithThrottle(line);
  157. }
  158. /**
  159. * scroll Preview element by scroll event
  160. * @param {number} line
  161. */
  162. scrollPreviewByEditorLine(line) {
  163. if (this.previewElement == null) {
  164. return;
  165. }
  166. // prevent circular invocation
  167. if (this.isOriginOfScrollSyncPreview) {
  168. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  169. return;
  170. }
  171. // turn on the flag
  172. this.isOriginOfScrollSyncEditor = true;
  173. scrollSyncHelper.scrollPreview(this.previewElement, line);
  174. }
  175. /**
  176. * scroll Preview element by cursor moving
  177. * @param {number} line
  178. */
  179. scrollPreviewByCursorMoving(line) {
  180. if (this.previewElement == null) {
  181. return;
  182. }
  183. // prevent circular invocation
  184. if (this.isOriginOfScrollSyncPreview) {
  185. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  186. return;
  187. }
  188. // turn on the flag
  189. this.isOriginOfScrollSyncEditor = true;
  190. scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
  191. }
  192. /**
  193. * the scroll event handler from Preview component
  194. * @param {number} offset
  195. */
  196. onPreviewScroll(offset) {
  197. this.scrollEditorByPreviewScrollWithThrottle(offset);
  198. }
  199. /**
  200. * scroll Editor component by scroll event of Preview component
  201. * @param {number} offset
  202. */
  203. scrollEditorByPreviewScroll(offset) {
  204. if (this.previewElement == null) {
  205. return;
  206. }
  207. // prevent circular invocation
  208. if (this.isOriginOfScrollSyncEditor) {
  209. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  210. return;
  211. }
  212. // turn on the flag
  213. this.isOriginOfScrollSyncPreview = true;
  214. scrollSyncHelper.scrollEditor(this.editor, this.previewElement, offset);
  215. }
  216. saveDraft() {
  217. // only when the first time to edit
  218. if (!this.state.revisionId) {
  219. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  220. }
  221. }
  222. clearDraft() {
  223. this.props.crowi.clearDraft(this.props.pagePath);
  224. }
  225. renderPreview(value) {
  226. this.setState({ markdown: value });
  227. // render html
  228. const context = {
  229. markdown: this.state.markdown,
  230. currentPagePath: decodeURIComponent(window.location.pathname),
  231. };
  232. const growiRenderer = this.growiRenderer;
  233. const interceptorManager = this.props.crowi.interceptorManager;
  234. interceptorManager.process('preRenderPreview', context)
  235. .then(() => { return interceptorManager.process('prePreProcess', context) })
  236. .then(() => {
  237. context.markdown = growiRenderer.preProcess(context.markdown);
  238. })
  239. .then(() => { return interceptorManager.process('postPreProcess', context) })
  240. .then(() => {
  241. const parsedHTML = growiRenderer.process(context.markdown);
  242. context.parsedHTML = parsedHTML;
  243. })
  244. .then(() => { return interceptorManager.process('prePostProcess', context) })
  245. .then(() => {
  246. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  247. })
  248. .then(() => { return interceptorManager.process('postPostProcess', context) })
  249. .then(() => { return interceptorManager.process('preRenderPreviewHtml', context) })
  250. .then(() => {
  251. this.setState({ html: context.parsedHTML });
  252. })
  253. // process interceptors for post rendering
  254. .then(() => { return interceptorManager.process('postRenderPreviewHtml', context) });
  255. }
  256. apiErrorHandler(error) {
  257. toastr.error(error.message, 'Error occured', {
  258. closeButton: true,
  259. progressBar: true,
  260. newestOnTop: false,
  261. showDuration: '100',
  262. hideDuration: '100',
  263. timeOut: '3000',
  264. });
  265. }
  266. render() {
  267. const config = this.props.crowi.getConfig();
  268. const noCdn = !!config.env.NO_CDN;
  269. const emojiStrategy = this.props.crowi.getEmojiStrategy();
  270. return (
  271. <div className="row">
  272. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  273. <Editor
  274. ref={(c) => { this.editor = c }}
  275. value={this.state.markdown}
  276. editorOptions={this.state.editorOptions}
  277. noCdn={noCdn}
  278. isMobile={this.props.crowi.isMobile}
  279. isUploadable={this.state.isUploadable}
  280. isUploadableFile={this.state.isUploadableFile}
  281. emojiStrategy={emojiStrategy}
  282. onScroll={this.onEditorScroll}
  283. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  284. onChange={this.onMarkdownChanged}
  285. onUpload={this.onUpload}
  286. onSave={() => {
  287. this.props.onSaveWithShortcut(this.state.markdown);
  288. }}
  289. />
  290. </div>
  291. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  292. <Preview
  293. html={this.state.html}
  294. // eslint-disable-next-line no-return-assign
  295. inputRef={(el) => { return this.previewElement = el }}
  296. isMathJaxEnabled={this.state.isMathJaxEnabled}
  297. renderMathJaxOnInit={false}
  298. previewOptions={this.state.previewOptions}
  299. onScroll={this.onPreviewScroll}
  300. />
  301. </div>
  302. </div>
  303. );
  304. }
  305. }
  306. PageEditor.propTypes = {
  307. crowi: PropTypes.object.isRequired,
  308. crowiRenderer: PropTypes.object.isRequired,
  309. onSaveWithShortcut: PropTypes.func.isRequired,
  310. markdown: PropTypes.string.isRequired,
  311. pageId: PropTypes.string,
  312. revisionId: PropTypes.string,
  313. pagePath: PropTypes.string,
  314. editorOptions: PropTypes.instanceOf(EditorOptions),
  315. previewOptions: PropTypes.instanceOf(PreviewOptions),
  316. };