Skip to content

Instantly share code, notes, and snippets.

@srsudar
Last active April 27, 2020 13:18
Show Gist options
  • Save srsudar/4ae6d1398090e598a8c8938c71961cf3 to your computer and use it in GitHub Desktop.
Save srsudar/4ae6d1398090e598a8c8938c71961cf3 to your computer and use it in GitHub Desktop.
/**
* Highlight a selection on the page. `sel` is optional and mostly provided
* for testing.
*/
public async highlightCurrentSelection(rangyHighlighter:rangyHl.Highlighter, sel: Selection):
Promise<models.HighlightedText> {
const result: models.HighlightedText =
this.createHighlightedTextFromSelection(rangy);
// It looks like Rangy operates only on WrappedSelection. Faking it doesn't
// seem trivial (at least three methods, some of which are non-obvious), and
// WrappedSelection isn't an exported type. For now we'll just disregard the
// sel parameter, which is ugly, but c'est la vie.
sel = sel || this.rangyObj.getSelection(window);
let highlights = rangyHighlighter.highlightSelection(HIGHLIGHT_CLASS_NAME);
if (highlights.length > 1) {
// Chrome only supports a single Range, according to the docs.
throw new Error('More than one highlight, which should be impossible');
}
if (highlights.length == 0) {
console.warn('No highlights returned');
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment