Editor.jsx 11 KB

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