DowncastDispatcher
The downcast dispatcher is a central point of downcasting (conversion from the model to the view), which is a process of reacting to changes in the model and firing a set of events. The callbacks listening to these events are called converters. The converters' role is to convert the model changes to changes in view (for example, adding view nodes or changing attributes on view elements).
During the conversion process, downcast dispatcher fires events basing on the state of the model and prepares data for these events. It is important to understand that the events are connected with the changes done on the model, for example: "a node has been inserted" or "an attribute has changed". This is in contrary to upcasting (a view-to-model conversion) where you convert the view state (view nodes) to a model tree.
The events are prepared basing on a diff created by the Differ, which buffers them and then passes to the downcast dispatcher as a diff between the old model state and the new model state.
Note that because the changes are converted, there is a need to have a mapping between the model structure and the view structure.
To map positions and elements during the downcast (a model-to-view conversion), use Mapper.
Downcast dispatcher fires the following events for model tree changes:
insert– If a range of nodes was inserted to the model tree.remove– If a range of nodes was removed from the model tree.attribute– If an attribute was added, changed or removed from a model node.
For insert
and attribute,
the downcast dispatcher generates consumables.
These are used to have control over which changes have already been consumed. It is useful when some converters
overwrite others or convert multiple changes (for example, it converts an insertion of an element and also converts that
element's attributes during the insertion).
Additionally, downcast dispatcher fires events for marker changes:
addMarker– If a marker was added.removeMarker– If a marker was removed.
Note that changing a marker is done through removing the marker from the old range and adding it to the new range, so both of these events are fired.
Finally, a downcast dispatcher also handles firing events for the model selection conversion:
selection– Converts the selection from the model to the view.attribute– Fired for every selection attribute.addMarker– Fired for every marker that contains a selection.
Unlike the model tree and the markers, the events for selection are not fired for changes but for a selection state.
When providing custom listeners for a downcast dispatcher, remember to check whether a given change has not been consumed yet.
When providing custom listeners for a downcast dispatcher, keep in mind that you should not stop the event. If you stop it,
then the default converter at the lowest priority will not trigger the conversion of this node's attributes and child nodes.
When providing custom listeners for a downcast dispatcher, remember to use the provided view downcast writer to apply changes to the view document.
You can read more about conversion in the following guide:
An example of a custom converter for the downcast dispatcher:
// You will convert inserting a "paragraph" model element into the model.
downcastDispatcher.on( 'insert:paragraph', ( evt, data, conversionApi ) => {
// Remember to check whether the change has not been consumed yet and consume it.
if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
return;
}
// Translate the position in the model to a position in the view.
const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
// Create a <p> element that will be inserted into the view at the `viewPosition`.
const viewElement = conversionApi.writer.createContainerElement( 'p' );
// Bind the newly created view element to the model element so positions will map accordingly in the future.
conversionApi.mapper.bindElements( data.item, viewElement );
// Add the newly created view element to the view.
conversionApi.writer.insert( viewPosition, viewElement );
} );
Properties
-
_conversionApi : Pick<DowncastConversionApi, 'dispatcher' | 'mapper' | 'schema'>internalreadonlymodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_conversionApiA template for an interface passed by the dispatcher to the event callbacks.
-
_firedEventsMap : WeakMap<DowncastConversionApi, Map<unknown, Set<string>>>privatereadonlymodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_firedEventsMapA map of already fired events for a given
ModelConsumable.
Methods
-
constructor( conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#constructorCreates a downcast dispatcher instance.
Parameters
conversionApi : Pick<DowncastConversionApi, 'mapper' | 'schema'>Additional properties for an interface that will be passed to events fired by the downcast dispatcher.
Related:
-
convert( range, markers, writer, options ) → voidmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#convertStarts a conversion of a model range and the provided markers.
Parameters
range : ModelRangeThe inserted range.
markers : Map<string, ModelRange>The map of markers that should be down-casted.
writer : ViewDowncastWriterThe view writer that should be used to modify the view document.
options : Record<string, unknown>Optional options object passed to
convertionApi.options.Defaults to
{}
Returns
void
Fires
-
convertChanges( differ, markers, writer ) → voidmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#convertChangesConverts changes buffered in the given model differ and fires conversion events based on it.
Parameters
differ : DifferThe differ object with buffered changes.
markers : MarkerCollectionMarkers related to the model fragment to convert.
writer : ViewDowncastWriterThe view writer that should be used to modify the view document.
Returns
void
Fires
-
convertSelection( selection, markers, writer ) → voidmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#convertSelectionStarts the model selection conversion.
Fires events for a given selection to start the selection conversion.
Parameters
selection : ModelSelection | ModelDocumentSelectionThe selection to convert.
markers : MarkerCollectionMarkers connected with the converted model.
writer : ViewDowncastWriterView writer that should be used to modify the view document.
Returns
void
Fires
-
delegate( events ) → EmitterMixinDelegateChaininheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#delegateDelegates selected events to another
Emitter. For instance:emitterA.delegate( 'eventX' ).to( emitterB ); emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );Copy codethen
eventXis delegated (fired by)emitterBandemitterCalong withdata:emitterA.fire( 'eventX', data );Copy codeand
eventYis delegated (fired by)emitterCalong withdata:emitterA.fire( 'eventY', data );Copy codeParameters
events : Array<string>Event names that will be delegated to another emitter.
Returns
-
fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]inheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#fireFires an event, executing all callbacks registered for it.
The first parameter passed to callbacks is an
EventInfoobject, followed by the optionalargsprovided in thefire()method call.Type parameters
Parameters
eventOrInfo : GetNameOrEventInfo<TEvent>The name of the event or
EventInfoobject if event is delegated.args : TEvent[ 'args' ]Additional arguments to be passed to the callbacks.
Returns
GetEventInfo<TEvent>[ 'return' ]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).
-
listenTo( emitter, event, callback, [ options ] ) → voidinheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#listenTo:BASE_EMITTERRegisters 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' );Copy codeAn event callback can stop the event and set the return value of the
firemethod.Type parameters
Parameters
emitter : EmitterThe object that fires the event.
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
-
off( event, callback ) → voidinheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#offStops executing the callback on the given event. Shorthand for
this.stopListening( this, event, callback ).Parameters
event : stringThe name of the event.
callback : FunctionThe function to stop being called.
Returns
void
-
on( event, callback, [ options ] ) → voidinheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#onRegisters 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).Type parameters
Parameters
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
-
once( event, callback, [ options ] ) → voidinheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#onceRegisters a callback function to be executed on the next time the event is fired only. This is similar to calling
onfollowed byoffin the callback.Type parameters
Parameters
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
-
stopDelegating( [ event ], [ emitter ] ) → voidinheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#stopDelegatingStops 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 ] : stringThe 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 ofeventto all emitters.
Returns
void
-
stopListening( [ emitter ], [ event ], [ callback ] ) → voidinheritedmodule:engine/conversion/downcastdispatcher~DowncastDispatcher#stopListening:BASE_STOPStops 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 ] : EmitterThe 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.
Returns
void
-
_addConsumablesForInsert( consumable, walkerValues ) → ModelConsumableprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_addConsumablesForInsertPopulates provided
ModelConsumablewith values to consume from a given range, assuming that the range has just been inserted to the model.Parameters
consumable : ModelConsumableThe consumable.
walkerValues : Iterable<ModelTreeWalkerValue>The walker values for the inserted range.
Returns
ModelConsumableThe values to consume.
-
_addConsumablesForRange( consumable, range, type ) → ModelConsumableprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_addConsumablesForRangePopulates provided
ModelConsumablewith values to consume for a given range.Parameters
consumable : ModelConsumableThe consumable.
range : ModelRangeThe affected range.
type : stringConsumable type.
Returns
ModelConsumableThe values to consume.
-
_addConsumablesForSelection( consumable, selection, markers ) → ModelConsumableprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_addConsumablesForSelectionPopulates provided
ModelConsumablewith selection consumable values.Parameters
consumable : ModelConsumableThe consumable.
selection : ModelSelection | ModelDocumentSelectionThe selection to create the consumable from.
markers : Iterable<Marker>Markers that contain the selection.
Returns
ModelConsumableThe values to consume.
-
_convertAttribute( range, key, oldValue, newValue, conversionApi ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_convertAttributeStarts a conversion of an attribute change on a given
range.For each node in the given
range, attribute event is fired with the passed data.Parameters
range : ModelRangeChanged range.
key : stringKey of the attribute that has changed.
oldValue : unknownAttribute value before the change or
nullif the attribute has not been set before.newValue : unknownNew attribute value or
nullif the attribute has been removed.conversionApi : DowncastConversionApiThe conversion API object.
Returns
void
Fires
-
_convertInsert( range, conversionApi, options = { [options.doNotAddConsumables] } ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_convertInsertFires insertion conversion of a range of nodes.
For each node in the range,
insertevent is fired. For each attribute on each node,attributeevent is fired.Parameters
range : ModelRangeThe inserted range.
conversionApi : DowncastConversionApiThe conversion API object.
options : object-
Properties
[ options.doNotAddConsumables ] : booleanWhether the ModelConsumable should not get populated for items in the provided range.
Defaults to
{}
Returns
void
Fires
-
_convertMarkerAdd( markerName, markerRange, conversionApi ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_convertMarkerAddConverts the added marker. Fires the
addMarkerevent for each item in the marker's range. If the range is collapsed, a single event is dispatched. See the event description for more details.Parameters
markerName : stringMarker name.
markerRange : ModelRangeThe marker range.
conversionApi : DowncastConversionApiThe conversion API object.
Returns
void
Fires
-
_convertMarkerRemove( markerName, markerRange, conversionApi ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_convertMarkerRemoveFires the conversion of the marker removal. Fires the
removeMarkerevent with the provided data.Parameters
markerName : stringMarker name.
markerRange : ModelRangeThe marker range.
conversionApi : DowncastConversionApiThe conversion API object.
Returns
void
Fires
-
_convertReinsert( range, conversionApi ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_convertReinsertFires re-insertion conversion (with a
reconversionflag passed toinsertevents) of a range of elements (only elements on the range depth, without children).For each node in the range on its depth (without children),
insertevent is fired. For each attribute on each node,attributeevent is fired.Parameters
range : ModelRangeThe range to reinsert.
conversionApi : DowncastConversionApiThe conversion API object.
Returns
void
Fires
-
_convertRemove( position, length, name, conversionApi ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_convertRemoveFires conversion of a single node removal. Fires remove event with provided data.
Parameters
position : ModelPositionPosition from which node was removed.
length : numberOffset size of removed node.
name : stringName of removed node.
conversionApi : DowncastConversionApiThe conversion API object.
Returns
void
-
_createConversionApi( writer, refreshedItems, options ) → DowncastConversionApiprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_createConversionApiBuilds an instance of the
DowncastConversionApifrom a template and a givenViewDowncastWriterand options object.Parameters
writer : ViewDowncastWriterView writer that should be used to modify the view document.
refreshedItems : Set<ModelItem>A set of model elements that should not reuse their previous view representations.
Defaults to
...options : Record<string, unknown>Optional options passed to
convertionApi.options.Defaults to
{}
Returns
DowncastConversionApiThe conversion API object.
-
_reduceChanges( changes ) → Iterable<DifferItem | DifferItemReinsert>privatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_reduceChangesFires the reduction of changes buffered in the
Differ.Features can replace selected
DifferItems withreinsertentries to trigger reconversion. TheDowncastHelpers.elementToStructure()is using this event to trigger reconversion.Parameters
changes : Iterable<DifferItem>
Returns
Iterable<DifferItem | DifferItemReinsert>
Fires
-
_testAndFire( type, data, conversionApi ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_testAndFireTests whether given event wasn't already fired and if so, fires it.
Type parameters
TType
Parameters
type : TType | `${ TType }:${ string }`Event type.
data : DowncastDispatcherEventMap<ModelItem>[ TType ]Event data.
conversionApi : DowncastConversionApiThe conversion API object.
Returns
void
Fires
-
_testAndFireAddAttributes( item, conversionApi ) → voidprivatemodule:engine/conversion/downcastdispatcher~DowncastDispatcher#_testAndFireAddAttributesFires not already fired events for setting attributes on just inserted item.
Parameters
item : ModelItemThe model item to convert attributes for.
conversionApi : DowncastConversionApiThe conversion API object.
Returns
void
Events
-
addMarker( eventInfo, data, conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarkerFired when a new marker is added to the model. Also fired when a collapsed model selection that is inside a marker is converted.
addMarkeris a namespace for a class of events. Names of actually called events follow this pattern:addMarker:markerName. By specifying certain marker names, you can make the events even more gradual. For example, if markers are namedfoo:abc,foo:bar, then it is possible to listen toaddMarker:foooraddMarker:foo:abcandaddMarker:foo:barevents.If the marker range is not collapsed:
- the event is fired for each item in the marker range one by one,
conversionApi.consumableincludes each item of the marker range and the consumable value is same as the event name.
If the marker range is collapsed:
- there is only one event,
conversionApi.consumableincludes marker range with the event name.
If the selection inside a marker is converted:
- there is only one event,
conversionApi.consumableincludes the selection instance with the event name.
Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastDispatcherEventMap<TItem>[ TName ]Additional information about the change.
conversionApi : DowncastConversionApiConversion interface to be used by callback, passed in
DowncastDispatcherconstructor.
-
attribute( eventInfo, data, conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attributeFired in the following cases:
- when an attribute has been added, changed, or removed from a node,
- when a node with an attribute is inserted,
- when a collapsed model selection attribute is converted.
attributeis a namespace for a class of events. Names of actually called events follow this pattern:attribute:attributeKey:name.attributeKeyis the key of added/changed/removed attribute.nameis either'$text'if change was on a text node, or the name of element which attribute has changed.This way listeners can either listen to a general
attribute:boldevent or specific event (for exampleattribute:src:imageBlock).Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastDispatcherEventMap<TItem>[ TName ]Additional information about the change.
conversionApi : DowncastConversionApiConversion interface to be used by callback, passed in
DowncastDispatcherconstructor.
-
cleanSelection( eventInfo, data, conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:cleanSelectionFired at the beginning of selection conversion, before selection events.
Should be used to clean up the view state at the current selection position, before the selection is moved to another place.
Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastDispatcherEventMap<TItem>[ TName ]conversionApi : DowncastConversionApiConversion interface to be used by callback, passed in
DowncastDispatcherconstructor.
-
insert( eventInfo, data, conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insertFired for inserted nodes.
insertis a namespace for a class of events. Names of actually called events follow this pattern:insert:name.nameis either'$text', when a text node has been inserted, or name of inserted element.This way, the listeners can either listen to a general
insertevent or specific event (for exampleinsert:paragraph).Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastDispatcherEventMap<TItem>[ TName ]Additional information about the change.
conversionApi : DowncastConversionApiConversion interface to be used by callback, passed in the
DowncastDispatcherconstructor.
-
reduceChanges( eventInfo, data )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:reduceChangesFired to enable reducing (transforming) changes buffered in the
DifferbeforeconvertChanges()will fire any conversion events.For instance, a feature can replace selected
DifferItems with areinsertentry to trigger reconversion of an element when e.g. its attribute has changes. The *DowncastHelpers.elementToStructure()helper is using this event to trigger reconversion of an element when the element, its attributes or direct children changed.Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastReduceChangesEventData
-
remove( eventInfo, data, conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:removeFired for removed nodes.
removeis a namespace for a class of events. Names of actually called events follow this pattern:remove:name.nameis either'$text', when a a text node has been removed, or the name of removed element.This way, listeners can either listen to a general
removeevent or specific event (for exampleremove:paragraph).Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastDispatcherEventMap<TItem>[ TName ]Additional information about the change.
conversionApi : DowncastConversionApiConversion interface to be used by callback, passed in
DowncastDispatcherconstructor.
-
removeMarker( eventInfo, data, conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:removeMarkerFired when a marker is removed from the model.
removeMarkeris a namespace for a class of events. Names of actually called events follow this pattern:removeMarker:markerName. By specifying certain marker names, you can make the events even more gradual. For example, if markers are namedfoo:abc,foo:bar, then it is possible to listen toremoveMarker:fooorremoveMarker:foo:abcandremoveMarker:foo:barevents.Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastDispatcherEventMap<TItem>[ TName ]Additional information about the change.
conversionApi : DowncastConversionApiConversion interface to be used by callback, passed in
DowncastDispatcherconstructor.
-
selection( eventInfo, data, conversionApi )module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:selectionFired for selection changes.
Parameters
eventInfo : EventInfoAn object containing information about the fired event.
data : DowncastDispatcherEventMap<TItem>[ TName ]conversionApi : DowncastConversionApiConversion interface to be used by callback, passed in
DowncastDispatcherconstructor.