CodeMirrorEditor.jsx 24 KB

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