Created
December 6, 2017 22:53
-
-
Save omarstreak/b78052726032ecd933ea0ce652d44314 to your computer and use it in GitHub Desktop.
Function to get information around cursor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @flow */ | |
/* this code heavily borrows from https://github.com/zurb/tribute */ | |
export type CursorContext = { | |
textNode: Node; | |
textNodeParent: Node; | |
textNodeContent: string; | |
textBeforeCursor: string; | |
textAfterCursor: string; | |
cursorCharacterPosition: number; | |
}; | |
export default function getCursorContext(): ?CursorContext { | |
let cursorTextNodeAndParent = getTextNodeAndParent(); | |
if(!cursorTextNodeAndParent) return null; | |
// we now normalize the textNodeParent to make sure there's only one text node | |
// makes subsequent code a lot simpler | |
cursorTextNodeAndParent.textNodeParent.normalize(); | |
cursorTextNodeAndParent = getTextNodeAndParent(); | |
if(!cursorTextNodeAndParent) return null; | |
const {textNode, textNodeParent, selection} = cursorTextNodeAndParent; | |
const range = selection.getRangeAt(0); | |
const textNodeContent = textNode.textContent; | |
const cursorCharacterPosition = range.startOffset; | |
if(!(cursorCharacterPosition >= 0)) return null; | |
return { | |
textNode, textNodeParent, textNodeContent, cursorCharacterPosition, | |
textBeforeCursor: textNodeContent.substring(0, cursorCharacterPosition), | |
textAfterCursor: textNodeContent.substr(cursorCharacterPosition) | |
}; | |
} | |
function getTextNodeAndParent(): ?{textNode: Node; textNodeParent: Node; selection: Selection;} { | |
const selection = document.getSelection(); | |
if(!selection) return null; | |
const textNode = selection.anchorNode; | |
if(!textNode || textNode.nodeType !== Node.TEXT_NODE) return null; | |
const textNodeParent = textNode.parentNode; | |
if(!textNodeParent) return null; | |
return {textNode, textNodeParent, selection}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment