PageEditor.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. export default class PageEditor extends React.Component {
  10. constructor(props) {
  11. super(props);
  12. const config = this.props.crowi.getConfig();
  13. const isUploadable = config.upload.image || config.upload.file;
  14. const isUploadableFile = config.upload.file;
  15. const isMathJaxEnabled = !!config.env.MATHJAX;
  16. this.state = {
  17. revisionId: this.props.revisionId,
  18. markdown: this.props.markdown,
  19. isUploadable,
  20. isUploadableFile,
  21. isMathJaxEnabled,
  22. editorOptions: this.props.editorOptions,
  23. previewOptions: this.props.previewOptions,
  24. };
  25. this.growiRenderer = new GrowiRenderer(this.props.crowi, this.props.crowiRenderer, {mode: 'editor'});
  26. this.setCaretLine = this.setCaretLine.bind(this);
  27. this.focusToEditor = this.focusToEditor.bind(this);
  28. this.onMarkdownChanged = this.onMarkdownChanged.bind(this);
  29. this.onSave = this.onSave.bind(this);
  30. this.onUpload = this.onUpload.bind(this);
  31. this.onEditorScroll = this.onEditorScroll.bind(this);
  32. this.getMaxScrollTop = this.getMaxScrollTop.bind(this);
  33. this.getScrollTop = this.getScrollTop.bind(this);
  34. this.saveDraft = this.saveDraft.bind(this);
  35. this.clearDraft = this.clearDraft.bind(this);
  36. this.pageSavedHandler = this.pageSavedHandler.bind(this);
  37. this.apiErrorHandler = this.apiErrorHandler.bind(this);
  38. // create throttled function
  39. this.renderWithDebounce = debounce(50, throttle(100, this.renderPreview));
  40. this.saveDraftWithDebounce = debounce(300, this.saveDraft);
  41. }
  42. componentWillMount() {
  43. // restore draft
  44. this.restoreDraft();
  45. // initial rendering
  46. this.renderPreview(this.state.markdown);
  47. }
  48. focusToEditor() {
  49. this.refs.editor.forceToFocus();
  50. }
  51. /**
  52. * set caret position of editor
  53. * @param {number} line
  54. */
  55. setCaretLine(line) {
  56. this.refs.editor.setCaretLine(line);
  57. }
  58. /**
  59. * set options (used from the outside)
  60. * @param {object} editorOptions
  61. */
  62. setEditorOptions(editorOptions) {
  63. this.setState({ editorOptions });
  64. }
  65. /**
  66. * set options (used from the outside)
  67. * @param {object} previewOptions
  68. */
  69. setPreviewOptions(previewOptions) {
  70. this.setState({ previewOptions });
  71. }
  72. /**
  73. * the change event handler for `markdown` state
  74. * @param {string} value
  75. */
  76. onMarkdownChanged(value) {
  77. this.renderWithDebounce(value);
  78. this.saveDraftWithDebounce()
  79. }
  80. /**
  81. * the save event handler
  82. */
  83. onSave() {
  84. let endpoint;
  85. let data;
  86. // update
  87. if (this.props.pageId != null) {
  88. endpoint = '/pages.update';
  89. data = {
  90. page_id: this.props.pageId,
  91. revision_id: this.state.revisionId,
  92. body: this.state.markdown,
  93. };
  94. }
  95. // create
  96. else {
  97. endpoint = '/pages.create';
  98. data = {
  99. path: this.props.pagePath,
  100. body: this.state.markdown,
  101. };
  102. }
  103. this.props.crowi.apiPost(endpoint, data)
  104. .then((res) => {
  105. // show toastr
  106. toastr.success(undefined, 'Saved successfully', {
  107. closeButton: true,
  108. progressBar: true,
  109. newestOnTop: false,
  110. showDuration: "100",
  111. hideDuration: "100",
  112. timeOut: "1200",
  113. extendedTimeOut: "150",
  114. });
  115. this.pageSavedHandler(res.page);
  116. })
  117. .catch(this.apiErrorHandler)
  118. }
  119. /**
  120. * the upload event handler
  121. * @param {any} files
  122. */
  123. onUpload(file) {
  124. const endpoint = '/attachments.add';
  125. // create a FromData instance
  126. const formData = new FormData();
  127. formData.append('_csrf', this.props.crowi.csrfToken);
  128. formData.append('file', file);
  129. formData.append('path', this.props.pagePath);
  130. formData.append('page_id', this.props.pageId || 0);
  131. // post
  132. this.props.crowi.apiPost(endpoint, formData)
  133. .then((res) => {
  134. const url = res.url;
  135. const attachment = res.attachment;
  136. const fileName = attachment.originalName;
  137. let insertText = `[${fileName}](${url})`;
  138. // when image
  139. if (attachment.fileFormat.startsWith('image/')) {
  140. // modify to "![fileName](url)" syntax
  141. insertText = '!' + insertText;
  142. }
  143. this.refs.editor.insertText(insertText);
  144. // update page information if created
  145. if (res.pageCreated) {
  146. this.pageSavedHandler(res.page);
  147. }
  148. })
  149. .catch(this.apiErrorHandler)
  150. // finally
  151. .then(() => {
  152. this.refs.editor.terminateUploadingState();
  153. });
  154. }
  155. /**
  156. * the scroll event handler from codemirror
  157. * @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).
  158. * see https://codemirror.net/doc/manual.html#events
  159. */
  160. onEditorScroll(data) {
  161. const rate = data.top / (data.height - data.clientHeight)
  162. const top = this.getScrollTop(this.previewElement, rate);
  163. this.previewElement.scrollTop = top;
  164. }
  165. /**
  166. * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
  167. * @param {*} dom
  168. */
  169. getMaxScrollTop(dom) {
  170. var rect = dom.getBoundingClientRect();
  171. return dom.scrollHeight - rect.height;
  172. };
  173. /**
  174. * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
  175. * @param {*} dom
  176. */
  177. getScrollTop(dom, rate) {
  178. var maxScrollTop = this.getMaxScrollTop(dom);
  179. var top = maxScrollTop * rate;
  180. return top;
  181. };
  182. /*
  183. * methods for draft
  184. */
  185. restoreDraft() {
  186. // restore draft when the first time to edit
  187. const draft = this.props.crowi.findDraft(this.props.pagePath);
  188. if (!this.props.revisionId && draft != null) {
  189. this.setState({markdown: draft});
  190. }
  191. }
  192. saveDraft() {
  193. // only when the first time to edit
  194. if (!this.state.revisionId) {
  195. this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
  196. }
  197. }
  198. clearDraft() {
  199. this.props.crowi.clearDraft(this.props.pagePath);
  200. }
  201. pageSavedHandler(page) {
  202. // update states
  203. this.setState({
  204. revisionId: page.revision._id,
  205. markdown: page.revision.body
  206. })
  207. // clear draft
  208. this.clearDraft();
  209. // dispatch onSaveSuccess event
  210. if (this.props.onSaveSuccess != null) {
  211. this.props.onSaveSuccess(page);
  212. }
  213. }
  214. apiErrorHandler(error) {
  215. console.error(error);
  216. toastr.error(error.message, 'Error occured', {
  217. closeButton: true,
  218. progressBar: true,
  219. newestOnTop: false,
  220. showDuration: "100",
  221. hideDuration: "100",
  222. timeOut: "3000",
  223. });
  224. }
  225. renderPreview(value) {
  226. const config = this.props.crowi.config;
  227. this.setState({ markdown: value });
  228. // render html
  229. var context = {
  230. markdown: this.state.markdown,
  231. dom: this.previewElement,
  232. currentPagePath: decodeURIComponent(location.pathname)
  233. };
  234. const growiRenderer = this.growiRenderer;
  235. const interceptorManager = this.props.crowi.interceptorManager;
  236. interceptorManager.process('preRenderPreview', context)
  237. .then(() => interceptorManager.process('prePreProcess', context))
  238. .then(() => {
  239. context.markdown = growiRenderer.preProcess(context.markdown);
  240. })
  241. .then(() => interceptorManager.process('postPreProcess', context))
  242. .then(() => {
  243. var parsedHTML = growiRenderer.process(context.markdown);
  244. context['parsedHTML'] = parsedHTML;
  245. })
  246. .then(() => interceptorManager.process('prePostProcess', context))
  247. .then(() => {
  248. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML, context.dom);
  249. })
  250. .then(() => interceptorManager.process('postPostProcess', context))
  251. .then(() => interceptorManager.process('preRenderPreviewHtml', context))
  252. .then(() => {
  253. this.setState({ html: context.parsedHTML });
  254. // set html to the hidden input (for submitting to save)
  255. $('#form-body').val(this.state.markdown);
  256. })
  257. // process interceptors for post rendering
  258. .then(() => interceptorManager.process('postRenderPreviewHtml', context));
  259. }
  260. render() {
  261. return (
  262. <div className="row">
  263. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  264. <Editor ref="editor" value={this.state.markdown}
  265. editorOptions={this.state.editorOptions}
  266. isUploadable={this.state.isUploadable}
  267. isUploadableFile={this.state.isUploadableFile}
  268. onScroll={this.onEditorScroll}
  269. onChange={this.onMarkdownChanged}
  270. onSave={this.onSave}
  271. onUpload={this.onUpload}
  272. />
  273. </div>
  274. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  275. <Preview html={this.state.html}
  276. inputRef={el => this.previewElement = el}
  277. isMathJaxEnabled={this.state.isMathJaxEnabled}
  278. renderMathJaxOnInit={false}
  279. previewOptions={this.state.previewOptions}
  280. />
  281. </div>
  282. </div>
  283. )
  284. }
  285. }
  286. PageEditor.propTypes = {
  287. crowi: PropTypes.object.isRequired,
  288. crowiRenderer: PropTypes.object.isRequired,
  289. markdown: PropTypes.string.isRequired,
  290. pageId: PropTypes.string,
  291. revisionId: PropTypes.string,
  292. pagePath: PropTypes.string,
  293. onSaveSuccess: PropTypes.func,
  294. editorOptions: PropTypes.instanceOf(EditorOptions),
  295. previewOptions: PropTypes.instanceOf(PreviewOptions),
  296. };