PageEditor.js 12 KB

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