Editor.js 13 KB

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