Editor.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. // closeOnUnfocus: false, // for debug
  91. hint: () => {
  92. const matched = cm.getDoc().getRange(sc.from(), sc.to());
  93. const term = matched.replace(':', ''); // remove ':' in the head
  94. // get a list of shortnames
  95. const shortnames = this.searchEmojiShortnames(term);
  96. if (shortnames.length >= 1) {
  97. return {
  98. list: this.generateEmojiRenderer(shortnames),
  99. from: sc.from(),
  100. to: sc.to(),
  101. };
  102. }
  103. },
  104. });
  105. }
  106. /**
  107. * see https://codemirror.net/doc/manual.html#addon_show-hint
  108. * @param {any}
  109. */
  110. generateEmojiRenderer(emojiShortnames) {
  111. return emojiShortnames.map((shortname) => {
  112. return {
  113. text: shortname,
  114. className: 'crowi-emoji-autocomplete',
  115. render: (element) => {
  116. element.innerHTML =
  117. `<div class="img-container">${this.emojiShortnameImageMap[shortname]}</div>` +
  118. `<span class="shortname-container">${shortname}</span>`;
  119. }
  120. }
  121. });
  122. }
  123. /**
  124. * transplanted from https://github.com/emojione/emojione/blob/master/examples/OTHER.md
  125. * @param {string} term
  126. * @returns {string[]} a list of shortname
  127. */
  128. searchEmojiShortnames(term) {
  129. const maxLength = 12;
  130. let results1 = [], results2 = [], results3 = [], results4 = [];
  131. const countLen1 = () => { results1.length; }
  132. const countLen2 = () => { countLen1() + results2.length; }
  133. const countLen3 = () => { countLen2() + results3.length; }
  134. const countLen4 = () => { countLen3() + results4.length; }
  135. // TODO performance tune
  136. // when total length of all results is less than `maxLength`
  137. for (let unicode in emojiStrategy) {
  138. const data = emojiStrategy[unicode];
  139. if (maxLength <= countLen1()) { break; }
  140. // prefix match to shortname
  141. else if (data.shortname.indexOf(`:${term}`) > -1) {
  142. results1.push(data.shortname);
  143. continue;
  144. }
  145. else if (maxLength <= countLen2()) { continue; }
  146. // partial match to shortname
  147. else if (data.shortname.indexOf(term) > -1) {
  148. results2.push(data.shortname);
  149. continue;
  150. }
  151. else if (maxLength <= countLen3()) { continue; }
  152. // partial match to elements of aliases
  153. else if ((data.aliases != null) && data.aliases.find(elem => elem.indexOf(term) > -1)) {
  154. results3.push(data.shortname);
  155. continue;
  156. }
  157. else if (maxLength <= countLen4()) { continue; }
  158. // partial match to elements of keywords
  159. else if ((data.keywords != null) && data.keywords.find(elem => elem.indexOf(term) > -1)) {
  160. results4.push(data.shortname);
  161. }
  162. };
  163. let results = results1.concat(results2).concat(results3).concat(results4);
  164. results = results.slice(0, maxLength);
  165. return results;
  166. }
  167. /**
  168. * dispatch onSave event
  169. */
  170. dispatchSave() {
  171. if (this.props.onSave != null) {
  172. this.props.onSave();
  173. }
  174. }
  175. render() {
  176. return (
  177. <ReactCodeMirror
  178. ref="cm"
  179. value={this.state.value}
  180. options={{
  181. mode: 'gfm',
  182. theme: 'eclipse',
  183. lineNumbers: true,
  184. tabSize: 4,
  185. indentUnit: 4,
  186. lineWrapping: true,
  187. autoRefresh: true,
  188. autoCloseTags: true,
  189. matchBrackets: true,
  190. matchTags: {bothTags: true},
  191. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  192. highlightSelectionMatches: {annotateScrollbar: true},
  193. // markdown mode options
  194. highlightFormatting: true,
  195. // continuelist, indentlist
  196. extraKeys: {
  197. "Enter": "newlineAndIndentContinueMarkdownList",
  198. "Tab": "indentMore",
  199. "Shift-Tab": "indentLess",
  200. }
  201. }}
  202. onScroll={(editor, data) => {
  203. if (this.props.onScroll != null) {
  204. this.props.onScroll(data);
  205. }
  206. }}
  207. onChange={(editor, data, value) => {
  208. if (this.props.onChange != null) {
  209. this.props.onChange(value);
  210. }
  211. // Emoji AutoComplete
  212. this.autoCompleteEmoji(editor);
  213. }}
  214. />
  215. )
  216. }
  217. }
  218. Editor.propTypes = {
  219. value: PropTypes.string,
  220. onChange: PropTypes.func,
  221. onScroll: PropTypes.func,
  222. onSave: PropTypes.func,
  223. };