Skip to content

Instantly share code, notes, and snippets.

@Comandeer
Last active November 15, 2018 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Comandeer/32195795833a7a9718eace9e769a24e7 to your computer and use it in GitHub Desktop.
Save Comandeer/32195795833a7a9718eace9e769a24e7 to your computer and use it in GitHub Desktop.
Proposal for simplified API for range highlighting

Proposal for simplified API for range highlighting

::highlight(example-highlight) {
    background-color: yellow;
    color: blue;
}
function highlightText( startNode, startOffset, endNode, endOffset ) {
    const highlightRange = new Range();
    highlightRange.setStart( startNode, startOffset );
    highlightRange.setEnd( endNode, endOffset );
    highlightRange.highlight.style.color = "black";
    highlightRange.highlight.add( 'example-highlight' );
}
partial interface Range {
	[SameObject, PutForwards=false] readonly attribute HighlightList highlights;
};

[Exposed=Window]
partial interface HighlightList {
	readonly attribute unsigned long length;
	[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
	
	boolean contains(USVString name);
	void add(USVString... names);
	void remove(optional USVString... names);
	
	iterable<USVString>;
};

Rationale

  • Moving ability to highlight from HighlightRange into Range allows to highlight already selected text, without the need of recreating the range.
  • Having yet another global collection (alongside e.g. customElements) seems like overkill for most of the cases. What's more, if we must have saved reference to the range to be able to remove it from HighlightsMap, then we could as well do it on range level.
  • HTMLElement has its own style property, which contains all styles associated directly to the element. Analogically Range can have its own property connected with highlighting.
  • HighlightList is based on DOMTokenList (used in e.g. element.classList). The main difference is the changed behavior of remove method, which will remove all highlights if called without parameters.

Issues

  • There seems to be a fundamental incompatibility between the new Highlight API and Selection API. The first one allows to have multiple ranges rendered at once in several places on the screen, while the latter allows only one-range selection. If browsers supported multiple-range selection, we would be able to extend Selection interface with highlight abilities.
  • Adding HighlightList to Range interface allows range to decide, when it will be rendered. It could be seen as a breach of SRP: Range should not decide about it. OTOH it won't be a precedence, as HTMLElement has methods like append or remove. Additionally, due to this change, API for highlighting will be much simpler and contained.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment