Editor.jsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import Dropzone from 'react-dropzone';
  4. import {
  5. Modal, ModalHeader, ModalBody,
  6. } from 'reactstrap';
  7. import { useDefaultIndentSize } from '~/stores/context';
  8. import { useEditorSettings } from '~/stores/editor';
  9. import AbstractEditor from './AbstractEditor';
  10. import Cheatsheet from './Cheatsheet';
  11. import CodeMirrorEditor from './CodeMirrorEditor';
  12. import pasteHelper from './PasteHelper';
  13. import TextAreaEditor from './TextAreaEditor';
  14. class Editor extends AbstractEditor {
  15. constructor(props) {
  16. super(props);
  17. this.state = {
  18. isComponentDidMount: false,
  19. dropzoneActive: false,
  20. isUploading: false,
  21. isCheatsheetModalShown: false,
  22. };
  23. this.getEditorSubstance = this.getEditorSubstance.bind(this);
  24. this.pasteFilesHandler = this.pasteFilesHandler.bind(this);
  25. this.dragEnterHandler = this.dragEnterHandler.bind(this);
  26. this.dragLeaveHandler = this.dragLeaveHandler.bind(this);
  27. this.dropHandler = this.dropHandler.bind(this);
  28. this.showMarkdownHelp = this.showMarkdownHelp.bind(this);
  29. this.addAttachmentHandler = this.addAttachmentHandler.bind(this);
  30. this.getAcceptableType = this.getAcceptableType.bind(this);
  31. this.getDropzoneClassName = this.getDropzoneClassName.bind(this);
  32. this.renderDropzoneOverlay = this.renderDropzoneOverlay.bind(this);
  33. }
  34. componentDidMount() {
  35. this.setState({ isComponentDidMount: true });
  36. }
  37. getEditorSubstance() {
  38. return this.props.isMobile
  39. ? this.taEditor
  40. : this.cmEditor;
  41. }
  42. /**
  43. * @inheritDoc
  44. */
  45. forceToFocus() {
  46. this.getEditorSubstance().forceToFocus();
  47. }
  48. /**
  49. * @inheritDoc
  50. */
  51. setValue(newValue) {
  52. this.getEditorSubstance().setValue(newValue);
  53. }
  54. /**
  55. * @inheritDoc
  56. */
  57. setGfmMode(bool) {
  58. this.getEditorSubstance().setGfmMode(bool);
  59. }
  60. /**
  61. * @inheritDoc
  62. */
  63. setCaretLine(line) {
  64. this.getEditorSubstance().setCaretLine(line);
  65. }
  66. /**
  67. * @inheritDoc
  68. */
  69. setScrollTopByLine(line) {
  70. this.getEditorSubstance().setScrollTopByLine(line);
  71. }
  72. /**
  73. * @inheritDoc
  74. */
  75. insertText(text) {
  76. this.getEditorSubstance().insertText(text);
  77. }
  78. /**
  79. * remove overlay and set isUploading to false
  80. */
  81. terminateUploadingState() {
  82. this.setState({
  83. dropzoneActive: false,
  84. isUploading: false,
  85. });
  86. }
  87. /**
  88. * dispatch onUpload event
  89. */
  90. dispatchUpload(files) {
  91. if (this.props.onUpload != null) {
  92. this.props.onUpload(files);
  93. }
  94. }
  95. /**
  96. * get acceptable(uploadable) file type
  97. */
  98. getAcceptableType() {
  99. let accept = 'null'; // reject all
  100. if (this.props.isUploadable) {
  101. if (!this.props.isUploadableFile) {
  102. accept = 'image/*'; // image only
  103. }
  104. else {
  105. accept = ''; // allow all
  106. }
  107. }
  108. return accept;
  109. }
  110. pasteFilesHandler(event) {
  111. const items = event.clipboardData.items || event.clipboardData.files || [];
  112. // abort if length is not 1
  113. if (items.length < 1) {
  114. return;
  115. }
  116. for (let i = 0; i < items.length; i++) {
  117. try {
  118. const file = items[i].getAsFile();
  119. // check file type (the same process as Dropzone)
  120. if (file != null && pasteHelper.isAcceptableType(file, this.getAcceptableType())) {
  121. this.dispatchUpload(file);
  122. this.setState({ isUploading: true });
  123. }
  124. }
  125. catch (e) {
  126. this.logger.error(e);
  127. }
  128. }
  129. }
  130. dragEnterHandler(event) {
  131. const dataTransfer = event.dataTransfer;
  132. // do nothing if contents is not files
  133. if (!dataTransfer.types.includes('Files')) {
  134. return;
  135. }
  136. this.setState({ dropzoneActive: true });
  137. }
  138. dragLeaveHandler() {
  139. this.setState({ dropzoneActive: false });
  140. }
  141. dropHandler(accepted, rejected) {
  142. // rejected
  143. if (accepted.length !== 1) { // length should be 0 or 1 because `multiple={false}` is set
  144. this.setState({ dropzoneActive: false });
  145. return;
  146. }
  147. const file = accepted[0];
  148. this.dispatchUpload(file);
  149. this.setState({ isUploading: true });
  150. }
  151. showMarkdownHelp() {
  152. this.setState({ isCheatsheetModalShown: true });
  153. }
  154. addAttachmentHandler() {
  155. this.dropzone.open();
  156. }
  157. getDropzoneClassName(isDragAccept, isDragReject) {
  158. let className = 'dropzone';
  159. if (!this.props.isUploadable) {
  160. className += ' dropzone-unuploadable';
  161. }
  162. else {
  163. className += ' dropzone-uploadable';
  164. if (this.props.isUploadableFile) {
  165. className += ' dropzone-uploadablefile';
  166. }
  167. }
  168. // uploading
  169. if (this.state.isUploading) {
  170. className += ' dropzone-uploading';
  171. }
  172. if (isDragAccept) {
  173. className += ' dropzone-accepted';
  174. }
  175. if (isDragReject) {
  176. className += ' dropzone-rejected';
  177. }
  178. return className;
  179. }
  180. renderDropzoneOverlay() {
  181. return (
  182. <div className="overlay overlay-dropzone-active">
  183. {this.state.isUploading
  184. && (
  185. <span className="overlay-content">
  186. <div className="speeding-wheel d-inline-block"></div>
  187. <span className="sr-only">Uploading...</span>
  188. </span>
  189. )
  190. }
  191. {!this.state.isUploading && <span className="overlay-content"></span>}
  192. </div>
  193. );
  194. }
  195. renderNavbar() {
  196. return (
  197. <div className="m-0 navbar navbar-default navbar-editor" style={{ minHeight: 'unset' }}>
  198. <ul className="pl-2 nav nav-navbar">
  199. { this.getNavbarItems() != null && this.getNavbarItems().map((item, idx) => {
  200. // eslint-disable-next-line react/no-array-index-key
  201. return <li key={`navbarItem-${idx}`}>{item}</li>;
  202. }) }
  203. </ul>
  204. </div>
  205. );
  206. }
  207. getNavbarItems() {
  208. // set navbar items(react elements) here that are common in CodeMirrorEditor or TextAreaEditor
  209. const navbarItems = [];
  210. // concat common items and items specific to CodeMirrorEditor or TextAreaEditor
  211. return navbarItems.concat(this.getEditorSubstance().getNavbarItems());
  212. }
  213. renderCheatsheetModal() {
  214. const hideCheatsheetModal = () => {
  215. this.setState({ isCheatsheetModalShown: false });
  216. };
  217. return (
  218. <Modal isOpen={this.state.isCheatsheetModalShown} toggle={hideCheatsheetModal} className="modal-gfm-cheatsheet">
  219. <ModalHeader tag="h4" toggle={hideCheatsheetModal} className="bg-primary text-light">
  220. <i className="icon-fw icon-question" />Markdown help
  221. </ModalHeader>
  222. <ModalBody>
  223. <Cheatsheet />
  224. </ModalBody>
  225. </Modal>
  226. );
  227. }
  228. render() {
  229. const flexContainer = {
  230. height: '100%',
  231. display: 'flex',
  232. flexDirection: 'column',
  233. };
  234. const {
  235. isMobile,
  236. indentSize,
  237. } = this.props;
  238. return (
  239. <>
  240. <div style={flexContainer} className="editor-container">
  241. <Dropzone
  242. ref={(c) => { this.dropzone = c }}
  243. accept={this.getAcceptableType()}
  244. noClick
  245. noKeyboard
  246. multiple={false}
  247. onDragLeave={this.dragLeaveHandler}
  248. onDrop={this.dropHandler}
  249. >
  250. {({
  251. getRootProps,
  252. getInputProps,
  253. isDragAccept,
  254. isDragReject,
  255. }) => {
  256. return (
  257. <div className={this.getDropzoneClassName(isDragAccept, isDragReject)} {...getRootProps()}>
  258. { this.state.dropzoneActive && this.renderDropzoneOverlay() }
  259. { this.state.isComponentDidMount && this.renderNavbar() }
  260. {/* for PC */}
  261. { !isMobile && (
  262. // eslint-disable-next-line arrow-body-style
  263. <CodeMirrorEditor
  264. ref={(c) => { this.cmEditor = c }}
  265. indentSize={indentSize}
  266. onPasteFiles={this.pasteFilesHandler}
  267. onDragEnter={this.dragEnterHandler}
  268. onMarkdownHelpButtonClicked={this.showMarkdownHelp}
  269. onAddAttachmentButtonClicked={this.addAttachmentHandler}
  270. {...this.props}
  271. />
  272. )}
  273. {/* for mobile */}
  274. { isMobile && (
  275. <TextAreaEditor
  276. ref={(c) => { this.taEditor = c }}
  277. onPasteFiles={this.pasteFilesHandler}
  278. onDragEnter={this.dragEnterHandler}
  279. {...this.props}
  280. />
  281. )}
  282. <input {...getInputProps()} />
  283. </div>
  284. );
  285. }}
  286. </Dropzone>
  287. { this.props.isUploadable
  288. && (
  289. <button
  290. type="button"
  291. className="btn btn-outline-secondary btn-block btn-open-dropzone"
  292. onClick={this.addAttachmentHandler}
  293. >
  294. <i className="icon-paper-clip" aria-hidden="true"></i>&nbsp;
  295. Attach files
  296. <span className="d-none d-sm-inline">
  297. &nbsp;by dragging &amp; dropping,&nbsp;
  298. <span className="btn-link">selecting them</span>,&nbsp;
  299. or pasting from the clipboard.
  300. </span>
  301. </button>
  302. )
  303. }
  304. { this.renderCheatsheetModal() }
  305. </div>
  306. </>
  307. );
  308. }
  309. }
  310. Editor.propTypes = Object.assign({
  311. noCdn: PropTypes.bool,
  312. // this value is markdown
  313. value: PropTypes.string,
  314. isMobile: PropTypes.bool,
  315. isUploadable: PropTypes.bool,
  316. isUploadableFile: PropTypes.bool,
  317. onChange: PropTypes.func,
  318. onUpload: PropTypes.func,
  319. editorSettings: PropTypes.object.isRequired,
  320. indentSize: PropTypes.number,
  321. }, AbstractEditor.propTypes);
  322. const EditorWrapper = React.forwardRef((props, ref) => {
  323. const { data: editorSettings } = useEditorSettings();
  324. const { data: defaultIndentSize } = useDefaultIndentSize();
  325. if (editorSettings == null) {
  326. return <></>;
  327. }
  328. return (
  329. <Editor
  330. ref={ref}
  331. {...props}
  332. editorSettings={editorSettings}
  333. // eslint-disable-next-line react/prop-types
  334. indentSize={props.indentSize ?? defaultIndentSize}
  335. />
  336. );
  337. });
  338. export default EditorWrapper;