PageEditor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. revisionId: this.props.revisionId,
  19. markdown: this.props.markdown,
  20. isUploadable,
  21. isUploadableFile,
  22. isMathJaxEnabled,
  23. editorOptions: this.props.editorOptions,
  24. previewOptions: this.props.previewOptions,
  25. };
  26. this.growiRenderer = new GrowiRenderer(this.props.crowi, this.props.crowiRenderer, {mode: 'editor'});
  27. this.setCaretLine = this.setCaretLine.bind(this);
  28. this.focusToEditor = this.focusToEditor.bind(this);
  29. this.onMarkdownChanged = this.onMarkdownChanged.bind(this);
  30. this.onSave = this.onSave.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.pageSavedHandler = this.pageSavedHandler.bind(this);
  38. this.apiErrorHandler = this.apiErrorHandler.bind(this);
  39. // for scrolling
  40. this.lastScrolledDateWithCursor = null;
  41. this.isOriginOfScrollSyncEditor = false;
  42. this.isOriginOfScrollSyncEditor = false;
  43. // create throttled function
  44. this.scrollPreviewByEditorLineWithThrottle = throttle(20, this.scrollPreviewByEditorLine);
  45. this.scrollPreviewByCursorMovingWithThrottle = throttle(20, this.scrollPreviewByCursorMoving);
  46. this.scrollEditorByPreviewScrollWithThrottle = throttle(20, this.scrollEditorByPreviewScroll);
  47. this.renderWithDebounce = debounce(50, throttle(100, this.renderPreview));
  48. this.saveDraftWithDebounce = debounce(800, this.saveDraft);
  49. }
  50. componentWillMount() {
  51. // initial rendering
  52. this.renderPreview(this.state.markdown);
  53. }
  54. focusToEditor() {
  55. this.refs.editor.forceToFocus();
  56. }
  57. /**
  58. * set caret position of editor
  59. * @param {number} line
  60. */
  61. setCaretLine(line) {
  62. this.refs.editor.setCaretLine(line);
  63. scrollSyncHelper.scrollPreview(this.previewElement, line);
  64. }
  65. /**
  66. * set options (used from the outside)
  67. * @param {object} editorOptions
  68. */
  69. setEditorOptions(editorOptions) {
  70. this.setState({ editorOptions });
  71. }
  72. /**
  73. * set options (used from the outside)
  74. * @param {object} previewOptions
  75. */
  76. setPreviewOptions(previewOptions) {
  77. this.setState({ previewOptions });
  78. }
  79. /**
  80. * the change event handler for `markdown` state
  81. * @param {string} value
  82. */
  83. onMarkdownChanged(value) {
  84. this.renderWithDebounce(value);
  85. this.saveDraftWithDebounce()
  86. }
  87. /**
  88. * the save event handler
  89. */
  90. onSave() {
  91. let endpoint;
  92. let data;
  93. // update
  94. if (this.props.pageId != null) {
  95. endpoint = '/pages.update';
  96. data = {
  97. page_id: this.props.pageId,
  98. revision_id: this.state.revisionId,
  99. body: this.state.markdown,
  100. };
  101. }
  102. // create
  103. else {
  104. endpoint = '/pages.create';
  105. data = {
  106. path: this.props.pagePath,
  107. body: this.state.markdown,
  108. };
  109. }
  110. this.props.crowi.apiPost(endpoint, data)
  111. .then((res) => {
  112. // show toastr
  113. toastr.success(undefined, 'Saved successfully', {
  114. closeButton: true,
  115. progressBar: true,
  116. newestOnTop: false,
  117. showDuration: "100",
  118. hideDuration: "100",
  119. timeOut: "1200",
  120. extendedTimeOut: "150",
  121. });
  122. this.pageSavedHandler(res.page);
  123. })
  124. .catch(this.apiErrorHandler)
  125. }
  126. /**
  127. * the upload event handler
  128. * @param {any} files
  129. */
  130. onUpload(file) {
  131. const endpoint = '/attachments.add';
  132. // create a FromData instance
  133. const formData = new FormData();
  134. formData.append('_csrf', this.props.crowi.csrfToken);
  135. formData.append('file', file);
  136. formData.append('path', this.props.pagePath);
  137. formData.append('page_id', this.props.pageId || 0);
  138. // post
  139. this.props.crowi.apiPost(endpoint, formData)
  140. .then((res) => {
  141. const url = res.url;
  142. const attachment = res.attachment;
  143. const fileName = attachment.originalName;
  144. let insertText = `[${fileName}](${url})`;
  145. // when image
  146. if (attachment.fileFormat.startsWith('image/')) {
  147. // modify to "![fileName](url)" syntax
  148. insertText = '!' + insertText;
  149. }
  150. this.refs.editor.insertText(insertText);
  151. // update page information if created
  152. if (res.pageCreated) {
  153. this.pageSavedHandler(res.page);
  154. }
  155. })
  156. .catch(this.apiErrorHandler)
  157. // finally
  158. .then(() => {
  159. this.refs.editor.terminateUploadingState();
  160. });
  161. }
  162. /**
  163. * the scroll event handler from codemirror
  164. * @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).
  165. * And data.line is also available that is added by Editor component
  166. * @see https://codemirror.net/doc/manual.html#events
  167. */
  168. onEditorScroll(data) {
  169. // prevent scrolling
  170. // if the elapsed time from last scroll with cursor is shorter than 40ms
  171. const now = new Date();
  172. if (now - this.lastScrolledDateWithCursor < 40) {
  173. return;
  174. }
  175. this.scrollPreviewByEditorLineWithThrottle(data.line);
  176. }
  177. /**
  178. * the scroll event handler from codemirror
  179. * @param {number} line
  180. * @see https://codemirror.net/doc/manual.html#events
  181. */
  182. onEditorScrollCursorIntoView(line) {
  183. // record date
  184. this.lastScrolledDateWithCursor = new Date();
  185. this.scrollPreviewByCursorMovingWithThrottle(line);
  186. }
  187. /**
  188. * scroll Preview element by scroll event
  189. * @param {number} line
  190. */
  191. scrollPreviewByEditorLine(line) {
  192. if (this.previewElement == null) {
  193. return;
  194. }
  195. // prevent circular invocation
  196. if (this.isOriginOfScrollSyncPreview) {
  197. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  198. return;
  199. }
  200. // turn on the flag
  201. this.isOriginOfScrollSyncEditor = true;
  202. scrollSyncHelper.scrollPreview(this.previewElement, line);
  203. };
  204. /**
  205. * scroll Preview element by cursor moving
  206. * @param {number} line
  207. */
  208. scrollPreviewByCursorMoving(line) {
  209. if (this.previewElement == null) {
  210. return;
  211. }
  212. // prevent circular invocation
  213. if (this.isOriginOfScrollSyncPreview) {
  214. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  215. return;
  216. }
  217. // turn on the flag
  218. this.isOriginOfScrollSyncEditor = true;
  219. scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
  220. };
  221. /**
  222. * the scroll event handler from Preview component
  223. * @param {number} offset
  224. */
  225. onPreviewScroll(offset) {
  226. this.scrollEditorByPreviewScrollWithThrottle(offset);
  227. }
  228. /**
  229. * scroll Editor component by scroll event of Preview component
  230. * @param {number} offset
  231. */
  232. scrollEditorByPreviewScroll(offset) {
  233. if (this.previewElement == null) {
  234. return;
  235. }
  236. // prevent circular invocation
  237. if (this.isOriginOfScrollSyncEditor) {
  238. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  239. return;
  240. }
  241. // turn on the flag
  242. this.isOriginOfScrollSyncPreview = true;
  243. scrollSyncHelper.scrollEditor(this.refs.editor, this.previewElement, offset);
  244. }
  245. saveDraft() {
  246. // only when the first time to edit
  247. if (!this.state.revisionId) {
  248. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  249. }
  250. }
  251. clearDraft() {
  252. this.props.crowi.clearDraft(this.props.pagePath);
  253. }
  254. pageSavedHandler(page) {
  255. // update states
  256. this.setState({
  257. revisionId: page.revision._id,
  258. markdown: page.revision.body
  259. })
  260. // clear draft
  261. this.clearDraft();
  262. // dispatch onSaveSuccess event
  263. if (this.props.onSaveSuccess != null) {
  264. this.props.onSaveSuccess(page);
  265. }
  266. }
  267. apiErrorHandler(error) {
  268. console.error(error);
  269. toastr.error(error.message, 'Error occured', {
  270. closeButton: true,
  271. progressBar: true,
  272. newestOnTop: false,
  273. showDuration: "100",
  274. hideDuration: "100",
  275. timeOut: "3000",
  276. });
  277. }
  278. renderPreview(value) {
  279. const config = this.props.crowi.config;
  280. this.setState({ markdown: value });
  281. // render html
  282. var 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. var 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. return (
  315. <div className="row">
  316. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  317. <Editor ref="editor" value={this.state.markdown}
  318. editorOptions={this.state.editorOptions}
  319. isUploadable={this.state.isUploadable}
  320. isUploadableFile={this.state.isUploadableFile}
  321. onScroll={this.onEditorScroll}
  322. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  323. onChange={this.onMarkdownChanged}
  324. onSave={this.onSave}
  325. onUpload={this.onUpload}
  326. />
  327. </div>
  328. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  329. <Preview html={this.state.html}
  330. inputRef={el => this.previewElement = el}
  331. isMathJaxEnabled={this.state.isMathJaxEnabled}
  332. renderMathJaxOnInit={false}
  333. previewOptions={this.state.previewOptions}
  334. onScroll={this.onPreviewScroll}
  335. />
  336. </div>
  337. </div>
  338. )
  339. }
  340. }
  341. PageEditor.propTypes = {
  342. crowi: PropTypes.object.isRequired,
  343. crowiRenderer: PropTypes.object.isRequired,
  344. markdown: PropTypes.string.isRequired,
  345. pageId: PropTypes.string,
  346. revisionId: PropTypes.string,
  347. pagePath: PropTypes.string,
  348. onSaveSuccess: PropTypes.func,
  349. editorOptions: PropTypes.instanceOf(EditorOptions),
  350. previewOptions: PropTypes.instanceOf(PreviewOptions),
  351. };