Editor.js 15 KB

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