docs
Loading...
Searching...
No Matches
Selection

#include <Ultralight/dom/Selection.h>

Overview

A handle to the active user selection or caret in a document.

A dom::Selection represents either a caret or highlighted text on a page. You obtain one by calling Document::getSelection() or Window::getSelection().

The handle is live– reading its properties reflects the user's current selection.

This example checks whether the user highlighted text and shows a quote button:

dom::Selection selection = document.getSelection();
if (!selection.isCollapsed())
ShowQuoteButton(selection.toString());
A handle to the active user selection or caret in a document.
Definition Selection.h:101
bool isCollapsed() const
Whether or not the selection is a caret (isCollapsed).
Definition Selection.h:191
std::string toString() const
Get the selected text (toString).
Definition Selection.h:210

Anchor and Focus

A selection spans between two endpoints in the document tree:

  • The anchor marks where the selection starts. Calling anchorNode() returns the containing dom::Node, and anchorOffset() returns the offset within that node.
  • The focus marks where the selection ends. Calling focusNode() and focusOffset() returns its position, which can sit before the anchor when the user selects backward.

Each document has its own Selection (including each subframe).

Reacting to Selection Changes

Every change to the active selection dispatches a selectionchange event on the document. The library delivers these events during a later Renderer::Update(), dispatching one event for each change.

This example updates UI state whenever the selection changes:

document.addEventListener("selectionchange", [selection] {
UpdateQuoteButton(selection.toString());
});

Selecting a Range

To select a dom::Range, call removeAllRanges() before calling addRange(). On its own, addRange() only expands an existing selection if the new range overlaps it, and it ignores any range that doesn't overlap.

This example selects the contents of an element:

dom::Range range = document.createRange();
range.selectNodeContents(document.getElementById("quote"));
selection.removeAllRanges();
selection.addRange(range);
A handle to a live range (a span of a page between two boundary points).
Definition Range.h:58
void selectNodeContents(const Node &node) const
Make the range cover everything inside a node (selectNodeContents).
Definition Range.h:281
void addRange(const Range &range) const
Select a range (addRange).
Definition Selection.h:426
void removeAllRanges() const
Clear the selection (removeAllRanges or empty).
Definition Selection.h:412

Selections in Text Fields

The selection doesn't enter editable form controls. When an <input> or <textarea> has focus, anchorNode() and focusNode() sit just outside the element, and isCollapsed() returns true. To read or change selected text inside an editable field, use the element's selectionStart and selectionEnd properties instead (see dom::HTMLInputElement).

Differences from Web Browsers

Several methods handle node validation and range ownership differently from JavaScript:

  • Cross-document nodes are ignored. Passing a node from another document (such as a subframe) leaves the selection unchanged instead of throwing an exception.
  • Offsets past the end of a node fail only in extend(). Other placement methods like collapse(), setBaseAndExtent(), and selectAllChildren() don't check whether an offset exceeds the node's length.
  • getRangeAt() returns an independent copy. Changes made to the returned dom::Range don't alter the active selection.

After its page goes away, a Selection stops working like a dom::Element does (see that class).

See also
dom::Document::getSelection(), dom::Window::getSelection(), dom::Range, dom::HTMLInputElement

Static Public Member Functions

static Selection Adopt (ULDOMSelection handle)
 Wrap a C handle you own, taking ownership of it.
static Selection FromBorrowed (ULDOMSelection handle)
 Wrap a C handle you don't own, adding a reference.

Public Member Functions

 Selection ()
 Create an empty Selection.
 Selection (const Selection &other)
 Copy constructor (both handles refer to the same selection).
 Selection (Selection &&other) noexcept
 Move constructor (other becomes empty).
