PageEditor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import * as toastr from 'toastr';
  4. import { throttle, debounce } from 'throttle-debounce';
  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.pageSavedHandler = this.pageSavedHandler.bind(this);
  39. this.apiErrorHandler = this.apiErrorHandler.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.renderWithDebounce = 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. }
  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 save event handler
  90. */
  91. onSave() {
  92. let endpoint;
  93. let data;
  94. // update
  95. if (this.state.pageId != null) {
  96. endpoint = '/pages.update';
  97. data = {
  98. page_id: this.state.pageId,
  99. revision_id: this.state.revisionId,
  100. body: this.state.markdown,
  101. };
  102. }
  103. // create
  104. else {
  105. endpoint = '/pages.create';
  106. data = {
  107. path: this.props.pagePath,
  108. body: this.state.markdown,
  109. };
  110. }
  111. this.props.crowi.apiPost(endpoint, data)
  112. .then((res) => {
  113. // show toastr
  114. toastr.success(undefined, 'Saved successfully', {
  115. closeButton: true,
  116. progressBar: true,
  117. newestOnTop: false,
  118. showDuration: '100',
  119. hideDuration: '100',
  120. timeOut: '1200',
  121. extendedTimeOut: '150',
  122. });
  123. this.pageSavedHandler(res.page);
  124. })
  125. .catch(this.apiErrorHandler);
  126. }
  127. /**
  128. * the upload event handler
  129. * @param {any} files
  130. */
  131. onUpload(file) {
  132. const endpoint = '/attachments.add';
  133. // create a FromData instance
  134. const formData = new FormData();
  135. formData.append('_csrf', this.props.crowi.csrfToken);
  136. formData.append('file', file);
  137. formData.append('path', this.props.pagePath);
  138. formData.append('page_id', this.state.pageId || 0);
  139. // post
  140. this.props.crowi.apiPost(endpoint, formData)
  141. .then((res) => {
  142. const url = res.url;
  143. const attachment = res.attachment;
  144. const fileName = attachment.originalName;
  145. let insertText = `[${fileName}](${url})`;
  146. // when image
  147. if (attachment.fileFormat.startsWith('image/')) {
  148. // modify to "![fileName](url)" syntax
  149. insertText = '!' + insertText;
  150. }
  151. this.refs.editor.insertText(insertText);
  152. // update page information if created
  153. if (res.pageCreated) {
  154. this.pageSavedHandler(res.page);
  155. }
  156. })
  157. .catch(this.apiErrorHandler)
  158. // finally
  159. .then(() => {
  160. this.refs.editor.terminateUploadingState();
  161. });
  162. }
  163. /**
  164. * the scroll event handler from codemirror
  165. * @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).
  166. * And data.line is also available that is added by Editor component
  167. * @see https://codemirror.net/doc/manual.html#events
  168. */
  169. onEditorScroll(data) {
  170. // prevent scrolling
  171. // if the elapsed time from last scroll with cursor is shorter than 40ms
  172. const now = new Date();
  173. if (now - this.lastScrolledDateWithCursor < 40) {
  174. return;
  175. }
  176. this.scrollPreviewByEditorLineWithThrottle(data.line);
  177. }
  178. /**
  179. * the scroll event handler from codemirror
  180. * @param {number} line
  181. * @see https://codemirror.net/doc/manual.html#events
  182. */
  183. onEditorScrollCursorIntoView(line) {
  184. // record date
  185. this.lastScrolledDateWithCursor = new Date();
  186. this.scrollPreviewByCursorMovingWithThrottle(line);
  187. }
  188. /**
  189. * scroll Preview element by scroll event
  190. * @param {number} line
  191. */
  192. scrollPreviewByEditorLine(line) {
  193. if (this.previewElement == null) {
  194. return;
  195. }
  196. // prevent circular invocation
  197. if (this.isOriginOfScrollSyncPreview) {
  198. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  199. return;
  200. }
  201. // turn on the flag
  202. this.isOriginOfScrollSyncEditor = true;
  203. scrollSyncHelper.scrollPreview(this.previewElement, line);
  204. }
  205. /**
  206. * scroll Preview element by cursor moving
  207. * @param {number} line
  208. */
  209. scrollPreviewByCursorMoving(line) {
  210. if (this.previewElement == null) {
  211. return;
  212. }
  213. // prevent circular invocation
  214. if (this.isOriginOfScrollSyncPreview) {
  215. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  216. return;
  217. }
  218. // turn on the flag
  219. this.isOriginOfScrollSyncEditor = true;
  220. scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
  221. }
  222. /**
  223. * the scroll event handler from Preview component
  224. * @param {number} offset
  225. */
  226. onPreviewScroll(offset) {
  227. this.scrollEditorByPreviewScrollWithThrottle(offset);
  228. }
  229. /**
  230. * scroll Editor component by scroll event of Preview component
  231. * @param {number} offset
  232. */
  233. scrollEditorByPreviewScroll(offset) {
  234. if (this.previewElement == null) {
  235. return;
  236. }
  237. // prevent circular invocation
  238. if (this.isOriginOfScrollSyncEditor) {
  239. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  240. return;
  241. }
  242. // turn on the flag
  243. this.isOriginOfScrollSyncPreview = true;
  244. scrollSyncHelper.scrollEditor(this.refs.editor, this.previewElement, offset);
  245. }
  246. saveDraft() {
  247. // only when the first time to edit
  248. if (!this.state.revisionId) {
  249. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  250. }
  251. }
  252. clearDraft() {
  253. this.props.crowi.clearDraft(this.props.pagePath);
  254. }
  255. pageSavedHandler(page) {
  256. // update states
  257. this.setState({
  258. pageId: page.id,
  259. revisionId: page.revision._id,
  260. markdown: page.revision.body
  261. });
  262. // clear draft
  263. this.clearDraft();
  264. // dispatch onSaveSuccess event
  265. if (this.props.onSaveSuccess != null) {
  266. this.props.onSaveSuccess(page);
  267. }
  268. }
  269. apiErrorHandler(error) {
  270. toastr.error(error.message, 'Error occured', {
  271. closeButton: true,
  272. progressBar: true,
  273. newestOnTop: false,
  274. showDuration: '100',
  275. hideDuration: '100',
  276. timeOut: '3000',
  277. });
  278. }
  279. renderPreview(value) {
  280. this.setState({ markdown: value });
  281. // render html
  282. const context = {
  283. markdown: this.state.markdown,
  284. dom: this.previewElement,
  285. currentPagePath: decodeURIComponent(location.pathname)
  286. };
  287. const growiRenderer = this.growiRenderer;
  288. const interceptorManager = this.props.crowi.interceptorManager;
  289. interceptorManager.process('preRenderPreview', context)
  290. .then(() => interceptorManager.process('prePreProcess', context))
  291. .then(() => {
  292. context.markdown = growiRenderer.preProcess(context.markdown);
  293. })
  294. .then(() => interceptorManager.process('postPreProcess', context))
  295. .then(() => {
  296. const parsedHTML = growiRenderer.process(context.markdown);
  297. context['parsedHTML'] = parsedHTML;
  298. })
  299. .then(() => interceptorManager.process('prePostProcess', context))
  300. .then(() => {
  301. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML, context.dom);
  302. })
  303. .then(() => interceptorManager.process('postPostProcess', context))
  304. .then(() => interceptorManager.process('preRenderPreviewHtml', context))
  305. .then(() => {
  306. this.setState({ html: context.parsedHTML });
  307. // set html to the hidden input (for submitting to save)
  308. $('#form-body').val(this.state.markdown);
  309. })
  310. // process interceptors for post rendering
  311. .then(() => interceptorManager.process('postRenderPreviewHtml', context));
  312. }
  313. render() {
  314. const emojiStrategy = this.props.crowi.getEmojiStrategy();
  315. return (
  316. <div className="row">
  317. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  318. <Editor ref="editor" value={this.state.markdown}
  319. editorOptions={this.state.editorOptions}
  320. isMobile={this.props.crowi.isMobile}
  321. isUploadable={this.state.isUploadable}
  322. isUploadableFile={this.state.isUploadableFile}
  323. emojiStrategy={emojiStrategy}
  324. onScroll={this.onEditorScroll}
  325. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  326. onChange={this.onMarkdownChanged}
  327. onSave={this.onSave}
  328. onUpload={this.onUpload}
  329. />
  330. </div>
  331. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  332. <Preview html={this.state.html}
  333. inputRef={el => this.previewElement = el}
  334. isMathJaxEnabled={this.state.isMathJaxEnabled}
  335. renderMathJaxOnInit={false}
  336. previewOptions={this.state.previewOptions}
  337. onScroll={this.onPreviewScroll}
  338. />
  339. </div>
  340. </div>
  341. );
  342. }
  343. }
  344. PageEditor.propTypes = {
  345. crowi: PropTypes.object.isRequired,
  346. crowiRenderer: PropTypes.object.isRequired,
  347. markdown: PropTypes.string.isRequired,
  348. pageId: PropTypes.string,
  349. revisionId: PropTypes.string,
  350. pagePath: PropTypes.string,
  351. onSaveSuccess: PropTypes.func,
  352. editorOptions: PropTypes.instanceOf(EditorOptions),
  353. previewOptions: PropTypes.instanceOf(PreviewOptions),
  354. };