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