Selection & operator= (Selection other) noexcept
 Assignment (copies or moves).
 ~Selection ()
 Destroy this handle (the selection itself isn't affected).
 operator bool () const
 Whether or not this Selection is valid (see IsAlive()).
bool IsEmpty () const
 Whether or not this Selection is empty (it holds no handle).
bool IsAlive () const
 Whether or not this Selection is valid (it isn't empty and its page is still alive).
Node anchorNode () const
 Get the node the selection starts in (anchorNode).
size_t anchorOffset () const
 Get the offset of the anchor in anchorNode() (anchorOffset).
Node focusNode () const
 Get the node the selection ends in (focusNode).
size_t focusOffset () const
 Get the offset of the focus in focusNode() (focusOffset).
bool isCollapsed () const
 Whether or not the selection is a caret (isCollapsed).
size_t rangeCount () const
 Get the number of ranges in the selection (rangeCount).
std::string type () const
 Get the kind of selection (type).
std::string toString () const
 Get the selected text (toString).
void collapse (const Node &node, size_t offset=0) const
 Place a caret (collapse or setPosition).
Result< void > collapse (const Node &node, Checked_t) const
 Same as collapse(), but returns a Result with the reason for a failure.
Result< void > collapse (const Node &node, size_t offset, Checked_t) const
 Same as collapse() with an offset, but returns a Result with the reason for a failure.
void collapseToStart () const
 Collapse the selection to its start (collapseToStart).
Result< void > collapseToStart (Checked_t) const
 Same as collapseToStart(), but returns a Result with the reason for a failure (eg, an InvalidStateError if nothing is selected).
void collapseToEnd () const
 Collapse the selection to its end (collapseToEnd).
Result< void > collapseToEnd (Checked_t) const
 Same as collapseToEnd(), but returns a Result with the reason for a failure (eg, an InvalidStateError if nothing is selected).
void extend (const Node &node, size_t offset=0) const
 Move the focus and keep the anchor where it is (extend).
Result< void > extend (const Node &node, Checked_t) const
 Same as extend(), but returns a Result with the reason for a failure (eg, an InvalidStateError if nothing is selected).
Result< void > extend (const Node &node, size_t offset, Checked_t) const
 Same as extend() with an offset, but returns a Result with the reason for a failure (eg, an IndexSizeError if offset is past the end of node).
void setBaseAndExtent (const Node &anchor_node, size_t anchor_offset, const Node &focus_node, size_t focus_offset) const
 Set the anchor and the focus in one call (setBaseAndExtent).
Result< void > setBaseAndExtent (const Node &anchor_node, size_t anchor_offset, const Node &focus_node, size_t focus_offset, Checked_t) const
 Same as setBaseAndExtent(), but returns a Result with the reason for a failure.
void selectAllChildren (const Node &node) const
 Select everything inside a node (selectAllChildren).
Result< void > selectAllChildren (const Node &node, Checked_t) const
 Same as selectAllChildren(), but returns a Result with the reason for a failure.
void removeAllRanges () const
 Clear the selection (removeAllRanges or empty).
void addRange (const Range &range) const
 Select a range (addRange).
Range getRangeAt (size_t index) const
 Get a range with the selection's start and end (getRangeAt).
Result< Range > getRangeAt (size_t index, Checked_t) const
 Same as getRangeAt(), but returns a Result with the reason for a failure (eg, an IndexSizeError if index isn't less than rangeCount()).
void deleteFromDocument () const
 Remove the selected content from the page (deleteFromDocument).
bool containsNode (const Node &node, bool partial=false) const
 Whether or not a node is in the selection (containsNode).
void modify (std::string_view alter, std::string_view direction, std::string_view granularity) const
 Move or extend the selection by a unit of text (modify), like the arrow keys do.
ULDOMSelection raw () const
 Get the C handle, for passing to the <Ultralight/CAPI/CAPI_DOMSelection.h> functions.
ULDOMSelection LeakRef ()
 Give up ownership of the C handle and return it.

Protected Member Functions

 Selection (ULDOMSelection handle)

Protected Attributes

ULDOMSelection handle_ = nullptr

Constructor & Destructor Documentation

◆ Selection() [1/4]

Selection ( )
inline

Create an empty Selection.

◆ Selection() [2/4]

Selection ( const Selection & other)
inline

Copy constructor (both handles refer to the same selection).

Parameters
otherThe Selection to copy.

◆ Selection() [3/4]

Selection ( Selection && other)
inlinenoexcept

Move constructor (other becomes empty).

Parameters
otherThe Selection to move from.

◆ ~Selection()

~Selection ( )
inline

Destroy this handle (the selection itself isn't affected).

◆ Selection() [4/4]

Selection ( ULDOMSelection handle)
inlineexplicitprotected

Member Function Documentation

◆ addRange()

void addRange ( const Range & range) const
inline

Select a range (addRange).

If nothing is selected, the selection moves to the range. If something is selected (even just a caret), a range that overlaps it grows the selection to cover both, and any other range is ignored. To replace the selection, call removeAllRanges() first.

Parameters
rangeThe range to select.
Note
The selection takes a copy of the range's boundary points, so changing the range later doesn't change the selection.

◆ Adopt()

Selection Adopt ( ULDOMSelection handle)
inlinestatic

Wrap a C handle you own, taking ownership of it.

Parameters
handleA handle from the C API that you would otherwise destroy with ulDestroyDOMSelection() (NULL gives an empty Selection).
Returns
Returns a Selection that destroys handle when it's done.

◆ anchorNode()

Node anchorNode ( ) const
inline

Get the node the selection starts in (anchorNode).

Returns
Returns the node (empty if nothing is selected).

◆ anchorOffset()

size_t anchorOffset ( ) const
inline

Get the offset of the anchor in anchorNode() (anchorOffset).

◆ collapse() [1/3]

Result< void > collapse ( const Node & node,
Checked_t  ) const
inlinenodiscard

Same as collapse(), but returns a Result with the reason for a failure.

Returns
Returns success (it fails only when this Selection is empty, or its page or node's page is gone).

◆ collapse() [2/3]

Result< void > collapse ( const Node & node,
size_t offset,
Checked_t  ) const
inlinenodiscard

Same as collapse() with an offset, but returns a Result with the reason for a failure.

Returns
Returns success (it fails only when this Selection is empty, or its page or node's page is gone).

◆ collapse() [3/3]

void collapse ( const Node & node,
size_t offset = 0 ) const
inline

Place a caret (collapse or setPosition).

Parameters
nodeThe node to put the caret in. Pass an empty Node to clear the selection.
offsetThe offset in node (like a Range boundary point).
Note
Unlike the web, an offset past the end of node doesn't fail, so check it yourself.

◆ collapseToEnd() [1/2]

void collapseToEnd ( ) const
inline

Collapse the selection to its end (collapseToEnd).

Does nothing if nothing is selected.

◆ collapseToEnd() [2/2]

Result< void > collapseToEnd ( Checked_t ) const
inlinenodiscard

Same as collapseToEnd(), but returns a Result with the reason for a failure (eg, an InvalidStateError if nothing is selected).

Returns
Returns success. Fails with an InvalidStateError if nothing is selected.

◆ collapseToStart() [1/2]

void collapseToStart ( ) const
inline

Collapse the selection to its start (collapseToStart).

Does nothing if nothing is selected.

◆ collapseToStart() [2/2]

Result< void > collapseToStart ( Checked_t ) const
inlinenodiscard

Same as collapseToStart(), but returns a Result with the reason for a failure (eg, an InvalidStateError if nothing is selected).

Returns
Returns success. Fails with an InvalidStateError if nothing is selected.

◆ containsNode()

bool containsNode ( const Node & node,
bool partial = false ) const
inline

Whether or not a node is in the selection (containsNode).

Parameters
nodeThe node to check.
partialPass true to count a node that's only partly selected.
Returns
Returns true if the node is in the selection.
Note
A text node counts if any of its text is selected, even when partial is false.

◆ deleteFromDocument()

void deleteFromDocument ( ) const
inline

Remove the selected content from the page (deleteFromDocument).

The selection collapses to where the content was.

◆ extend() [1/3]

Result< void > extend ( const Node & node,
Checked_t  ) const
inlinenodiscard

Same as extend(), but returns a Result with the reason for a failure (eg, an InvalidStateError if nothing is selected).

Returns
Returns success. Fails with an InvalidStateError if nothing is selected, or an IndexSizeError if offset is past the end of node.

◆ extend() [2/3]

Result< void > extend ( const Node & node,
size_t offset,
Checked_t  ) const
inlinenodiscard

Same as extend() with an offset, but returns a Result with the reason for a failure (eg, an IndexSizeError if offset is past the end of node).

Returns
Returns success. Fails with an InvalidStateError if nothing is selected, or an IndexSizeError if offset is past the end of node.

◆ extend() [3/3]

void extend ( const Node & node,
size_t offset = 0 ) const
inline

Move the focus and keep the anchor where it is (extend).

Use this to grow or shrink the selection from one end.

Parameters
nodeThe node to move the focus into.
offsetThe offset in node (like a Range boundary point).
Note
Nothing changes if nothing is selected or offset is past the end of node.

◆ focusNode()

Node focusNode ( ) const
inline

Get the node the selection ends in (focusNode).

Returns
Returns the node (empty if nothing is selected).

◆ focusOffset()

size_t focusOffset ( ) const
inline

Get the offset of the focus in focusNode() (focusOffset).

◆ FromBorrowed()

Selection FromBorrowed ( ULDOMSelection handle)
inlinestatic

Wrap a C handle you don't own, adding a reference.

Parameters
handleThe borrowed handle (NULL gives an empty Selection).
Returns
Returns a Selection with its own reference, so you can keep it as long as you like.

◆ getRangeAt() [1/2]

Range getRangeAt ( size_t index) const
inline

Get a range with the selection's start and end (getRangeAt).

Parameters
indexThe index of the range (always 0, since a selection has at most one range).
Returns
Returns a new Range (empty if index isn't less than rangeCount()).
Note
Each call returns a new copy. Changing the Range doesn't change the selection.

◆ getRangeAt() [2/2]

Result< Range > getRangeAt ( size_t index,
Checked_t  ) const
inlinenodiscard

Same as getRangeAt(), but returns a Result with the reason for a failure (eg, an IndexSizeError if index isn't less than rangeCount()).

Returns
Returns a new Range. Fails with an IndexSizeError if index isn't less than rangeCount().

◆ IsAlive()

bool IsAlive ( ) const
inline

Whether or not this Selection is valid (it isn't empty and its page is still alive).

Note
Safe to call from any thread.

◆ isCollapsed()

bool isCollapsed ( ) const
inline

Whether or not the selection is a caret (isCollapsed).

Returns
Returns true for a caret, and also when nothing is selected (or the Selection is empty or its page is gone).

◆ IsEmpty()

bool IsEmpty ( ) const
inline

Whether or not this Selection is empty (it holds no handle).

◆ LeakRef()

ULDOMSelection LeakRef ( )
inline

Give up ownership of the C handle and return it.

This Selection becomes empty.

Returns
Returns the handle. You must call ulDestroyDOMSelection() when finished.

◆ modify()

void modify ( std::string_view alter,
std::string_view direction,
std::string_view granularity ) const
inline

Move or extend the selection by a unit of text (modify), like the arrow keys do.

This is the non-standard Selection.modify() that browsers support.

Parameters
altermove to move the caret or extend to grow the selection.
directionforward, backward, left, or right.
granularitycharacter, word, sentence, line, paragraph, lineboundary, sentenceboundary, paragraphboundary, or documentboundary.
Note
The values ignore case. A call with any other value does nothing.

◆ operator bool()

operator bool ( ) const
inlineexplicit

Whether or not this Selection is valid (see IsAlive()).

◆ operator=()

Selection & operator= ( Selection other)
inlinenoexcept

Assignment (copies or moves).

Parameters
otherThe Selection to assign from.
Returns
Returns this Selection.

◆ rangeCount()

size_t rangeCount ( ) const
inline

Get the number of ranges in the selection (rangeCount).

Returns
Returns 0 if nothing is selected, otherwise 1.

◆ raw()

ULDOMSelection raw ( ) const
inline

Get the C handle, for passing to the <Ultralight/CAPI/CAPI_DOMSelection.h> functions.

Returns
Returns the handle (NULL for an empty Selection). This Selection still owns it, so don't destroy it.

◆ removeAllRanges()

void removeAllRanges ( ) const
inline

Clear the selection (removeAllRanges or empty).

◆ selectAllChildren() [1/2]

void selectAllChildren ( const Node & node) const
inline

Select everything inside a node (selectAllChildren).

Parameters
nodeThe node whose children to select. A text node has no children, so this places a caret at its start.

◆ selectAllChildren() [2/2]

Result< void > selectAllChildren ( const Node & node,
Checked_t  ) const
inlinenodiscard

Same as selectAllChildren(), but returns a Result with the reason for a failure.

Returns
Returns success (it fails only when a handle is empty or its page is gone).

◆ setBaseAndExtent() [1/2]

void setBaseAndExtent ( const Node & anchor_node,
size_t anchor_offset,
const Node & focus_node,
size_t focus_offset ) const
inline

Set the anchor and the focus in one call (setBaseAndExtent).

The focus can come before the anchor in the document.

Parameters
anchor_nodeThe node for the anchor.
anchor_offsetThe offset in anchor_node.
focus_nodeThe node for the focus.
focus_offsetThe offset in focus_node.
Note
If one node is empty, the selection becomes a caret at the other point. If both are empty, the selection is cleared.
Note
Unlike the web, an offset past the end of its node doesn't fail, so check offsets yourself.

◆ setBaseAndExtent() [2/2]

Result< void > setBaseAndExtent ( const Node & anchor_node,
size_t anchor_offset,
const Node & focus_node,
size_t focus_offset,
Checked_t  ) const
inlinenodiscard

Same as setBaseAndExtent(), but returns a Result with the reason for a failure.

Returns
Returns success (it fails only when this Selection is empty, or its page or a node's page is gone).

◆ toString()

std::string toString ( ) const
inline

Get the selected text (toString).

◆ type()

std::string type ( ) const
inline

Get the kind of selection (type).

Returns
Returns None (nothing is selected), Caret, or Range.

Member Data Documentation

◆ handle_

ULDOMSelection handle_ = nullptr
protected

The documentation for this class was generated from the following file: