PageEditor.js 12 KB

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