Editor.js 15 KB

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