Editor.js 14 KB

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