Editor.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import urljoin from 'url-join';
  4. const loadScripts = require('simple-load-script').all;
  5. const loadCss = require('load-css-file');
  6. import * as codemirror from 'codemirror';
  7. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  8. require('codemirror/lib/codemirror.css');
  9. require('codemirror/addon/display/autorefresh');
  10. require('codemirror/addon/edit/matchbrackets');
  11. require('codemirror/addon/edit/matchtags');
  12. require('codemirror/addon/edit/closetag');
  13. require('codemirror/addon/edit/continuelist');
  14. require('codemirror/addon/hint/show-hint');
  15. require('codemirror/addon/hint/show-hint.css');
  16. require('codemirror/addon/search/searchcursor');
  17. require('codemirror/addon/search/match-highlighter');
  18. require('codemirror/addon/selection/active-line');
  19. require('codemirror/addon/scroll/annotatescrollbar');
  20. require('codemirror/addon/fold/foldcode');
  21. require('codemirror/addon/fold/foldgutter');
  22. require('codemirror/addon/fold/foldgutter.css');
  23. require('codemirror/addon/fold/markdown-fold');
  24. require('codemirror/addon/fold/brace-fold');
  25. require('codemirror/mode/gfm/gfm');
  26. require('codemirror/theme/elegant.css');
  27. require('codemirror/theme/neo.css');
  28. require('codemirror/theme/mdn-like.css');
  29. require('codemirror/theme/material.css');
  30. require('codemirror/theme/monokai.css');
  31. require('codemirror/theme/twilight.css');
  32. import Dropzone from 'react-dropzone';
  33. import pasteHelper from './PasteHelper';
  34. import emojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  35. import InterceptorManager from '../../../../lib/util/interceptor-manager';
  36. import MarkdownListInterceptor from './MarkdownListInterceptor';
  37. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  38. export default class Editor extends React.Component {
  39. constructor(props) {
  40. super(props);
  41. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.37.0';
  42. this.interceptorManager = new InterceptorManager();
  43. this.interceptorManager.addInterceptors([
  44. new MarkdownListInterceptor(),
  45. new MarkdownTableInterceptor(),
  46. ]);
  47. this.state = {
  48. value: this.props.value,
  49. dropzoneActive: false,
  50. isUploading: false,
  51. };
  52. this.getCodeMirror = this.getCodeMirror.bind(this);
  53. this.setCaretLine = this.setCaretLine.bind(this);
  54. this.setScrollTopByLine = this.setScrollTopByLine.bind(this);
  55. this.forceToFocus = this.forceToFocus.bind(this);
  56. this.dispatchSave = this.dispatchSave.bind(this);
  57. this.handleEnterKey = this.handleEnterKey.bind(this);
  58. this.onScrollCursorIntoView = this.onScrollCursorIntoView.bind(this);
  59. this.onPaste = this.onPaste.bind(this);
  60. this.onDragEnterForCM = this.onDragEnterForCM.bind(this);
  61. this.onDragLeave = this.onDragLeave.bind(this);
  62. this.onDrop = this.onDrop.bind(this);
  63. this.getDropzoneAccept = this.getDropzoneAccept.bind(this);
  64. this.getDropzoneClassName = this.getDropzoneClassName.bind(this);
  65. this.renderOverlay = this.renderOverlay.bind(this);
  66. }
  67. componentDidMount() {
  68. // initialize caret line
  69. this.setCaretLine(0);
  70. // set save handler
  71. codemirror.commands.save = this.dispatchSave;
  72. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  73. window.CodeMirror = require('codemirror');
  74. // apply keymapMode
  75. const keymapMode = this.props.editorOptions.keymapMode;
  76. this.setKeymapMode(keymapMode);
  77. }
  78. getCodeMirror() {
  79. return this.refs.cm.editor;
  80. }
  81. loadCssAsync(source) {
  82. return new Promise((resolve) => {
  83. loadCss(source);
  84. resolve();
  85. });
  86. }
  87. forceToFocus() {
  88. const editor = this.getCodeMirror();
  89. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  90. const intervalId = setInterval(() => {
  91. this.getCodeMirror().focus();
  92. if (editor.hasFocus()) {
  93. clearInterval(intervalId);
  94. }
  95. }, 100);
  96. }
  97. /**
  98. * set caret position of codemirror
  99. * @param {string} number
  100. */
  101. setCaretLine(line) {
  102. if (isNaN(line)) {
  103. return;
  104. }
  105. const editor = this.getCodeMirror();
  106. const linePosition = Math.max(0, line);
  107. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  108. this.setScrollTopByLine(linePosition);
  109. }
  110. /**
  111. * scroll
  112. * @param {number} line
  113. */
  114. setScrollTopByLine(line) {
  115. if (isNaN(line)) {
  116. return;
  117. }
  118. const editor = this.getCodeMirror();
  119. // get top position of the line
  120. var top = editor.charCoords({line, ch: 0}, 'local').top;
  121. editor.scrollTo(null, top);
  122. }
  123. /**
  124. * set Key Maps
  125. * @see https://codemirror.net/doc/manual.html#keymaps
  126. *
  127. * @param {string} keymapMode 'vim' or 'emacs' or 'sublime'
  128. */
  129. setKeymapMode(keymapMode) {
  130. const loadCssAsync = this.loadCssAsync;
  131. if (keymapMode == null || !keymapMode.match(/^(vim|emacs|sublime)$/)) {
  132. // reset keymap
  133. this.getCodeMirror().setOption('keyMap', 'default');
  134. return;
  135. }
  136. Promise.all([
  137. loadScripts(
  138. urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js'),
  139. urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)
  140. ),
  141. loadCssAsync(
  142. urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')
  143. )
  144. ]).then(() => {
  145. this.getCodeMirror().setOption('keyMap', keymapMode);
  146. });
  147. }
  148. /**
  149. * remove overlay and set isUploading to false
  150. */
  151. terminateUploadingState() {
  152. this.setState({
  153. dropzoneActive: false,
  154. isUploading: false,
  155. });
  156. }
  157. /**
  158. * insert text
  159. * @param {string} text
  160. */
  161. insertText(text) {
  162. const editor = this.getCodeMirror();
  163. editor.getDoc().replaceSelection(text);
  164. }
  165. /**
  166. * dispatch onSave event
  167. */
  168. dispatchSave() {
  169. if (this.props.onSave != null) {
  170. this.props.onSave();
  171. }
  172. }
  173. /**
  174. * dispatch onUpload event
  175. */
  176. dispatchUpload(files) {
  177. if (this.props.onUpload != null) {
  178. this.props.onUpload(files);
  179. }
  180. }
  181. /**
  182. * handle ENTER key
  183. */
  184. handleEnterKey() {
  185. const editor = this.getCodeMirror();
  186. var context = {
  187. handlers: [], // list of handlers which process enter key
  188. editor: editor,
  189. };
  190. const interceptorManager = this.interceptorManager;
  191. interceptorManager.process('preHandleEnter', context)
  192. .then(() => {
  193. if (context.handlers.length == 0) {
  194. codemirror.commands.newlineAndIndentContinueMarkdownList(editor);
  195. }
  196. });
  197. }
  198. onScrollCursorIntoView(editor, event) {
  199. if (this.props.onScrollCursorIntoView != null) {
  200. const line = editor.getCursor().line;
  201. this.props.onScrollCursorIntoView(line);
  202. }
  203. }
  204. /**
  205. * CodeMirror paste event handler
  206. * see: https://codemirror.net/doc/manual.html#events
  207. * @param {any} editor An editor instance of CodeMirror
  208. * @param {any} event
  209. */
  210. onPaste(editor, event) {
  211. const types = event.clipboardData.types;
  212. // text
  213. if (types.includes('text/plain')) {
  214. pasteHelper.pasteText(editor, event);
  215. }
  216. // files
  217. else if (types.includes('Files')) {
  218. const dropzone = this.refs.dropzone;
  219. const items = event.clipboardData.items || event.clipboardData.files || [];
  220. // abort if length is not 1
  221. if (items.length != 1) {
  222. return;
  223. }
  224. const file = items[0].getAsFile();
  225. // check type and size
  226. if (pasteHelper.fileAccepted(file, dropzone.props.accept) &&
  227. pasteHelper.fileMatchSize(file, dropzone.props.maxSize, dropzone.props.minSize)) {
  228. this.dispatchUpload(file);
  229. this.setState({ isUploading: true });
  230. }
  231. }
  232. }
  233. onDragEnterForCM(editor, event) {
  234. const dataTransfer = event.dataTransfer;
  235. // do nothing if contents is not files
  236. if (!dataTransfer.types.includes('Files')) {
  237. return;
  238. }
  239. this.setState({ dropzoneActive: true });
  240. }
  241. onDragLeave() {
  242. this.setState({ dropzoneActive: false });
  243. }
  244. onDrop(accepted, rejected) {
  245. // rejected
  246. if (accepted.length != 1) { // length should be 0 or 1 because `multiple={false}` is set
  247. this.setState({ dropzoneActive: false });
  248. return;
  249. }
  250. const file = accepted[0];
  251. this.dispatchUpload(file);
  252. this.setState({ isUploading: true });
  253. }
  254. getDropzoneAccept() {
  255. let accept = 'null'; // reject all
  256. if (this.props.isUploadable) {
  257. if (!this.props.isUploadableFile) {
  258. accept = 'image/*' // image only
  259. }
  260. else {
  261. accept = ''; // allow all
  262. }
  263. }
  264. return accept;
  265. }
  266. getDropzoneClassName() {
  267. let className = 'dropzone';
  268. if (!this.props.isUploadable) {
  269. className += ' dropzone-unuploadable';
  270. }
  271. else {
  272. className += ' dropzone-uploadable';
  273. if (this.props.isUploadableFile) {
  274. className += ' dropzone-uploadablefile';
  275. }
  276. }
  277. // uploading
  278. if (this.state.isUploading) {
  279. className += ' dropzone-uploading';
  280. }
  281. return className;
  282. }
  283. renderOverlay() {
  284. const overlayStyle = {
  285. position: 'absolute',
  286. zIndex: 4, // forward than .CodeMirror-gutters
  287. top: 0,
  288. right: 0,
  289. bottom: 0,
  290. left: 0,
  291. };
  292. return (
  293. <div style={overlayStyle} className="dropzone-overlay">
  294. {this.state.isUploading &&
  295. <span className="dropzone-overlay-content">
  296. <i className="fa fa-spinner fa-pulse fa-fw"></i>
  297. <span className="sr-only">Uploading...</span>
  298. </span>
  299. }
  300. {!this.state.isUploading && <span className="dropzone-overlay-content"></span>}
  301. </div>
  302. );
  303. }
  304. render() {
  305. const flexContainer = {
  306. height: '100%',
  307. display: 'flex',
  308. flexDirection: 'column',
  309. }
  310. const theme = this.props.editorOptions.theme || 'elegant';
  311. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  312. return (
  313. <div style={flexContainer}>
  314. <Dropzone
  315. ref="dropzone"
  316. disableClick
  317. disablePreview={true}
  318. accept={this.getDropzoneAccept()}
  319. className={this.getDropzoneClassName()}
  320. acceptClassName="dropzone-accepted"
  321. rejectClassName="dropzone-rejected"
  322. multiple={false}
  323. onDragLeave={this.onDragLeave}
  324. onDrop={this.onDrop}
  325. >
  326. { this.state.dropzoneActive && this.renderOverlay() }
  327. <ReactCodeMirror
  328. ref="cm"
  329. editorDidMount={(editor) => {
  330. // add event handlers
  331. editor.on('paste', this.onPaste);
  332. editor.on('scrollCursorIntoView', this.onScrollCursorIntoView);
  333. }}
  334. value={this.state.value}
  335. options={{
  336. mode: 'gfm',
  337. theme: theme,
  338. styleActiveLine: styleActiveLine,
  339. lineNumbers: true,
  340. tabSize: 4,
  341. indentUnit: 4,
  342. lineWrapping: true,
  343. autoRefresh: true,
  344. autoCloseTags: true,
  345. matchBrackets: true,
  346. matchTags: {bothTags: true},
  347. // folding
  348. foldGutter: true,
  349. gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
  350. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  351. highlightSelectionMatches: {annotateScrollbar: true},
  352. // markdown mode options
  353. highlightFormatting: true,
  354. // continuelist, indentlist
  355. extraKeys: {
  356. 'Enter': this.handleEnterKey,
  357. 'Tab': 'indentMore',
  358. 'Shift-Tab': 'indentLess',
  359. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  360. }
  361. }}
  362. onScroll={(editor, data) => {
  363. if (this.props.onScroll != null) {
  364. // add line data
  365. const line = editor.lineAtHeight(data.top, 'local');
  366. data.line = line;
  367. this.props.onScroll(data);
  368. }
  369. }}
  370. onChange={(editor, data, value) => {
  371. if (this.props.onChange != null) {
  372. this.props.onChange(value);
  373. }
  374. // Emoji AutoComplete
  375. emojiAutoCompleteHelper.showHint(editor);
  376. }}
  377. onDragEnter={this.onDragEnterForCM}
  378. />
  379. </Dropzone>
  380. <button type="button" className="btn btn-default btn-block btn-open-dropzone"
  381. onClick={() => {this.refs.dropzone.open()}}>
  382. <i className="icon-paper-clip" aria-hidden="true"></i>&nbsp;
  383. Attach files by dragging &amp; dropping,&nbsp;
  384. <span className="btn-link">selecting them</span>,&nbsp;
  385. or pasting from the clipboard.
  386. </button>
  387. </div>
  388. )
  389. }
  390. }
  391. Editor.propTypes = {
  392. value: PropTypes.string,
  393. options: PropTypes.object,
  394. isUploadable: PropTypes.bool,
  395. isUploadableFile: PropTypes.bool,
  396. onChange: PropTypes.func,
  397. onScroll: PropTypes.func,
  398. onScrollCursorIntoView: PropTypes.func,
  399. onSave: PropTypes.func,
  400. onUpload: PropTypes.func,
  401. };