Skip to content

Instantly share code, notes, and snippets.

@omarstreak
Created December 6, 2017 23:10
Show Gist options
  • Save omarstreak/29b08e83f9b0f38923e8c738f0de8482 to your computer and use it in GitHub Desktop.
Save omarstreak/29b08e83f9b0f38923e8c738f0de8482 to your computer and use it in GitHub Desktop.
Positioning the menu at the caret
import containByScreen from 'contain-by-screen';
function positionMenuAtCaret({menuContainer, cursorContext, activeQuery}: {menuContainer: HTMLElement; cursorContext: CursorContext; activeQuery: string;}){
let textNode = cursorContext.textNode;
const menuLeftEdgeCharaterPosition = Math.max(cursorContext.cursorCharacterPosition - activeQuery.length, 0);
const range = document.createRange();
range.setStart(textNode, menuLeftEdgeCharaterPosition);
range.setEnd(textNode, menuLeftEdgeCharaterPosition);
range.collapse(true);
const marker = document.createElement('span');
range.insertNode(marker);
document.body.appendChild(menuContainer);
containByScreen(menuContainer, marker, {position: 'bottom', hAlign: 'left'});
marker.remove();
cursorContext.textNodeParent.normalize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment