Skip to content

Instantly share code, notes, and snippets.

@omarstreak
Created December 6, 2017 23:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omarstreak/cf585738ffa4e7d893d8d89bb99c9aa4 to your computer and use it in GitHub Desktop.
Save omarstreak/cf585738ffa4e7d893d8d89bb99c9aa4 to your computer and use it in GitHub Desktop.
function pasteText({replacementText, cursorContext, activeQuery}: {replacementText: string; cursorContext: CursorContext; activeQuery: string;}){
// update text node content with replaced text
const lastIndex = cursorContext.textBeforeCursor.lastIndexOf(activeQuery);
cursorContext.textNode.textContent = cursorContext.textNodeContent.substring(0, lastIndex) + replacementText + cursorContext.textAfterCursor;
const selection = document.getSelection();
if(!selection) return;
// put cursor at the end of the replaced text
const range = document.createRange();
range.setStart(cursorContext.textNode, lastIndex + replacementText.length);
range.setEnd(cursorContext.textNode, lastIndex + replacementText.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment