Editor.jsx 10 KB

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