Home Reference Source

application/components/common/simple-editor/modifier/mention.js

  1. import {Editor, EditorState,ContentState, Modifier} from 'draft-js';
  2.  
  3. /**
  4. * Mention modifier injects the mentioned user name into the editor. Keep in mind
  5. * that it doesn't inject any data, necessarily, just the name. The name is parsed on the
  6. * backend, which is what decides how notifications are sent.
  7. *
  8. * @param editorState object EditorState
  9. * @param store object AltStore
  10. * @returns object EditorState
  11. */
  12. const mentionModifier = (editorState, store) => {
  13. // grab the state, then get the current block
  14. const selectionState = editorState.getSelection();
  15. const currentBlock = editorState
  16. .getCurrentContent()
  17. .getBlockForKey(editorState.getSelection().getStartKey());
  18. // get the start of the selection (since it's collapsed)
  19. // then get the raw text
  20. const start = selectionState.getStartOffset();
  21. let end = start;
  22. const text = currentBlock.getText();
  23.  
  24. // count backward through the text until we get to an '@' symbol
  25. for (let i=start; i>=0; i--) {
  26. const char = text.charAt(i);
  27. if (char === '@') {
  28. end = i;
  29. break;
  30. }
  31. }
  32. // then we expand the selection to the entire mention text
  33. const updatedSelection = selectionState.merge({
  34. focusOffset: start,
  35. anchorOffset: end
  36. });
  37.  
  38. const user = store.stores.references.getState().selectedUser;
  39.  
  40. let mention = '@' + user.get('slug');
  41.  
  42. // replace the expanded selection with our new text
  43. const replacement = Modifier.replaceText(
  44. editorState.getCurrentContent(),
  45. updatedSelection,
  46. mention
  47. );
  48. // force the editor to focus back on the end of the text we just passed in
  49. return EditorState.forceSelection(
  50. EditorState.push(editorState, replacement, 'insert-characters'),
  51. replacement.getSelectionAfter()
  52. );
  53. };
  54.  
  55. export default mentionModifier;