Title: CSS Custom Highlight API Module Level 1
Level: 1
Shortname: css-highlight-api
Status: ED
Work Status: exploring
Group: csswg
ED: https://drafts.csswg.org/css-highlight-api-1/
TR: https://www.w3.org/TR/css-highlight-api-1/
Previous Version: https://www.w3.org/TR/2020/WD-css-highlight-api-1-20201022/
Previous Version: https://www.w3.org/TR/2020/WD-css-highlight-api-1-20201208/
Editor: Florian Rivoal, On behalf of Bloomberg, https://florian.rivoal.net/, w3cid 43241
Editor: Sanket Joshi, Microsoft Corporation https://www.microsoft.com, https://github.com/sanketj
Editor: Megan Gardner, Apple Inc. https://apple.com/
Abstract:
	This CSS module describes a mechanism
	for styling arbitrary ranges of a document identified by script.
Complain About: accidental-2119 yes

Introduction

This section is non-normative. The Custom Highlight API extends the concept of [=highlight pseudo-elements=] (see [[css-pseudo-4#highlight-pseudos]]) by providing a way for web developers to style the text of arbitrary Range objects, rather than being limited to the user agent defined ''::selection'', ''::inactive-selection'', ''::spelling-error'', and '''::grammar-error'''. This is useful in a variety of scenarios, including editing frameworks that wish to implement their own selection, find-on-page over virtualized documents, multiple selection to represent online collaboration, or spellchecking frameworks. The Custom Highlight API provides a programmatic way of adding and removing highlights that do not affect the underlying DOM structure, but instead applies styles to text based on [=range=] objects, accessed via the ''::highlight()'' pseudo element.
The following code uses the ''::highlight()'' pseudo-element to apply a yellow background and blue foreground color to the text One two. It does so by adding a {{Highlight}} to the {{HighlightRegistry}} (both of these are new concepts introduced by this specification). The {{Highlight}} will contain a {{Range}} whose boundary points surround the text One two. <style> :root::highlight(example-highlight) { background-color: yellow; color: blue; } </style> <body><span>One </span><span>two </span><span>three…</span> <script> let r = new Range(); r.setStart(document.body, 0); r.setEnd(document.body, 2); CSS.highlights.set("example-highlight", new Highlight(r)); </script> The result would look like:
One Two three…

Module Interactions

This module depends on the Infra Standard [[!INFRA]] and on WebIDL [[!WebIDL]]. It assumes general familiarity with CSS and with the DOM Standard [[DOM]], and specifically extends the mechanisms defined in CSS Pseudo-Elements Module Level 4 [[!css-pseudo-4]] to handle [=highlight pseudo-elements=]. The Selectors Level 4 [[!selectors-4]] specification defines how [=pseudo-elements=] work in general. See [[#references]] for a full list of dependencies. Note: This draft is an early version. As it matures, the CSS-WG could decide to keep it as an independent module, or might prefer to fold it into [[css-pseudo-4]], or a later version of that module.

Setting up Custom Highlights

Creating Custom Highlights

A custom highlight is a collection of [=ranges=] representing portions of a document. They do not necessarily fit into the element tree, and can arbitrarily cross element boundaries without honoring its nesting structure. They can be used to affect the appearance of these portions of the document (see [[#styling-highlights]]), or to handle to events associated with them (see [[#events]]). [=Custom highlights=] are represented by Highlight objects, [=setlike=] objects whose [=set entries=] are {{AbstractRange}} objects. [=Ranges=] can be added to a [=custom highlight=] either by passing them to its constructor, or by using the usual API of [=setlike=] objects to manipulate its [=set entries=]. Note: As the [=ranges=] in a [=custom highlight=] are {{AbstractRange}} objects, authors can chose between using {{Range}} objects and {{StaticRange}} objects. See [[#range-invalidation]] for more details about this choice and its implications. [Exposed=Window] interface Highlight { constructor(AbstractRange... initialRanges); setlike<AbstractRange>; attribute long priority; }; See [[#priorities]] for more information on the {{Highlight/priority}} attribute.
When the Highlight(AbstractRange... initialRanges) constructor is invoked, run the following steps:
  1. Let |highlight| be the new {{Highlight}} object.
  2. Set |highlight|'s {{Highlight/priority}} to 0.
  3. For each |range| of {{initialRanges}}, let |rangeArg| be the result of [=converted to an ECMAScript value|converting=] |range| to an ECMAScript value, then run [[webidl#es-add-delete|the steps for a built-in setlike add function]], with |highlight| as the this value, and |rangeArg| as the argument.
  4. Return |highlight|.

Registering Custom Highlights

In order to have any effect, [=custom highlights=] need to be [=registered=] into the [=highlight registry=]. The highlight registry is accessed via the {{CSS/highlights}} attribute of the {{CSS}} namespace, and represents all the [=custom highlights=] [=registered=] for the [=current global object=]’s [=associated Document=]. It is a [=maplike=], and can be updated using the usual methods. It's [=map entries=] is initially empty. A [=custom highlight=] is said to be registered if it is in the [=highlight registry=]. It stops being [=registered=] if it is later removed. partial namespace CSS { readonly attribute HighlightRegistry highlights; }; [Exposed=Window] interface HighlightRegistry { maplike<DOMString, Highlight>; };
To [=register=] a [=custom highlight=], invoke the set method of the [=highlight registry=] which will run [[webidl#es-map-set|the steps for a built-in maplike set function]], with the [=context object=] as the this value, the passed-in [=custom highlight name=] as |keyArg|, and the passed-in highlight as |valueArg|. The custom highlight name assigned to a [=custom highlight=] when it is [=registered=] is used to identify the highlight during styling (see [[#styling-highlights]]). Note: When registering a [=custom highlight=], authors are recommended to use a [=custom highlight name=] that is a valid CSS [=identifier=]. Using a name that is not a valid identifier can make the highlight hard, and in some cases impossible, to style via CSS. Note: It is possible to [=register=] a [=custom highlight=] with more than one [=custom highlight name=]. However, using more than one name to style a highlight will assign the highlight multiple different sets of styles, without a way to control the stacking order of conflicting styles within these sets during [[#painting|painting]]. This may be limiting for authors and may cause confusing painting behavior (see the [[#styling-problems-with-multiple-names-per-highlight|example]] below for more context). Therefore, it is recommended that authors only use one name per highlight during styling.
<style> div::highlight(bar) { color: red; } div::highlight(foo) { color: green; } </style> <body><div>abc</div> <script> let div = document.body.firstChild; let r = new Range(); r.setStart(div, 0); r.setEnd(div, 1); let h = new Highlight(r); CSS.highlights.set('foo', h); CSS.highlights.set('bar', h); </script> In the example above, the same [=custom highlight=] object is [=registered=] under the names 'foo' and 'bar'. Since each of the [=style rules=] target the same highlight and have the same [=specificity=], authors may expect the last rule to win in cascading order and the highlighted content to be green. However, each highlight name gets an independent set of highlight styles, and the highlight will be painted once per name. In this case, because 'foo' was registered before 'bar', the highlight will be first painted with 'foo''s color (green) and then with 'bar''s color (red). As a result, the highlighted content will appear red.

Styling Custom Highlights

The Custom Highlight Pseudo-element: ''::highlight()''

The ::highlight(<>) pseudo-element (also known as the custom highlight pseudo-element) represents the portion of a document that is being [=contained=] or [=partially contained=] in all the [=ranges=] of the [=registered=] [=custom highlight=] with the [=custom highlight name=] <>, if any. <> must be a valid CSS <>.

Processing Model

Applicable Properties

[=Custom highlight pseudo-elements=], like the built-in [=highlight pseudo-elements=], can only be styled with a limited set of properties. See [[css-pseudo-4#highlight-styling]] for the full list.

Cascading and Inheritance

The [=cascading=] and [=inheritance=] of [=custom highlight pseudo-elements=] is handled identically to that of the built-in [=highlight pseudo-elements=], as defined in [[css-pseudo-4#highlight-cascade]].

Painting

The painting of [=custom highlights=] is also handled identically to that of the built-in [=highlight pseudo-elements=], as specified in [[css-pseudo-4#highlight-bounds]] and [[css-pseudo-4#highlight-painting]], with the following clarifications:
  • [=Collapsed=] [=ranges=] are not rendered.
  • Overlapping [=ranges=] within a single [=custom highlight=] are rendered as if a single range representing the union of the overlapping ones had been specified.
    The following example renders in a single highlight with semi-transparent blue background, not two overlapping ones which can be seen through each other. <style> ::highlight(sample) { background-color: rgba(0, 0, 255, 0.3); } </style> <body>Lorem Ipsum. <script> let textNode = document.body.firstChild; let r1 = new Range(); r1.setStart(textNode, 1); r1.setEnd(textNode, 5); let r2 = new Range(); r2.setStart(textNode, 3); r2.setEnd(textNode, 7); CSS.highlights.set("sample", new Highlight(r1, r2)); </script> In other words, this rendering would be correct:
    Lorem Ipsum.
    However, this one would be incorrect:
    Lorem Ipsum.
  • The [=highlight overlays=] of the [=custom highlights=] are below those of the built-in [=highlight pseudo-elements=] in the stacking order described in [[css-pseudo-4#highlight-painting]].
  • The relative stacking order of the [=highlight overlays=] of multiple [=custom highlights=] is defined by their [=priority=] (see [[#priorities]]).

Priority of Overlapping Highlights

A [=custom highlight=]'s {{Highlight/priority}} attribute defines its priority. This is used to determine the stacking order of the corresponding [=highlight overlay=] during painting operations (see [[#painting]]). A higher [=priority=] results in being above in the stacking order. A custom highlight will have a default numerical priority of 0 if its {{Highlight/priority}} attribute has not been explicitly set. When two or more [=custom highlights=] have the same numerical priority, the one most recently [=registered=] has the higher effective [=priority=].
<style> :root::highlight(foo) { color:blue; background-color:yellow; } :root::highlight(bar) { background-color:orange; } </style> <body>Some text <script> let textNode = document.body.firstChild; let r1 = new Range(); r1.setStart(textNode, 0); r1.setEnd(textNode, 6); let r2 = new Range(); r2.setStart(textNode, 3); r2.setEnd(textNode, 9); let h1 = new Highlight(r1); let h2 = new Highlight(r2); CSS.highlights.set("foo", h1); CSS.highlights.set("bar", h2); </script> As there are no priorities set (i.e. there is a tie between h1 and h2), the custom highlights' styles are stacked in order of insertion into the [=highlight registry=]. The rendered results will have "Som" with blue text on yellow background, "e t" with blue text on orange background, and "ext" with the default color on orange background.
Some text
Setting h1.priority = 1; would cause h1 to stack higher than h2, which would result in "Some t" being blue on yellow, and "ext" being default color on orange.
Some text

Responding to Changes

Repaints

The addition or removal of a [=custom highlight=] in the [=highlight registry=], or of a [=range=] in a [=registered=] [=custom highlight=], must cause the user agent to reevaluate the rendering, and to repaint if appropriate. The user agent must also repaint highlights as needed in response to changes by the author to the {{Highlight/priority}}, or to the [=boundary points=] of {{Range}}s of a [=registered=] [=custom highlight=]. Issue(4596): How should we specify the timing (and synchronicity) of this reevaluation?

Range Updating and Invalidation

Authors can build [=custom highlights=] using either {{Range}}s or {{StaticRange}}s. The resulting [=custom highlight=] represents the same parts of the document, and can be styled identically. However, the behavior is different in case the underlying document is modified. {{Range}}s are [=live ranges=]. The user agent will adjust the [=boundary points=] of {{Range}}s in response to DOM changes overlapping the range or at its boundary, and [[#repaint|repaint]] accordingly. [=Boundary points=] of [=live ranges=] can also be changed by the author. On the other hand, the user agent must not adjust the [=boundary points=] of {{StaticRange}}s in response to DOM changes, nor can they be modified by the author after creation.
Updating all {{Range}} objects as the DOM is modified has a significant performance cost. Authors who intend to observe DOM changes and react to them by adjusting or recreating the ranges in their [=custom highlights=] are strongly encouraged to user {{StaticRange}}s in order to avoid this costly but unnecessary step. Conversely, authors who use {{StaticRange}}s should observe and react to DOM changes, by discarding stale [=ranges=] or [=custom highlights=] and recreating new ones.
When computing how to render the document, if [=start node=] or [=end node=] of any [=range=] in the [=highlight regsitry=] refer to a {{Node}} which is no longer [=in a document tree=], the user agent must ignore that [=range=]. If the [=start offset=] or [=end offset=] of any [=range=] are greater than the corresponding node’s length, The user agent must behave as if it was equal to that length. Issue(4597): As far as I am aware, prior uses of {{StaticRange}}s were for [=ranges=] created by the user agent and passed to the author. Here, it's the other way around, which raises (for the first time?) the question of invalidation of static ranges. Can the above work? Is it Fast enough that it's worth distinguishing static and live ranges? Would some alternative handling be better? Issue(4598): The interaction of {{StaticRange}}s in a [=custom highlight=] and [[css-contain-2]] seems problematic: on a fully contained element, you should expect that DOM changes to descendants of that element will not cause invalidation and restyling/repainting of elements outside the contained one. However, if a static range has a boundary point inside the contained subtree and another boundary point outside of it, and the DOM in the contained subtree is changed so that the boundary point inside no longer points to a valid node, the whole range should be ignored, which would affect painting outside the contained subtree. Is this a weakness of [=style containment=], or of the invalidation logic above, or something else?

Event Handling

Issue: Section on Events TBD, based on https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/master/highlight/events-explainer.md Issue: should custom highlights have a dedicated event handling mechanism, or should that be added to pseudo-elements in general?

Appendix A. Privacy and Security Considerations

This section is non-normative. This specification is not thought to introduce any new security or privacy concern. Anyone suspecting that this is not accurate is encouraged to get in touch with the CSS Working Group or the co-editors.

Appendix B. Acknowledgements

This section is non-normative. Issue: Acknowledge people (other than editors) who deserve credit for this.

Appendix C. Changes

This section is non-normative. There have been only editorial changes since the previous Working Draft; see diffs.