PageEditor.js 12 KB

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