PageEditor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. *
  225. * @param {*} event
  226. */
  227. onPreviewScroll(offset) {
  228. this.scrollEditorByPreviewScrollWithThrottle(offset);
  229. }
  230. scrollEditorByPreviewScroll(offset) {
  231. if (this.previewElement == null) {
  232. return;
  233. }
  234. // prevent circular invocation
  235. if (this.isOriginOfScrollSyncEditor) {
  236. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  237. return;
  238. }
  239. // turn on the flag
  240. this.isOriginOfScrollSyncPreview = true;
  241. scrollSyncHelper.scrollEditor(this.refs.editor, this.previewElement, offset);
  242. }
  243. /*
  244. * methods for draft
  245. */
  246. restoreDraft() {
  247. // restore draft when the first time to edit
  248. const draft = this.props.crowi.findDraft(this.props.pagePath);
  249. if (!this.props.revisionId && draft != null) {
  250. this.setState({markdown: draft});
  251. }
  252. }
  253. saveDraft() {
  254. // only when the first time to edit
  255. if (!this.state.revisionId) {
  256. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  257. }
  258. }
  259. clearDraft() {
  260. this.props.crowi.clearDraft(this.props.pagePath);
  261. }
  262. pageSavedHandler(page) {
  263. // update states
  264. this.setState({
  265. revisionId: page.revision._id,
  266. markdown: page.revision.body
  267. })
  268. // clear draft
  269. this.clearDraft();
  270. // dispatch onSaveSuccess event
  271. if (this.props.onSaveSuccess != null) {
  272. this.props.onSaveSuccess(page);
  273. }
  274. }
  275. apiErrorHandler(error) {
  276. console.error(error);
  277. toastr.error(error.message, 'Error occured', {
  278. closeButton: true,
  279. progressBar: true,
  280. newestOnTop: false,
  281. showDuration: "100",
  282. hideDuration: "100",
  283. timeOut: "3000",
  284. });
  285. }
  286. renderPreview(value) {
  287. const config = this.props.crowi.config;
  288. this.setState({ markdown: value });
  289. // render html
  290. var context = {
  291. markdown: this.state.markdown,
  292. dom: this.previewElement,
  293. currentPagePath: decodeURIComponent(location.pathname)
  294. };
  295. const growiRenderer = this.growiRenderer;
  296. const interceptorManager = this.props.crowi.interceptorManager;
  297. interceptorManager.process('preRenderPreview', context)
  298. .then(() => interceptorManager.process('prePreProcess', context))
  299. .then(() => {
  300. context.markdown = growiRenderer.preProcess(context.markdown);
  301. })
  302. .then(() => interceptorManager.process('postPreProcess', context))
  303. .then(() => {
  304. var parsedHTML = growiRenderer.process(context.markdown);
  305. context['parsedHTML'] = parsedHTML;
  306. })
  307. .then(() => interceptorManager.process('prePostProcess', context))
  308. .then(() => {
  309. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML, context.dom);
  310. })
  311. .then(() => interceptorManager.process('postPostProcess', context))
  312. .then(() => interceptorManager.process('preRenderPreviewHtml', context))
  313. .then(() => {
  314. this.setState({ html: context.parsedHTML });
  315. // set html to the hidden input (for submitting to save)
  316. $('#form-body').val(this.state.markdown);
  317. })
  318. // process interceptors for post rendering
  319. .then(() => interceptorManager.process('postRenderPreviewHtml', context));
  320. }
  321. render() {
  322. return (
  323. <div className="row">
  324. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  325. <Editor ref="editor" value={this.state.markdown}
  326. editorOptions={this.state.editorOptions}
  327. isUploadable={this.state.isUploadable}
  328. isUploadableFile={this.state.isUploadableFile}
  329. onScroll={this.onEditorScroll}
  330. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  331. onChange={this.onMarkdownChanged}
  332. onSave={this.onSave}
  333. onUpload={this.onUpload}
  334. />
  335. </div>
  336. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  337. <Preview html={this.state.html}
  338. inputRef={el => this.previewElement = el}
  339. isMathJaxEnabled={this.state.isMathJaxEnabled}
  340. renderMathJaxOnInit={false}
  341. previewOptions={this.state.previewOptions}
  342. onScroll={this.onPreviewScroll}
  343. />
  344. </div>
  345. </div>
  346. )
  347. }
  348. }
  349. PageEditor.propTypes = {
  350. crowi: PropTypes.object.isRequired,
  351. crowiRenderer: PropTypes.object.isRequired,
  352. markdown: PropTypes.string.isRequired,
  353. pageId: PropTypes.string,
  354. revisionId: PropTypes.string,
  355. pagePath: PropTypes.string,
  356. onSaveSuccess: PropTypes.func,
  357. editorOptions: PropTypes.instanceOf(EditorOptions),
  358. previewOptions: PropTypes.instanceOf(PreviewOptions),
  359. };