CodeMirrorEditor.jsx 25 KB

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