Selection (engine/model)
@ckeditor/ckeditor5-engine/src/model/selection
Selection is a set of ranges. It has a direction specified by its anchor and focus (it can be forward or backward). Additionally, selection may have its own attributes (think – whether text typed in in this selection should have those attributes – e.g. whether you type a bolded text).
Filtering
Properties
-
Selection anchor. Anchor is the position from which the selection was started. If a user is making a selection by dragging the mouse, the anchor is where the user pressed the mouse button (the beginning of the selection).
Anchor and
focus
define the direction of the selection, which is important when expanding/shrinking selection. The focus moves, while the anchor should remain in the same place.Anchor is always set to the start or end position of the last of selection's ranges. Whether it is the
start
orend
depends on the specifiedoptions.backward
. See thesetTo()
method.May be set to
null
if there are no ranges in the selection.Related:
-
Selection focus. Focus is the position where the selection ends. If a user is making a selection by dragging the mouse, the focus is where the mouse cursor is.
-
isBackward : Boolean
module:engine/model/selection~Selection#isBackward
readonly
-
isCollapsed : Boolean
module:engine/model/selection~Selection#isCollapsed
readonly
Whether the selection is collapsed. Selection is collapsed when there is exactly one range in it and it is collapsed.
-
rangeCount : Number
module:engine/model/selection~Selection#rangeCount
readonly
Returns the number of ranges in the selection.
-
_attrs : Map.<String, *>
module:engine/model/selection~Selection#_attrs
protected
List of attributes set on current selection.
-
Stores selection ranges.
-
_lastRangeBackward : Boolean
module:engine/model/selection~Selection#_lastRangeBackward
private
Specifies whether the last added range was added as a backward or forward range.
Methods
-
constructor( [ selectable ], [ placeOrOffset ], [ options ] = { [options.backward] } )
module:engine/model/selection~Selection#constructor
Creates a new selection instance based on the given selectable or creates an empty selection if no arguments were passed.
// Creates empty selection without ranges. const selection = writer.createSelection(); // Creates selection at the given range. const range = writer.createRange( start, end ); const selection = writer.createSelection( range ); // Creates selection at the given ranges const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ]; const selection = writer.createSelection( ranges ); // Creates selection from the other selection. // Note: It doesn't copies selection attributes. const otherSelection = writer.createSelection(); const selection = writer.createSelection( otherSelection ); // Creates selection from the given document selection. // Note: It doesn't copies selection attributes. const documentSelection = model.document.selection; const selection = writer.createSelection( documentSelection ); // Creates selection at the given position. const position = writer.createPositionFromPath( root, path ); const selection = writer.createSelection( position ); // Creates selection at the given offset in the given element. const paragraph = writer.createElement( 'paragraph' ); const selection = writer.createSelection( paragraph, offset ); // Creates a range inside an element which starts before the // first child of that element and ends after the last child of that element. const selection = writer.createSelection( paragraph, 'in' ); // Creates a range on an item which starts before the item and ends // just after the item. const selection = writer.createSelection( paragraph, 'on' );
Selection's constructor allow passing additional options (
'backward'
) as the last argument.// Creates backward selection. const selection = writer.createSelection( range, { backward: true } );
Parameters
[ selectable ] : Selectable
[ placeOrOffset ] : Number | 'before' | 'end' | 'after' | 'on' | 'in'
Sets place or offset of the selection.
[ options ] : Object
-
Properties
[ options.backward ] : Boolean
Sets this selection instance to be backward.
-
containsEntireContent( [ element ] ) → Boolean
module:engine/model/selection~Selection#containsEntireContent
Checks whether the selection contains the entire content of the given element. This means that selection must start at a position touching the element's start and ends at position touching the element's end.
By default, this method will check whether the entire content of the selection's current root is selected. Useful to check if e.g. the user has just pressed Ctrl + A.
Parameters
[ element ] : Element
-
Defaults to
this.anchor.root
Returns
Boolean
-
delegate( events ) → EmitterMixinDelegateChain
module:engine/model/selection~Selection#delegate
mixed
Delegates selected events to another
Emitter
. For instance:emitterA.delegate( 'eventX' ).to( emitterB ); emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
then
eventX
is delegated (fired by)emitterB
andemitterC
along withdata
:emitterA.fire( 'eventX', data );
and
eventY
is delegated (fired by)emitterC
along withdata
:emitterA.fire( 'eventY', data );
Parameters
events : String
Event names that will be delegated to another emitter.
Returns
-
fire( eventOrInfo, [ args ] ) → *
module:engine/model/selection~Selection#fire
mixed
Fires an event, executing all callbacks registered for it.
The first parameter passed to callbacks is an
EventInfo
object, followed by the optionalargs
provided in thefire()
method call.Parameters
eventOrInfo : String | EventInfo
The name of the event or
EventInfo
object if event is delegated.[ args ] : *
Additional arguments to be passed to the callbacks.
Returns
*
By default the method returns
undefined
. However, the return value can be changed by listeners through modification of theevt.return
's property (the event info is the first param of every callback).
-
getAttribute( key ) → *
module:engine/model/selection~Selection#getAttribute
Gets an attribute value for given key or
undefined
if that attribute is not set on the selection.Parameters
key : String
Key of attribute to look for.
Returns
*
Attribute value or
undefined
.
-
getAttributeKeys() → Iterable.<String>
module:engine/model/selection~Selection#getAttributeKeys
Returns iterable that iterates over this selection's attribute keys.
Returns
Iterable.<String>
-
getAttributes() → Iterable.<*>
module:engine/model/selection~Selection#getAttributes
Returns iterable that iterates over this selection's attributes.
Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value. This format is accepted by native
Map
object and also can be passed inNode
constructor.Returns
Iterable.<*>
-
getFirstPosition() → Position | null
module:engine/model/selection~Selection#getFirstPosition
Returns the first position in the selection. First position is the position that is before any other position in the selection.
-
getFirstRange() → Range | null
module:engine/model/selection~Selection#getFirstRange
-
getLastPosition() → Position | null
module:engine/model/selection~Selection#getLastPosition
Returns the last position in the selection. Last position is the position that is after any other position in the selection.
-
getLastRange() → Range | null
module:engine/model/selection~Selection#getLastRange
-
Returns an iterable object that iterates over copies of selection ranges.
Returns
Iterable.<Range>
-
getSelectedBlocks() → Iterable.<Element>
module:engine/model/selection~Selection#getSelectedBlocks
Gets elements of type "block" touched by the selection.
This method's result can be used for example to apply block styling to all blocks covered by this selection.
Note:
getSelectedBlocks()
returns blocks that are nested in other non-block elements but will not return blocks nested in other blocks.In this case the function will return exactly all 3 paragraphs (note:
<blockQuote>
is not a block itself):<paragraph>[a</paragraph> <blockQuote> <paragraph>b</paragraph> </blockQuote> <paragraph>c]d</paragraph>
In this case the paragraph will also be returned, despite the collapsed selection:
<paragraph>[]a</paragraph>
In such a scenario, however, only blocks A, B & E will be returned as blocks C & D are nested in block B:
[<blockA></blockA> <blockB> <blockC></blockC> <blockD></blockD> </blockB> <blockE></blockE>]
If the selection is inside a block all the inner blocks (A & B) are returned:
<block> <blockA>[a</blockA> <blockB>b]</blockB> </block>
Special case: If a selection ends at the beginning of a block, that block is not returned as from user perspective this block wasn't selected. See #984 for more details.
<paragraph>[a</paragraph> <paragraph>b</paragraph> <paragraph>]c</paragraph> // this block will not be returned
Returns
Iterable.<Element>
-
getSelectedElement() → Element | null
module:engine/model/selection~Selection#getSelectedElement
-
hasAttribute( key ) → Boolean
module:engine/model/selection~Selection#hasAttribute
Checks if the selection has an attribute for given key.
Parameters
key : String
Key of attribute to check.
Returns
Boolean
true
if attribute with given key is set on selection,false
otherwise.
-
is( type ) → Boolean
module:engine/model/selection~Selection#is
Checks whether this object is of the given.
selection.is( 'selection' ); // -> true selection.is( 'model:selection' ); // -> true selection.is( 'view:selection' ); // -> false selection.is( 'range' ); // -> false
Check the entire list of model objects which implement the
is()
method.Parameters
type : String
Returns
Boolean
-
isEqual( otherSelection ) → Boolean
module:engine/model/selection~Selection#isEqual
Checks whether this selection is equal to the given selection. Selections are equal if they have the same directions, the same number of ranges and all ranges from one selection equal to ranges from the another selection.
Parameters
otherSelection : Selection | DocumentSelection
Selection to compare with.
Returns
Boolean
true
if selections are equal,false
otherwise.
-
listenTo( emitter, event, callback, [ options ] = { [options.priority] } )
module:engine/model/selection~Selection#listenTo
mixed
Registers a callback function to be executed when an event is fired in a specific (emitter) object.
Events can be grouped in namespaces using
:
. When namespaced event is fired, it additionally fires all callbacks for that namespace.// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ). myEmitter.on( 'myGroup', genericCallback ); myEmitter.on( 'myGroup:myEvent', specificCallback ); // genericCallback is fired. myEmitter.fire( 'myGroup' ); // both genericCallback and specificCallback are fired. myEmitter.fire( 'myGroup:myEvent' ); // genericCallback is fired even though there are no callbacks for "foo". myEmitter.fire( 'myGroup:foo' );
An event callback can stop the event and set the return value of the
fire
method.Parameters
emitter : Emitter
The object that fires the event.
event : String
The name of the event.
callback : function
The function to be called on event.
[ options ] : Object
Additional options.
Properties[ options.priority ] : PriorityString | Number
The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.
Defaults to
'normal'
Defaults to
{}
-
off( event, callback )
module:engine/model/selection~Selection#off
mixed
Stops executing the callback on the given event. Shorthand for
this.stopListening( this, event, callback )
.Parameters
event : String
The name of the event.
callback : function
The function to stop being called.
-
on( event, callback, [ options ] = { [options.priority] } )
module:engine/model/selection~Selection#on
mixed
Registers a callback function to be executed when an event is fired.
Shorthand for
this.listenTo( this, event, callback, options )
(it makes the emitter listen on itself).Parameters
event : String
The name of the event.
callback : function
The function to be called on event.
[ options ] : Object
Additional options.
Properties[ options.priority ] : PriorityString | Number
The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.
Defaults to
'normal'
Defaults to
{}
-
once( event, callback, [ options ] = { [options.priority] } )
module:engine/model/selection~Selection#once
mixed
Registers a callback function to be executed on the next time the event is fired only. This is similar to calling
on
followed byoff
in the callback.Parameters
event : String
The name of the event.
callback : function
The function to be called on event.
[ options ] : Object
Additional options.
Properties[ options.priority ] : PriorityString | Number
The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.
Defaults to
'normal'
Defaults to
{}
-
removeAttribute( key )
module:engine/model/selection~Selection#removeAttribute
Removes an attribute with given key from the selection.
If given attribute was set on the selection, fires the
event-change:range
event with removed attribute key.Parameters
key : String
Key of attribute to remove.
Fires
-
setAttribute( key, value )
module:engine/model/selection~Selection#setAttribute
Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
If the attribute value has changed, fires the
event-change:range
event with the attribute key.Parameters
key : String
Key of attribute to set.
value : *
Attribute value.
Fires
-
setFocus( itemOrPosition, [ offset ] )
module:engine/model/selection~Selection#setFocus
Moves
focus
to the specified location.The location can be specified in the same form as writer.createPositionAt() parameters.
Parameters
itemOrPosition : Item | Position
[ offset ] : Number | 'end' | 'before' | 'after'
Offset or one of the flags. Used only when first parameter is a model item.
Fires
-
setTo( selectable, [ placeOrOffset ], [ options ] = { [options.backward] } )
module:engine/model/selection~Selection#setTo
Sets this selection's ranges and direction to the specified location based on the given selectable.
// Removes all selection's ranges. selection.setTo( null ); // Sets selection to the given range. const range = writer.createRange( start, end ); selection.setTo( range ); // Sets selection to given ranges. const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ]; selection.setTo( ranges ); // Sets selection to other selection. // Note: It doesn't copies selection attributes. const otherSelection = writer.createSelection(); selection.setTo( otherSelection ); // Sets selection to the given document selection. // Note: It doesn't copies selection attributes. const documentSelection = new DocumentSelection( doc ); selection.setTo( documentSelection ); // Sets collapsed selection at the given position. const position = writer.createPositionFromPath( root, path ); selection.setTo( position ); // Sets collapsed selection at the position of the given node and an offset. selection.setTo( paragraph, offset );
Creates a range inside an element which starts before the first child of that element and ends after the last child of that element.
selection.setTo( paragraph, 'in' );
Creates a range on an item which starts before the item and ends just after the item.
selection.setTo( paragraph, 'on' );
Selection#setTo()
' method allow passing additional options (backward
) as the last argument.// Sets backward selection. const selection = writer.createSelection( range, { backward: true } );
Parameters
selectable : Selectable
[ placeOrOffset ] : Number | 'before' | 'end' | 'after' | 'on' | 'in'
Sets place or offset of the selection.
[ options ] : Object
-
Properties
[ options.backward ] : Boolean
Sets this selection instance to be backward.
-
stopDelegating( [ event ], [ emitter ] )
module:engine/model/selection~Selection#stopDelegating
mixed
Stops delegating events. It can be used at different levels:
- To stop delegating all events.
- To stop delegating a specific event to all emitters.
- To stop delegating a specific event to a specific emitter.
Parameters
[ event ] : String
The name of the event to stop delegating. If omitted, stops it all delegations.
[ emitter ] : Emitter
(requires
event
) The object to stop delegating a particular event to. If omitted, stops delegation ofevent
to all emitters.
-
stopListening( [ emitter ], [ event ], [ callback ] )
module:engine/model/selection~Selection#stopListening
mixed
Stops listening for events. It can be used at different levels:
- To stop listening to a specific callback.
- To stop listening to a specific event.
- To stop listening to all events fired by a specific object.
- To stop listening to all events fired by all objects.
Parameters
[ emitter ] : Emitter
The object to stop listening to. If omitted, stops it for all objects.
[ event ] : String
(Requires the
emitter
) The name of the event to stop listening to. If omitted, stops it for all events fromemitter
.[ callback ] : function
(Requires the
event
) The function to be removed from the call list for the givenevent
.
-
_addEventListener( event, callback, [ options ] = { [options.priority] } )
module:engine/model/selection~Selection#_addEventListener
protected mixed
Adds callback to emitter for given event.
Parameters
event : String
The name of the event.
callback : function
The function to be called on event.
[ options ] : Object
Additional options.
Properties[ options.priority ] : PriorityString | Number
The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.
Defaults to
'normal'
Defaults to
{}
-
_checkRange( range )
module:engine/model/selection~Selection#_checkRange
protected
Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
Parameters
range : Range
Range to check.
-
_popRange()
module:engine/model/selection~Selection#_popRange
protected
Removes most recently added range from the selection.
-
_pushRange( range )
module:engine/model/selection~Selection#_pushRange
protected
Adds given range to internal ranges array. Throws an error if given range is intersecting with any range that is already stored in this selection.
Parameters
range : Range
Range to add.
-
_removeAllRanges()
module:engine/model/selection~Selection#_removeAllRanges
protected
Deletes ranges from internal range array. Uses _popRange to ensure proper ranges removal.
-
_removeEventListener( event, callback )
module:engine/model/selection~Selection#_removeEventListener
protected mixed
Removes callback from emitter for given event.
Parameters
event : String
The name of the event.
callback : function
The function to stop being called.
-
_setRanges( newRanges, [ isLastBackward ] )
module:engine/model/selection~Selection#_setRanges
protected
Replaces all ranges that were added to the selection with given array of ranges. Last range of the array is treated like the last added range and is used to set
anchor
andfocus
. Accepts a flag describing in which direction the selection is made.Parameters
newRanges : Iterable.<Range>
Ranges to set.
[ isLastBackward ] : Boolean
Flag describing if last added range was selected forward - from start to end (
false
) or backward - from end to start (true
).Defaults to
false
Fires
Events
-
change:attribute( eventInfo, directChange, attributeKeys )
module:engine/model/selection~Selection#event:change:attribute
Fired when selection attribute changed.
Parameters
eventInfo : EventInfo
An object containing information about the fired event.
directChange : Boolean
In case of
Selection
class it is always set totrue
which indicates that the selection change was caused by a direct use of selection's API. TheDocumentSelection
, however, may change because its attributes were directly changed through the writer or because its position was changed in the model and its attributes were refreshed (which means an indirect change). The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live") which mean that they are not updated once the document changes.attributeKeys : Array.<String>
Array containing keys of attributes that changed.
-
change:range( eventInfo, directChange )
module:engine/model/selection~Selection#event:change:range
Fired when selection range(s) changed.
Parameters
eventInfo : EventInfo
An object containing information about the fired event.
directChange : Boolean
In case of
Selection
class it is always set totrue
which indicates that the selection change was caused by a direct use of selection's API. TheDocumentSelection
, however, may change because its position was directly changed through the writer or because its position was changed because the structure of the model has been changed (which means an indirect change). The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live") which mean that they are not updated once the document changes.
Every day, we work hard to keep our documentation complete. Have you spotted an outdated information? Is something missing? Please report it via our issue tracker.