Editor.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. this.state = {
  24. value: this.props.value,
  25. };
  26. this.initEmojiImageMap = this.initEmojiImageMap.bind(this);
  27. this.getCodeMirror = this.getCodeMirror.bind(this);
  28. this.setCaretLine = this.setCaretLine.bind(this);
  29. this.forceToFocus = this.forceToFocus.bind(this);
  30. this.dispatchSave = this.dispatchSave.bind(this);
  31. this.autoCompleteEmoji = this.autoCompleteEmoji.bind(this);
  32. this.initEmojiImageMap()
  33. }
  34. componentDidMount() {
  35. // initialize caret line
  36. this.setCaretLine(0);
  37. // set save handler
  38. codemirror.commands.save = this.dispatchSave;
  39. }
  40. initEmojiImageMap() {
  41. this.emojiShortnameImageMap = {};
  42. for (let unicode in emojiStrategy) {
  43. const data = emojiStrategy[unicode];
  44. const shortname = data.shortname;
  45. // add image tag
  46. this.emojiShortnameImageMap[shortname] = emojione.shortnameToImage(shortname);
  47. }
  48. }
  49. getCodeMirror() {
  50. return this.refs.cm.editor;
  51. }
  52. forceToFocus() {
  53. const editor = this.getCodeMirror();
  54. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  55. const intervalId = setInterval(() => {
  56. this.getCodeMirror().focus();
  57. if (editor.hasFocus()) {
  58. clearInterval(intervalId);
  59. }
  60. }, 100);
  61. }
  62. /**
  63. * set caret position of codemirror
  64. * @param {string} number
  65. */
  66. setCaretLine(line) {
  67. const editor = this.getCodeMirror();
  68. editor.setCursor({line: line-1}); // leave 'ch' field as null/undefined to indicate the end of line
  69. }
  70. /**
  71. * try to find emoji terms and show hint
  72. */
  73. autoCompleteEmoji() {
  74. const cm = this.getCodeMirror();
  75. // see https://regex101.com/r/gy3i03/1
  76. const pattern = /:[^:\s]+/
  77. const currentPos = cm.getCursor();
  78. // find previous ':shortname'
  79. const sc = cm.getSearchCursor(pattern, currentPos, { multiline: false });
  80. if (sc.findPrevious()) {
  81. const isInputtingEmoji = (currentPos.line === sc.to().line && currentPos.ch === sc.to().ch);
  82. // return if it isn't inputting emoji
  83. if (!isInputtingEmoji) {
  84. return;
  85. }
  86. }
  87. // see https://codemirror.net/doc/manual.html#addon_show-hint
  88. cm.showHint({
  89. completeSingle: false,
  90. hint: () => {
  91. const matched = cm.getDoc().getRange(sc.from(), sc.to());
  92. const term = matched.replace(':', ''); // remove ':' in the head
  93. // get a list of shortnames
  94. const shortnames = this.searchEmojiShortnames(term);
  95. if (shortnames.length >= 1) {
  96. return {
  97. list: this.generateEmojiRenderer(shortnames),
  98. from: sc.from(),
  99. to: sc.to(),
  100. };
  101. }
  102. },
  103. });
  104. }
  105. /**
  106. * see https://codemirror.net/doc/manual.html#addon_show-hint
  107. * @param {any}
  108. */
  109. generateEmojiRenderer(emojiShortnames) {
  110. return emojiShortnames.map((shortname) => {
  111. return {
  112. text: shortname,
  113. render: (element) => {
  114. element.innerHTML = `${this.emojiShortnameImageMap[shortname]} ${shortname}`;
  115. }
  116. }
  117. });
  118. }
  119. /**
  120. * transplanted from https://github.com/emojione/emojione/blob/master/examples/OTHER.md
  121. * @param {string} term
  122. * @returns {string[]} a list of shortname
  123. */
  124. searchEmojiShortnames(term) {
  125. const maxLength = 12;
  126. var results = [];
  127. var results2 = [];
  128. var results3 = [];
  129. var results4 = [];
  130. // TODO performance tune
  131. // when total length of all results is less than `maxLength`
  132. for (let unicode in emojiStrategy) {
  133. const data = emojiStrategy[unicode];
  134. // prefix match to shortname
  135. if (maxLength <= results.length) {
  136. break;
  137. }
  138. else if (data.shortname.indexOf(`:${term}`) > -1) {
  139. results.push(data.shortname);
  140. continue;
  141. }
  142. // partial match to shortname
  143. if (maxLength <= results.length) {
  144. continue;
  145. }
  146. else if (data.shortname.indexOf(term) > -1) {
  147. results2.push(data.shortname);
  148. continue;
  149. }
  150. // partial match to aliases
  151. if (maxLength <= results.length + results2.length) {
  152. continue;
  153. }
  154. else if ((data.aliases != null) && (data.aliases.indexOf(term) > -1)) {
  155. results3.push(data.shortname);
  156. continue;
  157. }
  158. // partial match to keywords
  159. if (maxLength <= results.length + results2.length + results3.length) {
  160. continue;
  161. }
  162. else if ((data.keywords != null) && (data.keywords.indexOf(term) > -1)) {
  163. results4.push(data.shortname);
  164. }
  165. };
  166. if (term.length >= 3) {
  167. results.sort(function(a,b) { return (a.length > b.length); });
  168. results2.sort(function(a,b) { return (a.length > b.length); });
  169. results3.sort(function(a,b) { return (a.length > b.length); });
  170. results4.sort();
  171. }
  172. var newResults = results.concat(results2).concat(results3).concat(results4);
  173. newResults = newResults.slice(0, maxLength);
  174. return newResults;
  175. }
  176. /**
  177. * dispatch onSave event
  178. */
  179. dispatchSave() {
  180. if (this.props.onSave != null) {
  181. this.props.onSave();
  182. }
  183. }
  184. render() {
  185. return (
  186. <ReactCodeMirror
  187. ref="cm"
  188. value={this.state.value}
  189. options={{
  190. mode: 'gfm',
  191. theme: 'eclipse',
  192. lineNumbers: true,
  193. tabSize: 4,
  194. indentUnit: 4,
  195. lineWrapping: true,
  196. autoRefresh: true,
  197. autoCloseTags: true,
  198. matchBrackets: true,
  199. matchTags: {bothTags: true},
  200. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  201. highlightSelectionMatches: {annotateScrollbar: true},
  202. // markdown mode options
  203. highlightFormatting: true,
  204. // continuelist, indentlist
  205. extraKeys: {
  206. "Enter": "newlineAndIndentContinueMarkdownList",
  207. "Tab": "indentMore",
  208. "Shift-Tab": "indentLess",
  209. }
  210. }}
  211. onScroll={(editor, data) => {
  212. if (this.props.onScroll != null) {
  213. this.props.onScroll(data);
  214. }
  215. }}
  216. onChange={(editor, data, value) => {
  217. if (this.props.onChange != null) {
  218. this.props.onChange(value);
  219. }
  220. // Emoji AutoComplete
  221. this.autoCompleteEmoji(editor);
  222. }}
  223. />
  224. )
  225. }
  226. }
  227. Editor.propTypes = {
  228. value: PropTypes.string,
  229. onChange: PropTypes.func,
  230. onScroll: PropTypes.func,
  231. onSave: PropTypes.func,
  232. };