CodeMirrorEditor.jsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import urljoin from 'url-join';
  4. import * as codemirror from 'codemirror';
  5. import { Button } from 'reactstrap';
  6. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  7. import InterceptorManager from '@commons/service/interceptor-manager';
  8. import AbstractEditor from './AbstractEditor';
  9. import SimpleCheatsheet from './SimpleCheatsheet';
  10. import pasteHelper from './PasteHelper';
  11. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  12. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  13. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  14. import mtu from './MarkdownTableUtil';
  15. import HandsontableModal from './HandsontableModal';
  16. import EditorIcon from './EditorIcon';
  17. const loadScript = require('simple-load-script');
  18. const loadCssSync = require('load-css-file');
  19. // set save handler
  20. codemirror.commands.save = (instance) => {
  21. if (instance.codeMirrorEditor != null) {
  22. instance.codeMirrorEditor.dispatchSave();
  23. }
  24. };
  25. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  26. window.CodeMirror = require('codemirror');
  27. require('codemirror/addon/display/placeholder');
  28. require('codemirror/addon/edit/matchbrackets');
  29. require('codemirror/addon/edit/matchtags');
  30. require('codemirror/addon/edit/closetag');
  31. require('codemirror/addon/edit/continuelist');
  32. require('codemirror/addon/hint/show-hint');
  33. require('codemirror/addon/hint/show-hint.css');
  34. require('codemirror/addon/search/searchcursor');
  35. require('codemirror/addon/search/match-highlighter');
  36. require('codemirror/addon/selection/active-line');
  37. require('codemirror/addon/scroll/annotatescrollbar');
  38. require('codemirror/addon/fold/foldcode');
  39. require('codemirror/addon/fold/foldgutter');
  40. require('codemirror/addon/fold/foldgutter.css');
  41. require('codemirror/addon/fold/markdown-fold');
  42. require('codemirror/addon/fold/brace-fold');
  43. require('codemirror/addon/display/placeholder');
  44. require('codemirror/mode/gfm/gfm');
  45. require('../../util/codemirror/autorefresh.ext');
  46. const MARKDOWN_TABLE_ACTIVATED_CLASS = 'markdown-table-activated';
  47. export default class CodeMirrorEditor extends AbstractEditor {
  48. constructor(props) {
  49. super(props);
  50. this.logger = require('@alias/logger')('growi:PageEditor:CodeMirrorEditor');
  51. this.state = {
  52. value: this.props.value,
  53. isGfmMode: this.props.isGfmMode,
  54. isEnabledEmojiAutoComplete: false,
  55. isLoadingKeymap: false,
  56. isSimpleCheatsheetShown: this.props.isGfmMode && this.props.value.length === 0,
  57. isCheatsheetModalShown: false,
  58. additionalClassSet: new Set(),
  59. };
  60. this.init();
  61. this.getCodeMirror = this.getCodeMirror.bind(this);
  62. this.getBol = this.getBol.bind(this);
  63. this.getEol = this.getEol.bind(this);
  64. this.loadTheme = this.loadTheme.bind(this);
  65. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  66. this.setKeymapMode = this.setKeymapMode.bind(this);
  67. this.handleEnterKey = this.handleEnterKey.bind(this);
  68. this.handleCtrlEnterKey = this.handleCtrlEnterKey.bind(this);
  69. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  70. this.pasteHandler = this.pasteHandler.bind(this);
  71. this.cursorHandler = this.cursorHandler.bind(this);
  72. this.changeHandler = this.changeHandler.bind(this);
  73. this.updateCheatsheetStates = this.updateCheatsheetStates.bind(this);
  74. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  75. this.renderCheatsheetModalButton = this.renderCheatsheetModalButton.bind(this);
  76. this.makeHeaderHandler = this.makeHeaderHandler.bind(this);
  77. this.showHandsonTableHandler = this.showHandsonTableHandler.bind(this);
  78. }
  79. init() {
  80. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.42.0';
  81. this.cmNoCdnScriptRoot = '/js/cdn';
  82. this.cmNoCdnStyleRoot = '/styles/cdn';
  83. this.interceptorManager = new InterceptorManager();
  84. this.interceptorManager.addInterceptors([
  85. new PreventMarkdownListInterceptor(),
  86. new MarkdownTableInterceptor(),
  87. ]);
  88. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  89. this.loadedKeymapSet = new Set();
  90. }
  91. componentWillMount() {
  92. if (this.props.emojiStrategy != null) {
  93. this.emojiAutoCompleteHelper = new EmojiAutoCompleteHelper(this.props.emojiStrategy);
  94. this.setState({ isEnabledEmojiAutoComplete: true });
  95. }
  96. }
  97. componentDidMount() {
  98. // ensure to be able to resolve 'this' to use 'codemirror.commands.save'
  99. this.getCodeMirror().codeMirrorEditor = this;
  100. // load theme
  101. const theme = this.props.editorOptions.theme;
  102. this.loadTheme(theme);
  103. // set keymap
  104. const keymapMode = this.props.editorOptions.keymapMode;
  105. this.setKeymapMode(keymapMode);
  106. }
  107. componentWillReceiveProps(nextProps) {
  108. // load theme
  109. const theme = nextProps.editorOptions.theme;
  110. this.loadTheme(theme);
  111. // set keymap
  112. const keymapMode = nextProps.editorOptions.keymapMode;
  113. this.setKeymapMode(keymapMode);
  114. }
  115. getCodeMirror() {
  116. return this.cm.editor;
  117. }
  118. /**
  119. * @inheritDoc
  120. */
  121. forceToFocus() {
  122. const editor = this.getCodeMirror();
  123. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  124. const intervalId = setInterval(() => {
  125. this.getCodeMirror().focus();
  126. if (editor.hasFocus()) {
  127. clearInterval(intervalId);
  128. // refresh
  129. editor.refresh();
  130. }
  131. }, 100);
  132. }
  133. /**
  134. * @inheritDoc
  135. */
  136. setValue(newValue) {
  137. this.setState({ value: newValue });
  138. this.getCodeMirror().getDoc().setValue(newValue);
  139. }
  140. /**
  141. * @inheritDoc
  142. */
  143. setGfmMode(bool) {
  144. // update state
  145. this.setState({
  146. isGfmMode: bool,
  147. isEnabledEmojiAutoComplete: bool,
  148. });
  149. this.updateCheatsheetStates(bool, null);
  150. // update CodeMirror option
  151. const mode = bool ? 'gfm' : undefined;
  152. this.getCodeMirror().setOption('mode', mode);
  153. }
  154. /**
  155. * @inheritDoc
  156. */
  157. setCaretLine(line) {
  158. if (Number.isNaN(line)) {
  159. return;
  160. }
  161. const editor = this.getCodeMirror();
  162. const linePosition = Math.max(0, line);
  163. editor.setCursor({ line: linePosition }); // leave 'ch' field as null/undefined to indicate the end of line
  164. this.setScrollTopByLine(linePosition);
  165. }
  166. /**
  167. * @inheritDoc
  168. */
  169. setScrollTopByLine(line) {
  170. if (Number.isNaN(line)) {
  171. return;
  172. }
  173. const editor = this.getCodeMirror();
  174. // get top position of the line
  175. const top = editor.charCoords({ line, ch: 0 }, 'local').top;
  176. editor.scrollTo(null, top);
  177. }
  178. /**
  179. * @inheritDoc
  180. */
  181. getStrFromBol() {
  182. const editor = this.getCodeMirror();
  183. const curPos = editor.getCursor();
  184. return editor.getDoc().getRange(this.getBol(), curPos);
  185. }
  186. /**
  187. * @inheritDoc
  188. */
  189. getStrToEol() {
  190. const editor = this.getCodeMirror();
  191. const curPos = editor.getCursor();
  192. return editor.getDoc().getRange(curPos, this.getEol());
  193. }
  194. /**
  195. * @inheritDoc
  196. */
  197. getStrFromBolToSelectedUpperPos() {
  198. const editor = this.getCodeMirror();
  199. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  200. return editor.getDoc().getRange(this.getBol(), pos);
  201. }
  202. /**
  203. * @inheritDoc
  204. */
  205. replaceBolToCurrentPos(text) {
  206. const editor = this.getCodeMirror();
  207. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  208. editor.getDoc().replaceRange(text, this.getBol(), pos);
  209. }
  210. /**
  211. * @inheritDoc
  212. */
  213. replaceLine(text) {
  214. const editor = this.getCodeMirror();
  215. editor.getDoc().replaceRange(text, this.getBol(), this.getEol());
  216. }
  217. /**
  218. * @inheritDoc
  219. */
  220. insertText(text) {
  221. const editor = this.getCodeMirror();
  222. editor.getDoc().replaceSelection(text);
  223. }
  224. /**
  225. * return the postion of the BOL(beginning of line)
  226. */
  227. getBol() {
  228. const editor = this.getCodeMirror();
  229. const curPos = editor.getCursor();
  230. return { line: curPos.line, ch: 0 };
  231. }
  232. /**
  233. * return the postion of the EOL(end of line)
  234. */
  235. getEol() {
  236. const editor = this.getCodeMirror();
  237. const curPos = editor.getCursor();
  238. const lineLength = editor.getDoc().getLine(curPos.line).length;
  239. return { line: curPos.line, ch: lineLength };
  240. }
  241. /**
  242. * select the upper position of pos1 and pos2
  243. * @param {{line: number, ch: number}} pos1
  244. * @param {{line: number, ch: number}} pos2
  245. */
  246. selectUpperPos(pos1, pos2) {
  247. // if both is in same line
  248. if (pos1.line === pos2.line) {
  249. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  250. }
  251. return (pos1.line < pos2.line) ? pos1 : pos2;
  252. }
  253. /**
  254. * select the lower position of pos1 and pos2
  255. * @param {{line: number, ch: number}} pos1
  256. * @param {{line: number, ch: number}} pos2
  257. */
  258. selectLowerPos(pos1, pos2) {
  259. // if both is in same line
  260. if (pos1.line === pos2.line) {
  261. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  262. }
  263. return (pos1.line < pos2.line) ? pos2 : pos1;
  264. }
  265. loadCss(source) {
  266. return new Promise((resolve) => {
  267. loadCssSync(source);
  268. resolve();
  269. });
  270. }
  271. /**
  272. * load Theme
  273. * @see https://codemirror.net/doc/manual.html#config
  274. *
  275. * @param {string} theme
  276. */
  277. loadTheme(theme) {
  278. if (!this.loadedThemeSet.has(theme)) {
  279. const url = this.props.noCdn
  280. ? urljoin(this.cmNoCdnStyleRoot, `codemirror-theme-${theme}.css`)
  281. : urljoin(this.cmCdnRoot, `theme/${theme}.min.css`);
  282. this.loadCss(url);
  283. // update Set
  284. this.loadedThemeSet.add(theme);
  285. }
  286. }
  287. /**
  288. * load assets for Key Maps
  289. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  290. */
  291. loadKeymapMode(keymapMode) {
  292. const loadCss = this.loadCss;
  293. const scriptList = [];
  294. const cssList = [];
  295. // add dependencies
  296. if (this.loadedKeymapSet.size === 0) {
  297. const dialogScriptUrl = this.props.noCdn
  298. ? urljoin(this.cmNoCdnScriptRoot, 'codemirror-dialog.js')
  299. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js');
  300. const dialogStyleUrl = this.props.noCdn
  301. ? urljoin(this.cmNoCdnStyleRoot, 'codemirror-dialog.css')
  302. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css');
  303. scriptList.push(loadScript(dialogScriptUrl));
  304. cssList.push(loadCss(dialogStyleUrl));
  305. }
  306. // load keymap
  307. if (!this.loadedKeymapSet.has(keymapMode)) {
  308. const keymapScriptUrl = this.props.noCdn
  309. ? urljoin(this.cmNoCdnScriptRoot, `codemirror-keymap-${keymapMode}.js`)
  310. : urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`);
  311. scriptList.push(loadScript(keymapScriptUrl));
  312. // update Set
  313. this.loadedKeymapSet.add(keymapMode);
  314. }
  315. // set loading state
  316. this.setState({ isLoadingKeymap: true });
  317. return Promise.all(scriptList.concat(cssList))
  318. .then(() => {
  319. this.setState({ isLoadingKeymap: false });
  320. });
  321. }
  322. /**
  323. * set Key Maps
  324. * @see https://codemirror.net/doc/manual.html#keymaps
  325. *
  326. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  327. */
  328. setKeymapMode(keymapMode) {
  329. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  330. // reset
  331. this.getCodeMirror().setOption('keyMap', 'default');
  332. return;
  333. }
  334. this.loadKeymapMode(keymapMode)
  335. .then(() => {
  336. let errorCount = 0;
  337. const timer = setInterval(() => {
  338. if (errorCount > 10) { // cancel over 3000ms
  339. this.logger.error(`Timeout to load keyMap '${keymapMode}'`);
  340. clearInterval(timer);
  341. }
  342. try {
  343. this.getCodeMirror().setOption('keyMap', keymapMode);
  344. clearInterval(timer);
  345. }
  346. catch (e) {
  347. this.logger.info(`keyMap '${keymapMode}' has not been initialized. retry..`);
  348. // continue if error occured
  349. errorCount++;
  350. }
  351. }, 300);
  352. });
  353. }
  354. /**
  355. * handle ENTER key
  356. */
  357. handleEnterKey() {
  358. if (!this.state.isGfmMode) {
  359. codemirror.commands.newlineAndIndent(this.getCodeMirror());
  360. return;
  361. }
  362. const context = {
  363. handlers: [], // list of handlers which process enter key
  364. editor: this,
  365. };
  366. const interceptorManager = this.interceptorManager;
  367. interceptorManager.process('preHandleEnter', context)
  368. .then(() => {
  369. if (context.handlers.length === 0) {
  370. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  371. }
  372. });
  373. }
  374. /**
  375. * handle Ctrl+ENTER key
  376. */
  377. handleCtrlEnterKey() {
  378. if (this.props.onCtrlEnter != null) {
  379. this.props.onCtrlEnter();
  380. }
  381. }
  382. scrollCursorIntoViewHandler(editor, event) {
  383. if (this.props.onScrollCursorIntoView != null) {
  384. const line = editor.getCursor().line;
  385. this.props.onScrollCursorIntoView(line);
  386. }
  387. }
  388. cursorHandler(editor, event) {
  389. const { additionalClassSet } = this.state;
  390. const hasCustomClass = additionalClassSet.has(MARKDOWN_TABLE_ACTIVATED_CLASS);
  391. const isInTable = mtu.isInTable(editor);
  392. if (!hasCustomClass && isInTable) {
  393. additionalClassSet.add(MARKDOWN_TABLE_ACTIVATED_CLASS);
  394. this.setState({ additionalClassSet });
  395. }
  396. if (hasCustomClass && !isInTable) {
  397. additionalClassSet.delete(MARKDOWN_TABLE_ACTIVATED_CLASS);
  398. this.setState({ additionalClassSet });
  399. }
  400. }
  401. changeHandler(editor, data, value) {
  402. if (this.props.onChange != null) {
  403. this.props.onChange(value);
  404. }
  405. this.updateCheatsheetStates(null, value);
  406. // Emoji AutoComplete
  407. if (this.state.isEnabledEmojiAutoComplete) {
  408. this.emojiAutoCompleteHelper.showHint(editor);
  409. }
  410. }
  411. /**
  412. * CodeMirror paste event handler
  413. * see: https://codemirror.net/doc/manual.html#events
  414. * @param {any} editor An editor instance of CodeMirror
  415. * @param {any} event
  416. */
  417. pasteHandler(editor, event) {
  418. const types = event.clipboardData.types;
  419. // files
  420. if (types.includes('Files')) {
  421. event.preventDefault();
  422. this.dispatchPasteFiles(event);
  423. }
  424. // text
  425. else if (types.includes('text/plain')) {
  426. pasteHelper.pasteText(this, event);
  427. }
  428. }
  429. /**
  430. * update states which related to cheatsheet
  431. * @param {boolean} isGfmModeTmp (use state.isGfmMode if null is set)
  432. * @param {string} valueTmp (get value from codemirror if null is set)
  433. */
  434. updateCheatsheetStates(isGfmModeTmp, valueTmp) {
  435. const isGfmMode = isGfmModeTmp || this.state.isGfmMode;
  436. const value = valueTmp || this.getCodeMirror().getDoc().getValue();
  437. // update isSimpleCheatsheetShown
  438. const isSimpleCheatsheetShown = isGfmMode && value.length === 0;
  439. this.setState({ isSimpleCheatsheetShown });
  440. }
  441. markdownHelpButtonClickedHandler() {
  442. if (this.props.onMarkdownHelpButtonClicked != null) {
  443. this.props.onMarkdownHelpButtonClicked();
  444. }
  445. }
  446. renderLoadingKeymapOverlay() {
  447. // centering
  448. const style = {
  449. top: 0,
  450. right: 0,
  451. bottom: 0,
  452. left: 0,
  453. };
  454. return this.state.isLoadingKeymap
  455. ? (
  456. <div className="overlay overlay-loading-keymap">
  457. <span style={style} className="overlay-content">
  458. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  459. </span>
  460. </div>
  461. )
  462. : '';
  463. }
  464. renderCheatsheetModalButton() {
  465. return (
  466. <button type="button" className="btn-link gfm-cheatsheet-modal-link text-muted small p-0" onClick={() => { this.markdownHelpButtonClickedHandler() }}>
  467. <i className="icon-question" /> Markdown
  468. </button>
  469. );
  470. }
  471. renderCheatsheetOverlay() {
  472. const cheatsheetModalButton = this.renderCheatsheetModalButton();
  473. return (
  474. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3">
  475. { this.state.isSimpleCheatsheetShown
  476. ? (
  477. <div className="text-right">
  478. {cheatsheetModalButton}
  479. <div className="mt-2">
  480. <SimpleCheatsheet />
  481. </div>
  482. </div>
  483. )
  484. : (
  485. <div className="mr-4">
  486. {cheatsheetModalButton}
  487. </div>
  488. )
  489. }
  490. </div>
  491. );
  492. }
  493. /**
  494. * return a function to replace a selected range with prefix + selection + suffix
  495. *
  496. * The cursor after replacing is inserted between the selection and the suffix.
  497. */
  498. createReplaceSelectionHandler(prefix, suffix) {
  499. return () => {
  500. const cm = this.getCodeMirror();
  501. const selection = cm.getDoc().getSelection();
  502. const curStartPos = cm.getCursor('from');
  503. const curEndPos = cm.getCursor('to');
  504. const curPosAfterReplacing = {};
  505. curPosAfterReplacing.line = curEndPos.line;
  506. if (curStartPos.line === curEndPos.line) {
  507. curPosAfterReplacing.ch = curEndPos.ch + prefix.length;
  508. }
  509. else {
  510. curPosAfterReplacing.ch = curEndPos.ch;
  511. }
  512. cm.getDoc().replaceSelection(prefix + selection + suffix);
  513. cm.setCursor(curPosAfterReplacing);
  514. cm.focus();
  515. };
  516. }
  517. /**
  518. * return a function to add prefix to selected each lines
  519. *
  520. * The cursor after editing is inserted between the end of the selection.
  521. */
  522. createAddPrefixToEachLinesHandler(prefix) {
  523. return () => {
  524. const cm = this.getCodeMirror();
  525. const startLineNum = cm.getCursor('from').line;
  526. const endLineNum = cm.getCursor('to').line;
  527. const lines = [];
  528. for (let i = startLineNum; i <= endLineNum; i++) {
  529. lines.push(prefix + cm.getDoc().getLine(i));
  530. }
  531. const replacement = `${lines.join('\n')}\n`;
  532. cm.getDoc().replaceRange(replacement, { line: startLineNum, ch: 0 }, { line: endLineNum + 1, ch: 0 });
  533. cm.setCursor(endLineNum, cm.getDoc().getLine(endLineNum).length);
  534. cm.focus();
  535. };
  536. }
  537. /**
  538. * make a selected line a header
  539. *
  540. * The cursor after editing is inserted between the end of the line.
  541. */
  542. makeHeaderHandler() {
  543. const cm = this.getCodeMirror();
  544. const lineNum = cm.getCursor('from').line;
  545. const line = cm.getDoc().getLine(lineNum);
  546. let prefix = '#';
  547. if (!line.startsWith('#')) {
  548. prefix += ' ';
  549. }
  550. cm.getDoc().replaceRange(prefix, { line: lineNum, ch: 0 }, { line: lineNum, ch: 0 });
  551. cm.focus();
  552. }
  553. showHandsonTableHandler() {
  554. this.handsontableModal.show(mtu.getMarkdownTable(this.getCodeMirror()));
  555. }
  556. getNavbarItems() {
  557. return [
  558. /* eslint-disable max-len */
  559. <Button
  560. key="nav-item-bold"
  561. size="sm"
  562. title="Bold"
  563. onClick={this.createReplaceSelectionHandler('**', '**')}
  564. >
  565. <EditorIcon icon="Bold" />
  566. </Button>,
  567. <Button
  568. key="nav-item-italic"
  569. size="sm"
  570. title="Italic"
  571. onClick={this.createReplaceSelectionHandler('*', '*')}
  572. >
  573. <EditorIcon icon="Italic" />
  574. </Button>,
  575. <Button
  576. key="nav-item-strikethrough"
  577. size="sm"
  578. title="Strikethrough"
  579. onClick={this.createReplaceSelectionHandler('~~', '~~')}
  580. >
  581. <EditorIcon icon="Strikethrough" />
  582. </Button>,
  583. <Button
  584. key="nav-item-header"
  585. size="sm"
  586. title="Heading"
  587. onClick={this.makeHeaderHandler}
  588. >
  589. <EditorIcon icon="Heading" />
  590. </Button>,
  591. <Button
  592. key="nav-item-code"
  593. size="sm"
  594. title="Inline Code"
  595. onClick={this.createReplaceSelectionHandler('`', '`')}
  596. >
  597. <EditorIcon icon="InlineCode" />
  598. </Button>,
  599. <Button
  600. key="nav-item-quote"
  601. size="sm"
  602. title="Quote"
  603. onClick={this.createAddPrefixToEachLinesHandler('> ')}
  604. >
  605. <EditorIcon icon="Quote" />
  606. </Button>,
  607. <Button
  608. key="nav-item-ul"
  609. size="sm"
  610. title="List"
  611. onClick={this.createAddPrefixToEachLinesHandler('- ')}
  612. >
  613. <EditorIcon icon="List" />
  614. </Button>,
  615. <Button
  616. key="nav-item-ol"
  617. size="sm"
  618. title="Numbered List"
  619. onClick={this.createAddPrefixToEachLinesHandler('1. ')}
  620. >
  621. <EditorIcon icon="NumberedList" />
  622. </Button>,
  623. <Button
  624. key="nav-item-checkbox"
  625. size="sm"
  626. title="Check List"
  627. onClick={this.createAddPrefixToEachLinesHandler('- [ ] ')}
  628. >
  629. <EditorIcon icon="CheckList" />
  630. </Button>,
  631. <Button
  632. key="nav-item-link"
  633. size="sm"
  634. title="Link"
  635. onClick={this.createReplaceSelectionHandler('[', ']()')}
  636. >
  637. <EditorIcon icon="Link" />
  638. </Button>,
  639. <Button
  640. key="nav-item-image"
  641. size="sm"
  642. title="Image"
  643. onClick={this.createReplaceSelectionHandler('![', ']()')}
  644. >
  645. <EditorIcon icon="Image" />
  646. </Button>,
  647. <Button
  648. key="nav-item-table"
  649. size="sm"
  650. title="Table"
  651. onClick={this.showHandsonTableHandler}
  652. >
  653. <EditorIcon icon="Table" />
  654. </Button>,
  655. /* eslint-able max-len */
  656. ];
  657. }
  658. render() {
  659. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  660. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  661. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plane Text..';
  662. return (
  663. <React.Fragment>
  664. <ReactCodeMirror
  665. ref={(c) => { this.cm = c }}
  666. className={additionalClasses}
  667. placeholder="search"
  668. editorDidMount={(editor) => {
  669. // add event handlers
  670. editor.on('paste', this.pasteHandler);
  671. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  672. }}
  673. value={this.state.value}
  674. options={{
  675. mode,
  676. theme: this.props.editorOptions.theme,
  677. styleActiveLine: this.props.editorOptions.styleActiveLine,
  678. lineNumbers: this.props.lineNumbers,
  679. tabSize: 4,
  680. indentUnit: 4,
  681. lineWrapping: true,
  682. autoRefresh: { force: true }, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  683. autoCloseTags: true,
  684. placeholder,
  685. matchBrackets: true,
  686. matchTags: { bothTags: true },
  687. // folding
  688. foldGutter: this.props.lineNumbers,
  689. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  690. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  691. highlightSelectionMatches: { annotateScrollbar: true },
  692. // markdown mode options
  693. highlightFormatting: true,
  694. // continuelist, indentlist
  695. extraKeys: {
  696. Enter: this.handleEnterKey,
  697. 'Ctrl-Enter': this.handleCtrlEnterKey,
  698. 'Cmd-Enter': this.handleCtrlEnterKey,
  699. Tab: 'indentMore',
  700. 'Shift-Tab': 'indentLess',
  701. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  702. },
  703. }}
  704. onCursor={this.cursorHandler}
  705. onScroll={(editor, data) => {
  706. if (this.props.onScroll != null) {
  707. // add line data
  708. const line = editor.lineAtHeight(data.top, 'local');
  709. data.line = line;
  710. this.props.onScroll(data);
  711. }
  712. }}
  713. onChange={this.changeHandler}
  714. onDragEnter={(editor, event) => {
  715. if (this.props.onDragEnter != null) {
  716. this.props.onDragEnter(event);
  717. }
  718. }}
  719. />
  720. { this.renderLoadingKeymapOverlay() }
  721. { this.renderCheatsheetOverlay() }
  722. <HandsontableModal
  723. ref={(c) => { this.handsontableModal = c }}
  724. onSave={(table) => { return mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }}
  725. />
  726. </React.Fragment>
  727. );
  728. }
  729. }
  730. CodeMirrorEditor.propTypes = Object.assign({
  731. editorOptions: PropTypes.object.isRequired,
  732. emojiStrategy: PropTypes.object,
  733. lineNumbers: PropTypes.bool,
  734. onMarkdownHelpButtonClicked: PropTypes.func,
  735. }, AbstractEditor.propTypes);
  736. CodeMirrorEditor.defaultProps = {
  737. lineNumbers: true,
  738. };