Document (engine/model)
@ckeditor/ckeditor5-engine/src/model/document
Data model's document. It contains the model's structure, its selection and the history of changes.
Read more about working with the model in introduction to the the editing engine's architecture.
Usually, the document contains just one root element, so
you can retrieve it by just calling getRoot without specifying its name:
model.document.getRoot(); // -> returns the main root
However, the document may contain multiple roots – e.g. when the editor has multiple editable areas (e.g. a title and a body of a message).
Filtering
Properties
-
The model differ object. Its role is to buffer changes done on the model document and then calculate a diff of those changes.
-
The graveyard tree root. A document always has a graveyard root that stores removed nodes.
-
The document's history.
-
Defines whether the document is in a read-only mode.
The user should not be able to change the data of a document that is read-only.
-
The model that the document is a part of.
-
A list of roots that are owned and managed by this document. Use
createRoot,getRootandgetRootNamesto manipulate it. -
The selection in this document.
-
version : numbermodule:engine/model/document~Document#versionThe document version. Every applied operation increases the version number. It is used to ensure that operations are applied on a proper document version.
This property is equal to
model.Document#history#version.If the base version does not match the document version, a model-document-applyoperation-wrong-version error is thrown.
Parameters
version : number
-
private
_hasSelectionChangedFromTheLastChangeBlock : booleanmodule:engine/model/document~Document#_hasSelectionChangedFromTheLastChangeBlockA flag that indicates whether the selection has changed since last change block.
-
Post-fixer callbacks registered to the model document.
Methods
-
constructor( model )module:engine/model/document~Document#constructorCreates an empty document instance with no
roots(other than the graveyard root).Parameters
model : Model
-
createRoot( elementName, rootName ) → RootElementmodule:engine/model/document~Document#createRootCreates a new root.
Note: do not use this method after the editor has been initialized! If you want to dynamically add a root, use
model.Writer#addRootinstead.Parameters
elementName : stringThe element name. Defaults to
'$root'which also has some basic schema defined (e.g.$blockelements are allowed inside the$root). Make sure to define a proper schema if you use a different name.Defaults to
'$root'rootName : stringA unique root name.
Defaults to
'main'
Returns
RootElementThe created root.
-
inherited
delegate( events ) → EmitterMixinDelegateChainmodule:engine/model/document~Document#delegateDelegates selected events to another
Emitter. For instance:emitterA.delegate( 'eventX' ).to( emitterB ); emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );then
eventXis delegated (fired by)emitterBandemitterCalong withdata:emitterA.fire( 'eventX', data );and
eventYis delegated (fired by)emitterCalong withdata:emitterA.fire( 'eventY', data );Parameters
events : Array<string>Event names that will be delegated to another emitter.
Returns
-
destroy() → voidmodule:engine/model/document~Document#destroy -
inherited
fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]module:engine/model/document~Document#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).
-
getRoot( name ) → null | RootElementmodule:engine/model/document~Document#getRootReturns a root by its name.
Detached roots are returned by this method. This is to be able to operate on the detached root (for example, to be able to create a position inside such a root for undo feature purposes).
Parameters
name : stringThe root name of the root to return.
Defaults to
'main'
Returns
null | RootElementThe root registered under a given name or
nullwhen there is no root with the given name.
-
getRootNames( includeDetached ) → Array<string>module:engine/model/document~Document#getRootNamesReturns an array with names of all roots added to the document (except the graveyard root).
Detached roots are not returned by this method by default. This is to make sure that all features or algorithms that operate on the document data know which roots are still a part of the document and should be processed.
Parameters
includeDetached : booleanSpecified whether detached roots should be returned as well.
Defaults to
false
Returns
Array<string>
-
getRoots( includeDetached ) → Array<RootElement>module:engine/model/document~Document#getRootsReturns an array with all roots added to the document (except the graveyard root).
Detached roots are not returned by this method by default. This is to make sure that all features or algorithms that operate on the document data know which roots are still a part of the document and should be processed.
Parameters
includeDetached : booleanSpecified whether detached roots should be returned as well.
Defaults to
false
Returns
Array<RootElement>
-
inherited
listenTo( emitter, event, callback, [ options ] ) → voidmodule:engine/model/document~Document#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' );An 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
-
Stops 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
-
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).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
-
Registers 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
-
registerPostFixer( postFixer ) → voidmodule:engine/model/document~Document#registerPostFixerUsed to register a post-fixer callback. A post-fixer mechanism guarantees that the features will operate on a correct model state.
An execution of a feature may lead to an incorrect document tree state. The callbacks are used to fix the document tree after it has changed. Post-fixers are fired just after all changes from the outermost change block were applied but before the change event is fired. If a post-fixer callback made a change, it should return
true. When this happens, all post-fixers are fired again to check if something else should not be fixed in the new document tree state.As a parameter, a post-fixer callback receives a writer instance connected with the executed changes block. Thanks to that, all changes done by the callback will be added to the same batch (and undo step) as the original changes. This makes post-fixer changes transparent for the user.
An example of a post-fixer is a callback that checks if all the data were removed from the editor. If so, the callback should add an empty paragraph so that the editor is never empty:
document.registerPostFixer( writer => { const changes = document.differ.getChanges(); // Check if the changes lead to an empty root in the editor. for ( const entry of changes ) { if ( entry.type == 'remove' && entry.position.root.isEmpty ) { writer.insertElement( 'paragraph', entry.position.root, 0 ); // It is fine to return early, even if multiple roots would need to be fixed. // All post-fixers will be fired again, so if there are more empty roots, those will be fixed, too. return true; } } return false; } );Parameters
postFixer : ModelPostFixer
Returns
void
-
inherited
stopDelegating( [ event ], [ emitter ] ) → voidmodule:engine/model/document~Document#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
-
inherited
stopListening( [ emitter ], [ event ], [ callback ] ) → voidmodule:engine/model/document~Document#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
-
toJSON() → unknownmodule:engine/model/document~Document#toJSONA custom
toJSON()method to solve child-parent circular dependencies.Returns
unknownA clone of this object with the document property changed to a string.
-
Returns the default range for this selection. The default range is a collapsed range that starts and ends at the beginning of this selection's document default root.
Returns
-
internal
_handleChangeBlock( writer ) → voidmodule:engine/model/document~Document#_handleChangeBlockCheck if there were any changes done on document, and if so, call post-fixers, fire
changeevent for features and conversion and then reset the differ. Firechange:dataevent when at least one operation or buffered marker changes the data.Parameters
writer : WriterThe writer on which post-fixers will be called.
Returns
void
Fires
-
internal
_validateSelectionRange( range ) → booleanmodule:engine/model/document~Document#_validateSelectionRangeChecks whether a given range is a valid range for the document's selection.
Parameters
range : RangeA range to check.
Returns
booleantrueifrangeis valid,falseotherwise.
-
Returns the default root for this document which is either the first root that was added to the document using
createRootor the graveyard root if no other roots were created.Returns
RootElementThe default root for this document.
-
protected
_hasDocumentChangedFromTheLastChangeBlock() → booleanmodule:engine/model/document~Document#_hasDocumentChangedFromTheLastChangeBlockReturns whether there is a buffered change or if the selection has changed from the last
enqueueChange()block orchange()block.Returns
booleanReturns
trueif document has changed from the lastchange()orenqueueChange()block.
-
Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.
Parameters
writer : WriterThe writer on which post-fixer callbacks will be called.
Returns
void
Events
-
change( eventInfo, batch )module:engine/model/document~Document#event:changeFired after each
enqueueChange()block or the outermostchange()block was executed and the document was changed during that block's execution.The changes which this event will cover include:
- document structure changes,
- selection changes,
- marker changes.
If you want to be notified about all these changes, then simply listen to this event like this:
model.document.on( 'change', () => { console.log( 'The document has changed!' ); } );If, however, you only want to be notified about the data changes, then use
change:dataevent, which is fired for document structure changes and marker changes (which affects the data).model.document.on( 'change:data', () => { console.log( 'The data has changed!' ); } );Parameters
-
change:data( eventInfo, batch )module:engine/model/document~Document#event:change:dataFired after each
enqueueChange()block or the outermostchange()block was executed and the document was changed during that block's execution.The changes which this event will cover include:
- document structure changes,
- selection changes,
- marker changes.
If you want to be notified about all these changes, then simply listen to this event like this:
model.document.on( 'change', () => { console.log( 'The document has changed!' ); } );If, however, you only want to be notified about the data changes, then use
change:dataevent, which is fired for document structure changes and marker changes (which affects the data).model.document.on( 'change:data', () => { console.log( 'The data has changed!' ); } );Parameters
Every day, we work hard to keep our documentation complete. Have you spotted outdated information? Is something missing? Please report it via our issue tracker.
With the release of version 42.0.0, we have rewritten much of our documentation to reflect the new import paths and features. We appreciate your feedback to help us ensure its accuracy and completeness.