Editor.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import emojione from 'emojione';
  4. import emojiStrategy from 'emojione/emoji_strategy.json';
  5. import * as codemirror from 'codemirror';
  6. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  7. require('codemirror/lib/codemirror.css');
  8. require('codemirror/addon/display/autorefresh');
  9. require('codemirror/addon/edit/matchbrackets');
  10. require('codemirror/addon/edit/matchtags');
  11. require('codemirror/addon/edit/closetag');
  12. require('codemirror/addon/edit/continuelist');
  13. require('codemirror/addon/hint/show-hint');
  14. require('codemirror/addon/hint/show-hint.css');
  15. require('codemirror/addon/search/searchcursor');
  16. require('codemirror/addon/search/match-highlighter');
  17. require('codemirror/addon/scroll/annotatescrollbar');
  18. require('codemirror/mode/gfm/gfm');
  19. require('codemirror/theme/eclipse.css');
  20. export default class Editor extends React.Component {
  21. constructor(props) {
  22. super(props);
  23. // https://regex101.com/r/7BN2fR/2
  24. this.indentAndMarkPattern = /^([ \t]*)(?:>|\-|\+|\*|\d+\.) /;
  25. this.state = {
  26. value: this.props.value,
  27. };
  28. this.initEmojiImageMap = this.initEmojiImageMap.bind(this);
  29. this.getCodeMirror = this.getCodeMirror.bind(this);
  30. this.setCaretLine = this.setCaretLine.bind(this);
  31. this.forceToFocus = this.forceToFocus.bind(this);
  32. this.dispatchSave = this.dispatchSave.bind(this);
  33. this.pasteHandler = this.pasteHandler.bind(this);
  34. this.pasteText = this.pasteText.bind(this);
  35. this.autoCompleteEmoji = this.autoCompleteEmoji.bind(this);
  36. this.initEmojiImageMap()
  37. }
  38. componentDidMount() {
  39. // initialize caret line
  40. this.setCaretLine(0);
  41. // set save handler
  42. codemirror.commands.save = this.dispatchSave;
  43. }
  44. initEmojiImageMap() {
  45. this.emojiShortnameImageMap = {};
  46. for (let unicode in emojiStrategy) {
  47. const data = emojiStrategy[unicode];
  48. const shortname = data.shortname;
  49. // add image tag
  50. this.emojiShortnameImageMap[shortname] = emojione.shortnameToImage(shortname);
  51. }
  52. }
  53. getCodeMirror() {
  54. return this.refs.cm.editor;
  55. }
  56. forceToFocus() {
  57. const editor = this.getCodeMirror();
  58. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  59. const intervalId = setInterval(() => {
  60. this.getCodeMirror().focus();
  61. if (editor.hasFocus()) {
  62. clearInterval(intervalId);
  63. }
  64. }, 100);
  65. }
  66. /**
  67. * set caret position of codemirror
  68. * @param {string} number
  69. */
  70. setCaretLine(line) {
  71. const editor = this.getCodeMirror();
  72. editor.setCursor({line: line-1}); // leave 'ch' field as null/undefined to indicate the end of line
  73. }
  74. /**
  75. * try to find emoji terms and show hint
  76. */
  77. autoCompleteEmoji() {
  78. const cm = this.getCodeMirror();
  79. // see https://regex101.com/r/gy3i03/1
  80. const pattern = /:[^:\s]+/
  81. const currentPos = cm.getCursor();
  82. // find previous ':shortname'
  83. const sc = cm.getSearchCursor(pattern, currentPos, { multiline: false });
  84. if (sc.findPrevious()) {
  85. const isInputtingEmoji = (currentPos.line === sc.to().line && currentPos.ch === sc.to().ch);
  86. // return if it isn't inputting emoji
  87. if (!isInputtingEmoji) {
  88. return;
  89. }
  90. }
  91. else {
  92. return;
  93. }
  94. // see https://codemirror.net/doc/manual.html#addon_show-hint
  95. cm.showHint({
  96. completeSingle: false,
  97. // closeOnUnfocus: false, // for debug
  98. hint: () => {
  99. const matched = cm.getDoc().getRange(sc.from(), sc.to());
  100. const term = matched.replace(':', ''); // remove ':' in the head
  101. // get a list of shortnames
  102. const shortnames = this.searchEmojiShortnames(term);
  103. if (shortnames.length >= 1) {
  104. return {
  105. list: this.generateEmojiRenderer(shortnames),
  106. from: sc.from(),
  107. to: sc.to(),
  108. };
  109. }
  110. },
  111. });
  112. }
  113. /**
  114. * see https://codemirror.net/doc/manual.html#addon_show-hint
  115. * @param {any}
  116. */
  117. generateEmojiRenderer(emojiShortnames) {
  118. return emojiShortnames.map((shortname) => {
  119. return {
  120. text: shortname,
  121. className: 'crowi-emoji-autocomplete',
  122. render: (element) => {
  123. element.innerHTML =
  124. `<div class="img-container">${this.emojiShortnameImageMap[shortname]}</div>` +
  125. `<span class="shortname-container">${shortname}</span>`;
  126. }
  127. }
  128. });
  129. }
  130. /**
  131. * transplanted from https://github.com/emojione/emojione/blob/master/examples/OTHER.md
  132. * @param {string} term
  133. * @returns {string[]} a list of shortname
  134. */
  135. searchEmojiShortnames(term) {
  136. const maxLength = 12;
  137. let results1 = [], results2 = [], results3 = [], results4 = [];
  138. const countLen1 = () => { results1.length; }
  139. const countLen2 = () => { countLen1() + results2.length; }
  140. const countLen3 = () => { countLen2() + results3.length; }
  141. const countLen4 = () => { countLen3() + results4.length; }
  142. // TODO performance tune
  143. // when total length of all results is less than `maxLength`
  144. for (let unicode in emojiStrategy) {
  145. const data = emojiStrategy[unicode];
  146. if (maxLength <= countLen1()) { break; }
  147. // prefix match to shortname
  148. else if (data.shortname.indexOf(`:${term}`) > -1) {
  149. results1.push(data.shortname);
  150. continue;
  151. }
  152. else if (maxLength <= countLen2()) { continue; }
  153. // partial match to shortname
  154. else if (data.shortname.indexOf(term) > -1) {
  155. results2.push(data.shortname);
  156. continue;
  157. }
  158. else if (maxLength <= countLen3()) { continue; }
  159. // partial match to elements of aliases
  160. else if ((data.aliases != null) && data.aliases.find(elem => elem.indexOf(term) > -1)) {
  161. results3.push(data.shortname);
  162. continue;
  163. }
  164. else if (maxLength <= countLen4()) { continue; }
  165. // partial match to elements of keywords
  166. else if ((data.keywords != null) && data.keywords.find(elem => elem.indexOf(term) > -1)) {
  167. results4.push(data.shortname);
  168. }
  169. };
  170. let results = results1.concat(results2).concat(results3).concat(results4);
  171. results = results.slice(0, maxLength);
  172. return results;
  173. }
  174. /**
  175. * CodeMirror paste event handler
  176. * see: https://codemirror.net/doc/manual.html#events
  177. * @param {any} editor
  178. * @param {any} event
  179. */
  180. pasteHandler(editor, event) {
  181. if (event.clipboardData.types.includes('text/plain') > -1) {
  182. this.pasteText(editor, event);
  183. }
  184. }
  185. /**
  186. * paste text
  187. * @param {any} editor
  188. * @param {any} event
  189. */
  190. pasteText(editor, event) {
  191. // get data in clipboard
  192. let text = event.clipboardData.getData('text/plain');
  193. if (text.length == 0) { return; }
  194. const curPos = editor.getCursor();
  195. // calc BOL (beginning of line)
  196. const bol = { line: curPos.line, ch: 0 };
  197. // get strings from BOL(beginning of line) to current position
  198. const strFromBol = editor.getDoc().getRange(bol, curPos);
  199. const matched = strFromBol.match(this.indentAndMarkPattern);
  200. // when match completely to pattern
  201. // (this means the current position is the beginning of the list item)
  202. if (matched && matched[0] == strFromBol) {
  203. const adjusted = this.adjustPastedData(strFromBol, text);
  204. // replace
  205. if (adjusted != null) {
  206. event.preventDefault();
  207. this.getCodeMirror().getDoc().replaceRange(adjusted, bol, curPos);
  208. }
  209. }
  210. }
  211. /**
  212. * return adjusted pasted data by indentAndMark
  213. *
  214. * @param {string} indentAndMark
  215. * @param {string} text
  216. * @returns adjusted pasted data
  217. * returns null when adjustment is not necessary
  218. */
  219. adjustPastedData(indentAndMark, text) {
  220. let adjusted = null;
  221. // e.g. '-item ...'
  222. if (text.match(this.indentAndMarkPattern)) {
  223. const indent = indentAndMark.match(this.indentAndMarkPattern)[1];
  224. const lines = text.match(/[^\r\n]+/g);
  225. const replacedLines = lines.map((line) => {
  226. return indent + line;
  227. })
  228. adjusted = replacedLines.join('\n');
  229. }
  230. return adjusted;
  231. }
  232. /**
  233. * dispatch onSave event
  234. */
  235. dispatchSave() {
  236. if (this.props.onSave != null) {
  237. this.props.onSave();
  238. }
  239. }
  240. render() {
  241. return (
  242. <ReactCodeMirror
  243. ref="cm"
  244. editorDidMount={(editor) => {
  245. editor.on('paste', this.pasteHandler);
  246. }}
  247. value={this.state.value}
  248. options={{
  249. mode: 'gfm',
  250. theme: 'eclipse',
  251. lineNumbers: true,
  252. tabSize: 4,
  253. indentUnit: 4,
  254. lineWrapping: true,
  255. autoRefresh: true,
  256. autoCloseTags: true,
  257. matchBrackets: true,
  258. matchTags: {bothTags: true},
  259. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  260. highlightSelectionMatches: {annotateScrollbar: true},
  261. // markdown mode options
  262. highlightFormatting: true,
  263. // continuelist, indentlist
  264. extraKeys: {
  265. "Enter": "newlineAndIndentContinueMarkdownList",
  266. "Tab": "indentMore",
  267. "Shift-Tab": "indentLess",
  268. }
  269. }}
  270. onScroll={(editor, data) => {
  271. if (this.props.onScroll != null) {
  272. this.props.onScroll(data);
  273. }
  274. }}
  275. onChange={(editor, data, value) => {
  276. if (this.props.onChange != null) {
  277. this.props.onChange(value);
  278. }
  279. // Emoji AutoComplete
  280. this.autoCompleteEmoji(editor);
  281. }}
  282. />
  283. )
  284. }
  285. }
  286. Editor.propTypes = {
  287. value: PropTypes.string,
  288. onChange: PropTypes.func,
  289. onScroll: PropTypes.func,
  290. onSave: PropTypes.func,
  291. };