Skip to content

Instantly share code, notes, and snippets.

@pmairoldi
Last active October 3, 2018 17:01
Show Gist options
  • Save pmairoldi/e439a54ac4cff3f4942a464ca9eead90 to your computer and use it in GitHub Desktop.
Save pmairoldi/e439a54ac4cff3f4942a464ca9eead90 to your computer and use it in GitHub Desktop.
Cursor Movements
function moveCursorTo(node: Node, offset: number, native: Selection) {
// COMPAT: IE 11 does not support Selection.setBaseAndExtent, fallback to collapse
if (native.setBaseAndExtent) {
native.setBaseAndExtent(node, offset, node, offset);
} else {
native.collapse(node, offset);
}
}
function selectFrom(start: Node, startOffset: number, end: Node, endOffset: number, native: Selection) {
// COMPAT: IE 11 does not support Selection.setBaseAndExtent
if (native.setBaseAndExtent) {
// COMPAT: Since the DOM range has no concept of backwards/forwards
// we need to check and do the right thing here.
// tslint:disable-next-line:no-bitwise
let isBackward = end.compareDocumentPosition(start) & Node.DOCUMENT_POSITION_PRECEDING;
if (isBackward) {
native.setBaseAndExtent(end, endOffset, start, startOffset);
} else {
native.setBaseAndExtent(start, startOffset, end, endOffset);
}
} else {
// COMPAT: IE 11 does not support Selection.setBaseAndExtent, fallback to addRange
native.removeAllRanges();
let range = document.createRange();
range.setStart(start, startOffset);
range.setEnd(end, endOffset);
native.addRange(range);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment