Editor.jsx 11 KB

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