Editor.jsx 10 KB

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