ModelSchema
The model's schema. It defines the allowed and disallowed structures of nodes as well as nodes' attributes. The schema is usually defined by the features and based on them, the editing framework and features make decisions on how to change and process the model.
The instance of schema is available in editor.model.schema.
Read more about the schema in:
- The schema section of the Introduction to the Editing engine architecture guide.
- The Schema deep-dive guide.
Properties
-
_attributeProperties : Record<string, ModelAttributeProperties>privatereadonlymodule:engine/model/schema~ModelSchema#_attributePropertiesA dictionary containing attribute properties.
-
_compiledDefinitions : null | Record<string, ModelSchemaCompiledItemDefinition> | undefinedprivatemodule:engine/model/schema~ModelSchema#_compiledDefinitions -
_customAttributeChecks : Map<string | symbol, Array<ModelSchemaAttributeCheckCallback>>privatereadonlymodule:engine/model/schema~ModelSchema#_customAttributeChecksStores additional callbacks registered for attribute names, which are evaluated when
checkAttributeis called.Keys are schema attribute names for which the callbacks are registered. Values are arrays with the callbacks.
Some checks are added under
_genericCheckSymbolkey, these are evaluated for everycheckAttributecall. -
_customChildChecks : Map<string | symbol, Array<ModelSchemaChildCheckCallback>>privatereadonlymodule:engine/model/schema~ModelSchema#_customChildChecksStores additional callbacks registered for schema items, which are evaluated when
checkChildis called.Keys are schema item names for which the callbacks are registered. Values are arrays with the callbacks.
Some checks are added under
_genericCheckSymbolkey, these are evaluated for everycheckChildcall. -
_genericCheckSymbol : symbolprivatereadonlymodule:engine/model/schema~ModelSchema#_genericCheckSymbol -
_sourceDefinitions : Record<string, Array<ModelSchemaItemDefinition>>privatereadonlymodule:engine/model/schema~ModelSchema#_sourceDefinitions
Methods
-
module:engine/model/schema~ModelSchema#constructorCreates a schema instance.
-
addAttributeCheck( callback, [ attributeName ] ) → voidmodule:engine/model/schema~ModelSchema#addAttributeCheckAllows registering a callback to the
checkAttributemethod calls.Callbacks allow you to implement rules which are not otherwise possible to achieve by using the declarative API of
ModelSchemaItemDefinition.Note that callback checks have bigger priority than declarative rules checks and may overwrite them.
For example, by using this method you can disallow setting attributes on nodes in specific contexts:
// Disallow setting `bold` on text inside `heading1` element: schema.addAttributeCheck( context => { if ( context.endsWith( 'heading1 $text' ) ) { return false; } }, 'bold' );Copy codeYou can skip the optional
attributeNameparameter to evaluate the callback for everycheckAttribute()call.// Disallow formatting attributes on text inside custom `myTitle` element: schema.addAttributeCheck( ( context, attributeName ) => { if ( context.endsWith( 'myTitle $text' ) && schema.getAttributeProperties( attributeName ).isFormatting ) { return false; } } );Copy codePlease note that the generic callbacks may affect the editor performance and should be avoided if possible.
When one of the callbacks makes a decision (returns
trueorfalse) the processing is finished and other callbacks are not fired. Callbacks are fired in the order they were added, however generic callbacks are fired before callbacks added for a specified item.You can also use event-checkAttribute event, if you need even better control. The result from the example above could also be achieved with following event callback:
schema.on( 'checkAttribute', ( evt, args ) => { const context = args[ 0 ]; const attributeName = args[ 1 ]; if ( context.endsWith( 'myTitle $text' ) && schema.getAttributeProperties( attributeName ).isFormatting ) { // Prevent next listeners from being called. evt.stop(); // Set the `checkAttribute()` return value. evt.return = false; } }, { priority: 'high' } );Copy codeNote that the callback checks and declarative rules checks are processed on
normalpriority.Adding callbacks this way can also negatively impact editor performance.
Parameters
callback : ModelSchemaAttributeCheckCallbackThe callback to be called. It is called with two parameters:
contextand attribute name. The callback may returntrueorfalse, to overridecheckAttribute()'s return value. If it does not return a boolean value, the default algorithm (or other callbacks) will definecheckAttribute()'s return value.[ attributeName ] : stringName of the attribute for which the callback is registered. If specified, the callback will be run only for
checkAttribute()calls with matchingattributeName. Otherwise, the callback will run for everycheckAttribute()call.
Returns
void
-
addChildCheck( callback, [ itemName ] ) → voidmodule:engine/model/schema~ModelSchema#addChildCheckAllows registering a callback to the
checkChildmethod calls.Callbacks allow you to implement rules which are not otherwise possible to achieve by using the declarative API of
ModelSchemaItemDefinition.Note that callback checks have bigger priority than declarative rules checks and may overwrite them.
For example, by using this method you can disallow elements in specific contexts:
// Disallow `heading1` inside a `blockQuote` that is inside a table. schema.addChildCheck( ( context, childDefinition ) => { if ( context.endsWith( 'tableCell blockQuote' ) ) { return false; } }, 'heading1' );Copy codeYou can skip the optional
itemNameparameter to evaluate the callback for everycheckChild()call.// Inside specific custom element, allow only children, which allows for a specific attribute. schema.addChildCheck( ( context, childDefinition ) => { if ( context.endsWith( 'myElement' ) ) { return childDefinition.allowAttributes.includes( 'myAttribute' ); } } );Copy codePlease note that the generic callbacks may affect the editor performance and should be avoided if possible.
When one of the callbacks makes a decision (returns
trueorfalse) the processing is finished and other callbacks are not fired. Callbacks are fired in the order they were added, however generic callbacks are fired before callbacks added for a specified item.You can also use
checkChildevent, if you need even better control. The result from the example above could also be achieved with following event callback:schema.on( 'checkChild', ( evt, args ) => { const context = args[ 0 ]; const childDefinition = args[ 1 ]; if ( context.endsWith( 'myElement' ) ) { // Prevent next listeners from being called. evt.stop(); // Set the `checkChild()` return value. evt.return = childDefinition.allowAttributes.includes( 'myAttribute' ); } }, { priority: 'high' } );Copy codeNote that the callback checks and declarative rules checks are processed on
normalpriority.Adding callbacks this way can also negatively impact editor performance.
Parameters
callback : ModelSchemaChildCheckCallbackThe callback to be called. It is called with two parameters:
ModelSchemaContext(context) instance andModelSchemaCompiledItemDefinition(definition). The callback may returntrue/falseto overridecheckChild()'s return value. If it does not return a boolean value, the default algorithm (or other callbacks) will definecheckChild()'s return value.[ itemName ] : stringName of the schema item for which the callback is registered. If specified, the callback will be run only for
checkChild()calls whichdefparameter matches theitemName. Otherwise, the callback will run for everycheckChildcall.
Returns
void
-
bind( bindProperty1, bindProperty2 ) → ObservableDualBindChain<K1, ModelSchema[ K1 ], K2, ModelSchema[ K2 ]>inheritedmodule:engine/model/schema~ModelSchema#bind:DUAL_BINDBinds observable properties to other objects implementing the
Observableinterface.Read more in the dedicated guide covering the topic of property bindings with some additional examples.
Consider two objects: a
buttonand an associatedcommand(bothObservable).A simple property binding could be as follows:
button.bind( 'isEnabled' ).to( command, 'isEnabled' );Copy codeor even shorter:
button.bind( 'isEnabled' ).to( command );Copy codewhich works in the following way:
button.isEnabledinstantly equalscommand.isEnabled,- whenever
command.isEnabledchanges,button.isEnabledwill immediately reflect its value.
Note: To release the binding, use
unbind.You can also "rename" the property in the binding by specifying the new name in the
to()chain:button.bind( 'isEnabled' ).to( command, 'isWorking' );Copy codeIt is possible to bind more than one property at a time to shorten the code:
button.bind( 'isEnabled', 'value' ).to( command );Copy codewhich corresponds to:
button.bind( 'isEnabled' ).to( command ); button.bind( 'value' ).to( command );Copy codeThe binding can include more than one observable, combining multiple data sources in a custom callback:
button.bind( 'isEnabled' ).to( command, 'isEnabled', ui, 'isVisible', ( isCommandEnabled, isUIVisible ) => isCommandEnabled && isUIVisible );Copy codeUsing a custom callback allows processing the value before passing it to the target property:
button.bind( 'isEnabled' ).to( command, 'value', value => value === 'heading1' );Copy codeIt is also possible to bind to the same property in an array of observables. To bind a
buttonto multiple commands (alsoObservables) so that each and every one of them must be enabled for the button to become enabled, use the following code:button.bind( 'isEnabled' ).toMany( [ commandA, commandB, commandC ], 'isEnabled', ( isAEnabled, isBEnabled, isCEnabled ) => isAEnabled && isBEnabled && isCEnabled );Copy codeType parameters
K1K2
Parameters
bindProperty1 : K1Observable property that will be bound to other observable(s).
bindProperty2 : K2Observable property that will be bound to other observable(s).
Returns
ObservableDualBindChain<K1, ModelSchema[ K1 ], K2, ModelSchema[ K2 ]>The bind chain with the
to()andtoMany()methods.
-
bind( bindProperties ) → ObservableMultiBindChaininheritedmodule:engine/model/schema~ModelSchema#bind:MANY_BINDBinds observable properties to other objects implementing the
Observableinterface.Read more in the dedicated guide covering the topic of property bindings with some additional examples.
Consider two objects: a
buttonand an associatedcommand(bothObservable).A simple property binding could be as follows:
button.bind( 'isEnabled' ).to( command, 'isEnabled' );Copy codeor even shorter:
button.bind( 'isEnabled' ).to( command );Copy codewhich works in the following way:
button.isEnabledinstantly equalscommand.isEnabled,- whenever
command.isEnabledchanges,button.isEnabledwill immediately reflect its value.
Note: To release the binding, use
unbind.You can also "rename" the property in the binding by specifying the new name in the
to()chain:button.bind( 'isEnabled' ).to( command, 'isWorking' );Copy codeIt is possible to bind more than one property at a time to shorten the code:
button.bind( 'isEnabled', 'value' ).to( command );Copy codewhich corresponds to:
button.bind( 'isEnabled' ).to( command ); button.bind( 'value' ).to( command );Copy codeThe binding can include more than one observable, combining multiple data sources in a custom callback:
button.bind( 'isEnabled' ).to( command, 'isEnabled', ui, 'isVisible', ( isCommandEnabled, isUIVisible ) => isCommandEnabled && isUIVisible );Copy codeUsing a custom callback allows processing the value before passing it to the target property:
button.bind( 'isEnabled' ).to( command, 'value', value => value === 'heading1' );Copy codeIt is also possible to bind to the same property in an array of observables. To bind a
buttonto multiple commands (alsoObservables) so that each and every one of them must be enabled for the button to become enabled, use the following code:button.bind( 'isEnabled' ).toMany( [ commandA, commandB, commandC ], 'isEnabled', ( isAEnabled, isBEnabled, isCEnabled ) => isAEnabled && isBEnabled && isCEnabled );Copy codeParameters
bindProperties : Array<'off' | 'set' | 'bind' | 'unbind' | 'decorate' | 'stopListening' | 'on' | 'once' | 'listenTo' | 'fire' | 'delegate' | 'stopDelegating' | 'register' | 'extend' | 'getDefinitions' | 'getDefinition' | 'isRegistered' | 'isBlock' | 'isLimit' | 'isObject' | 'isInline' | 'isSelectable' | 'isContent' | 'checkChild' | 'checkAttribute' | 'checkMerge' | 'addChildCheck' | 'addAttributeCheck' | 'setAttributeProperties' | 'getAttributeProperties' | 'getLimitElement' | 'checkAttributeInSelection' | 'getValidRanges' | 'getNearestSelectionRange' | 'findAllowedParent' | 'setAllowedAttributes' | 'removeDisallowedAttributes' | 'getAttributesWithProperty' | 'createContext' | 'findOptimalInsertionRange'>Observable properties that will be bound to other observable(s).
Returns
ObservableMultiBindChainThe bind chain with the
to()andtoMany()methods.
-
bind( bindProperty ) → ObservableSingleBindChain<K, ModelSchema[ K ]>inheritedmodule:engine/model/schema~ModelSchema#bind:SINGLE_BINDBinds observable properties to other objects implementing the
Observableinterface.Read more in the dedicated guide covering the topic of property bindings with some additional examples.
Consider two objects: a
buttonand an associatedcommand(bothObservable).A simple property binding could be as follows:
button.bind( 'isEnabled' ).to( command, 'isEnabled' );Copy codeor even shorter:
button.bind( 'isEnabled' ).to( command );Copy codewhich works in the following way:
button.isEnabledinstantly equalscommand.isEnabled,- whenever
command.isEnabledchanges,button.isEnabledwill immediately reflect its value.
Note: To release the binding, use
unbind.You can also "rename" the property in the binding by specifying the new name in the
to()chain:button.bind( 'isEnabled' ).to( command, 'isWorking' );Copy codeIt is possible to bind more than one property at a time to shorten the code:
button.bind( 'isEnabled', 'value' ).to( command );Copy codewhich corresponds to:
button.bind( 'isEnabled' ).to( command ); button.bind( 'value' ).to( command );Copy codeThe binding can include more than one observable, combining multiple data sources in a custom callback:
button.bind( 'isEnabled' ).to( command, 'isEnabled', ui, 'isVisible', ( isCommandEnabled, isUIVisible ) => isCommandEnabled && isUIVisible );Copy codeUsing a custom callback allows processing the value before passing it to the target property:
button.bind( 'isEnabled' ).to( command, 'value', value => value === 'heading1' );Copy codeIt is also possible to bind to the same property in an array of observables. To bind a
buttonto multiple commands (alsoObservables) so that each and every one of them must be enabled for the button to become enabled, use the following code:button.bind( 'isEnabled' ).toMany( [ commandA, commandB, commandC ], 'isEnabled', ( isAEnabled, isBEnabled, isCEnabled ) => isAEnabled && isBEnabled && isCEnabled );Copy codeType parameters
K
Parameters
bindProperty : KObservable property that will be bound to other observable(s).
Returns
ObservableSingleBindChain<K, ModelSchema[ K ]>The bind chain with the
to()andtoMany()methods.
-
checkAttribute( context, attributeName ) → booleanmodule:engine/model/schema~ModelSchema#checkAttributeChecks whether the given attribute can be applied in the given context (on the last item of the context).
schema.checkAttribute( textNode, 'bold' ); // -> false schema.extend( '$text', { allowAttributes: 'bold' } ); schema.checkAttribute( textNode, 'bold' ); // -> trueCopy codeBoth callback checks and declarative rules (added when registering and extending items) are evaluated when this method is called.
Note that callback checks have bigger priority than declarative rules checks and may overwrite them.
Parameters
context : ModelSchemaContextDefinitionThe context in which the attribute will be checked.
attributeName : stringName of attribute to check in the given context.
Returns
boolean
Fires
-
checkAttributeInSelection( selection, attribute ) → booleanmodule:engine/model/schema~ModelSchema#checkAttributeInSelectionChecks whether the attribute is allowed in selection:
- if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
- if the selection is collapsed, then checks if on the selection position there's a text with the specified attribute allowed.
Parameters
selection : ModelSelection | ModelDocumentSelectionSelection which will be checked.
attribute : stringThe name of the attribute to check.
Returns
boolean
-
checkChild( context, def ) → booleanmodule:engine/model/schema~ModelSchema#checkChildChecks whether the given node can be a child of the given context.
schema.checkChild( model.document.getRoot(), paragraph ); // -> false schema.register( 'paragraph', { allowIn: '$root' } ); schema.checkChild( model.document.getRoot(), paragraph ); // -> trueCopy codeBoth callback checks and declarative rules (added when registering and extending items) are evaluated when this method is called.
Note that callback checks have bigger priority than declarative rules checks and may overwrite them.
Note that when verifying whether the given node can be a child of the given context, the schema also verifies the entire context – from its root to its last element. Therefore, it is possible for
checkChild()to returnfalseeven though thecontextlast element can contain the checked child. It happens if one of thecontextelements does not allow its child. Whencontextis verified, custom checks are considered as well.Parameters
context : ModelSchemaContextDefinitionThe context in which the child will be checked.
def : string | ModelNode | ModelDocumentFragmentThe child to check.
Returns
boolean
Fires
-
checkMerge( baseElement, elementToMerge ) → booleanmodule:engine/model/schema~ModelSchema#checkMerge -
checkMerge( position ) → booleanmodule:engine/model/schema~ModelSchema#checkMerge -
createContext( context ) → ModelSchemaContextmodule:engine/model/schema~ModelSchema#createContextCreates an instance of the schema context.
Parameters
context : ModelSchemaContextDefinition
Returns
-
decorate( methodName ) → voidinheritedmodule:engine/model/schema~ModelSchema#decorateTurns the given methods of this object into event-based ones. This means that the new method will fire an event (named after the method) and the original action will be plugged as a listener to that event.
Read more in the dedicated guide covering the topic of decorating methods with some additional examples.
Decorating the method does not change its behavior (it only adds an event), but it allows to modify it later on by listening to the method's event.
For example, to cancel the method execution the event can be stopped:
class Foo extends ObservableMixin() { constructor() { super(); this.decorate( 'method' ); } method() { console.log( 'called!' ); } } const foo = new Foo(); foo.on( 'method', ( evt ) => { evt.stop(); }, { priority: 'high' } ); foo.method(); // Nothing is logged.Copy codeNote: The high priority listener has been used to execute this particular callback before the one which calls the original method (which uses the "normal" priority).
It is also possible to change the returned value:
foo.on( 'method', ( evt ) => { evt.return = 'Foo!'; } ); foo.method(); // -> 'Foo'Copy codeFinally, it is possible to access and modify the arguments the method is called with:
method( a, b ) { console.log( `${ a }, ${ b }` ); } // ... foo.on( 'method', ( evt, args ) => { args[ 0 ] = 3; console.log( args[ 1 ] ); // -> 2 }, { priority: 'high' } ); foo.method( 1, 2 ); // -> '3, 2'Copy codeParameters
methodName : 'off' | 'set' | 'bind' | 'unbind' | 'decorate' | 'stopListening' | 'on' | 'once' | 'listenTo' | 'fire' | 'delegate' | 'stopDelegating' | 'register' | 'extend' | 'getDefinitions' | 'getDefinition' | 'isRegistered' | 'isBlock' | 'isLimit' | 'isObject' | 'isInline' | 'isSelectable' | 'isContent' | 'checkChild' | 'checkAttribute' | 'checkMerge' | 'addChildCheck' | 'addAttributeCheck' | 'setAttributeProperties' | 'getAttributeProperties' | 'getLimitElement' | 'checkAttributeInSelection' | 'getValidRanges' | 'getNearestSelectionRange' | 'findAllowedParent' | 'setAllowedAttributes' | 'removeDisallowedAttributes' | 'getAttributesWithProperty' | 'createContext' | 'findOptimalInsertionRange'Name of the method to decorate.
Returns
void
-
delegate( events ) → EmitterMixinDelegateChaininheritedmodule:engine/model/schema~ModelSchema#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
-
extend( itemName, definition ) → voidmodule:engine/model/schema~ModelSchema#extendExtends a registered item's definition.
Extending properties such as
allowInwill add more items to the existing properties, while redefining properties such asisBlockwill override the previously defined ones.schema.register( 'foo', { allowIn: '$root', isBlock: true; } ); schema.extend( 'foo', { allowIn: 'blockQuote', isBlock: false } ); schema.getDefinition( 'foo' ); // { // allowIn: [ '$root', 'blockQuote' ], // isBlock: false // }Copy codeParameters
itemName : stringdefinition : ModelSchemaItemDefinition
Returns
void
-
findAllowedParent( position, node ) → null | ModelElementmodule:engine/model/schema~ModelSchema#findAllowedParentTries to find position ancestors that allow to insert a given node. It starts searching from the given position and goes node by node to the top of the model tree as long as a limit element, an object element or a topmost ancestor is not reached.
Parameters
position : ModelPositionThe position that the search will start from.
node : string | ModelNodeThe node for which an allowed parent should be found or its name.
Returns
null | ModelElementAllowed parent or null if nothing was found.
-
fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]inheritedmodule:engine/model/schema~ModelSchema#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).
-
getAttributeProperties( attributeName ) → ModelAttributePropertiesmodule:engine/model/schema~ModelSchema#getAttributePropertiesReturns properties associated with a given model attribute. See
setAttributeProperties().Parameters
attributeName : stringA name of the attribute.
Returns
-
getAttributesWithProperty( node, propertyName, propertyValue ) → Record<string, unknown>module:engine/model/schema~ModelSchema#getAttributesWithPropertyGets attributes of a node that have a given property.
Parameters
node : ModelNodeNode to get attributes from.
propertyName : stringName of the property that attribute must have to return it.
propertyValue : unknownDesired value of the property that we want to check. When
undefinedattributes will be returned if they have set a given property no matter what the value is. If specified it will return attributes which given property's value is equal to this parameter.
Returns
Record<string, unknown>Object with attributes' names as key and attributes' values as value.
-
getDefinition( item ) → undefined | ModelSchemaCompiledItemDefinitionmodule:engine/model/schema~ModelSchema#getDefinitionReturns a definition of the given item or
undefinedif an item is not registered.This method should normally be used for reflection purposes (e.g. defining a clone of a certain element, checking a list of all block elements, etc). Use specific methods (such as
checkChild()orisLimit()) in other cases.Parameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
undefined | ModelSchemaCompiledItemDefinition
-
getDefinitions() → Record<string, ModelSchemaCompiledItemDefinition>module:engine/model/schema~ModelSchema#getDefinitionsReturns data of all registered items.
This method should normally be used for reflection purposes (e.g. defining a clone of a certain element, checking a list of all block elements, etc). Use specific methods (such as
checkChild()orisLimit()) in other cases.Returns
Record<string, ModelSchemaCompiledItemDefinition>
-
getLimitElement( selectionOrRangeOrPosition ) → ModelElementmodule:engine/model/schema~ModelSchema#getLimitElementReturns the lowest limit element containing the entire selection/range/position or the root otherwise.
Parameters
selectionOrRangeOrPosition : ModelPosition | ModelRange | ModelSelection | ModelDocumentSelectionThe selection/range/position to check.
Returns
ModelElementThe lowest limit element containing the entire
selectionOrRangeOrPosition.
-
getNearestSelectionRange( position, direction ) → null | ModelRangemodule:engine/model/schema~ModelSchema#getNearestSelectionRangeBasing on given
position, finds and returns a range which is nearest to thatpositionand is a correct range for selection.The correct selection range might be collapsed when it is located in a position where the text node can be placed. Non-collapsed range is returned when selection can be placed around element marked as an "object" in the schema.
Direction of searching for the nearest correct selection range can be specified as:
both- searching will be performed in both ways,forward- searching will be performed only forward,backward- searching will be performed only backward.
When valid selection range cannot be found,
nullis returned.Parameters
position : ModelPositionReference position where new selection range should be looked for.
direction : 'forward' | 'backward' | 'both'Search direction.
Defaults to
'both'
Returns
null | ModelRangeNearest selection range or
nullif one cannot be found.
-
getValidRanges( ranges, attribute ) → IterableIterator<ModelRange>module:engine/model/schema~ModelSchema#getValidRangesTransforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
Parameters
ranges : Iterable<ModelRange>Ranges to be validated.
attribute : stringThe name of the attribute to check.
Returns
IterableIterator<ModelRange>Ranges in which the attribute is allowed.
-
isBlock( item ) → booleanmodule:engine/model/schema~ModelSchema#isBlockReturns
trueif the given item is defined to be a block by theModelSchemaItemDefinition'sisBlockproperty.schema.isBlock( 'paragraph' ); // -> true schema.isBlock( '$root' ); // -> false const paragraphElement = writer.createElement( 'paragraph' ); schema.isBlock( paragraphElement ); // -> trueCopy codeSee the Block elements section of the Schema deep-dive guide for more details.
Parameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
boolean
-
isContent( item ) → booleanmodule:engine/model/schema~ModelSchema#isContentReturns
trueif the given item is defined to be a content by theModelSchemaItemDefinition'sisContentproperty.schema.isContent( 'paragraph' ); // -> false schema.isContent( 'heading1' ); // -> false schema.isContent( 'imageBlock' ); // -> true schema.isContent( 'horizontalLine' ); // -> true const text = writer.createText( 'foo' ); schema.isContent( text ); // -> trueCopy codeSee the Content elements section of the Schema deep-dive guide for more details.
Parameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
boolean
-
isInline( item ) → booleanmodule:engine/model/schema~ModelSchema#isInlineReturns
trueif the given item is defined to be an inline element by theModelSchemaItemDefinition'sisInlineproperty.schema.isInline( 'paragraph' ); // -> false schema.isInline( 'softBreak' ); // -> true const text = writer.createText( 'foo' ); schema.isInline( text ); // -> trueCopy codeSee the Inline elements section of the Schema deep-dive guide for more details.
Parameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
boolean
-
isLimit( item ) → booleanmodule:engine/model/schema~ModelSchema#isLimitReturns
trueif the given item should be treated as a limit element.It considers an item to be a limit element if its
ModelSchemaItemDefinition'sisLimitorisObjectproperty was set totrue.schema.isLimit( 'paragraph' ); // -> false schema.isLimit( '$root' ); // -> true schema.isLimit( editor.model.document.getRoot() ); // -> true schema.isLimit( 'imageBlock' ); // -> trueCopy codeSee the Limit elements section of the Schema deep-dive guide for more details.
Parameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
boolean
-
isObject( item ) → booleanmodule:engine/model/schema~ModelSchema#isObjectReturns
trueif the given item should be treated as an object element.It considers an item to be an object element if its
ModelSchemaItemDefinition'sisObjectproperty was set totrue.schema.isObject( 'paragraph' ); // -> false schema.isObject( 'imageBlock' ); // -> true const imageElement = writer.createElement( 'imageBlock' ); schema.isObject( imageElement ); // -> trueCopy codeSee the Object elements section of the Schema deep-dive guide for more details.
Parameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
boolean
-
isRegistered( item ) → booleanmodule:engine/model/schema~ModelSchema#isRegisteredReturns
trueif the given item is registered in the schema.schema.isRegistered( 'paragraph' ); // -> true schema.isRegistered( editor.model.document.getRoot() ); // -> true schema.isRegistered( 'foo' ); // -> falseCopy codeParameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
boolean
-
isSelectable( item ) → booleanmodule:engine/model/schema~ModelSchema#isSelectableReturns
trueif the given item is defined to be a selectable element by theModelSchemaItemDefinition'sisSelectableproperty.schema.isSelectable( 'paragraph' ); // -> false schema.isSelectable( 'heading1' ); // -> false schema.isSelectable( 'imageBlock' ); // -> true schema.isSelectable( 'tableCell' ); // -> true const text = writer.createText( 'foo' ); schema.isSelectable( text ); // -> falseCopy codeSee the Selectable elements section of the Schema deep-dive guide for more details.
Parameters
item : string | ModelDocumentFragment | ModelItem | ModelSchemaContextItem
Returns
boolean
-
listenTo( emitter, event, callback, [ options ] ) → voidinheritedmodule:engine/model/schema~ModelSchema#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/model/schema~ModelSchema#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/model/schema~ModelSchema#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/model/schema~ModelSchema#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
-
register( itemName, [ definition ] ) → voidmodule:engine/model/schema~ModelSchema#registerRegisters a schema item. Can only be called once for every item name.
schema.register( 'paragraph', { inheritAllFrom: '$block' } );Copy codeParameters
itemName : string[ definition ] : ModelSchemaItemDefinition
Returns
void
-
removeDisallowedAttributes( nodes, writer ) → voidmodule:engine/model/schema~ModelSchema#removeDisallowedAttributesRemoves attributes disallowed by the schema.
Parameters
nodes : Iterable<ModelNode>Nodes that will be filtered.
writer : ModelWriter
Returns
void
-
set( values ) → voidinheritedmodule:engine/model/schema~ModelSchema#set:OBJECTCreates and sets the value of an observable properties of this object. Such a property becomes a part of the state and is observable.
It accepts a single object literal containing key/value pairs with properties to be set.
This method throws the
observable-set-cannot-overrideerror if the observable instance already has a property with the given property name. This prevents from mistakenly overriding existing properties and methods, but means thatfoo.set( 'bar', 1 )may be slightly slower thanfoo.bar = 1.In TypeScript, those properties should be declared in class using
declarekeyword. In example:public declare myProp1: number; public declare myProp2: string; constructor() { this.set( { 'myProp1: 2, 'myProp2: 'foo' } ); }Copy codeParameters
values : objectAn object with
name=>valuepairs.
Returns
void
-
set( name, value ) → voidinheritedmodule:engine/model/schema~ModelSchema#set:KEY_VALUECreates and sets the value of an observable property of this object. Such a property becomes a part of the state and is observable.
This method throws the
observable-set-cannot-overrideerror if the observable instance already has a property with the given property name. This prevents from mistakenly overriding existing properties and methods, but means thatfoo.set( 'bar', 1 )may be slightly slower thanfoo.bar = 1.In TypeScript, those properties should be declared in class using
declarekeyword. In example:public declare myProp: number; constructor() { this.set( 'myProp', 2 ); }Copy codeType parameters
K
Parameters
name : KThe property's name.
value : ModelSchema[ K ]The property's value.
Returns
void
-
setAllowedAttributes( node, attributes, writer ) → voidmodule:engine/model/schema~ModelSchema#setAllowedAttributesSets attributes allowed by the schema on a given node.
Parameters
node : ModelNodeA node to set attributes on.
attributes : Record<string, unknown>Attributes keys and values.
writer : ModelWriterAn instance of the model writer.
Returns
void
-
setAttributeProperties( attributeName, properties ) → voidmodule:engine/model/schema~ModelSchema#setAttributePropertiesThis method allows assigning additional metadata to the model attributes. For example,
AttributeProperties#isFormattingproperty is used to mark formatting attributes (likeboldoritalic).// Mark bold as a formatting attribute. schema.setAttributeProperties( 'bold', { isFormatting: true } ); // Override code not to be considered a formatting markup. schema.setAttributeProperties( 'code', { isFormatting: false } );Copy codeProperties are not limited to members defined in the
AttributePropertiestype and you can also use custom properties:schema.setAttributeProperties( 'blockQuote', { customProperty: 'value' } );Copy codeSubsequent calls with the same attribute will extend its custom properties:
schema.setAttributeProperties( 'blockQuote', { one: 1 } ); schema.setAttributeProperties( 'blockQuote', { two: 2 } ); console.log( schema.getAttributeProperties( 'blockQuote' ) ); // Logs: { one: 1, two: 2 }Copy codeParameters
attributeName : stringA name of the attribute to receive the properties.
properties : ModelAttributePropertiesA dictionary of properties.
Returns
void
-
stopDelegating( [ event ], [ emitter ] ) → voidinheritedmodule:engine/model/schema~ModelSchema#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/model/schema~ModelSchema#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
-
unbind( unbindProperties ) → voidinheritedmodule:engine/model/schema~ModelSchema#unbindRemoves the binding created with
bind.// Removes the binding for the 'a' property. A.unbind( 'a' ); // Removes bindings for all properties. A.unbind();Copy codeParameters
unbindProperties : Array<'off' | 'set' | 'bind' | 'unbind' | 'decorate' | 'stopListening' | 'on' | 'once' | 'listenTo' | 'fire' | 'delegate' | 'stopDelegating' | 'register' | 'extend' | 'getDefinitions' | 'getDefinition' | 'isRegistered' | 'isBlock' | 'isLimit' | 'isObject' | 'isInline' | 'isSelectable' | 'isContent' | 'checkChild' | 'checkAttribute' | 'checkMerge' | 'addChildCheck' | 'addAttributeCheck' | 'setAttributeProperties' | 'getAttributeProperties' | 'getLimitElement' | 'checkAttributeInSelection' | 'getValidRanges' | 'getNearestSelectionRange' | 'findAllowedParent' | 'setAllowedAttributes' | 'removeDisallowedAttributes' | 'getAttributesWithProperty' | 'createContext' | 'findOptimalInsertionRange'>Observable properties to be unbound. All the bindings will be released if no properties are provided.
Returns
void
-
findOptimalInsertionRange( selection, [ place ] ) → ModelRangeinternalmodule:engine/model/schema~ModelSchema#findOptimalInsertionRangeReturns a model range which is optimal (in terms of UX) for inserting a widget block.
For instance, if a selection is in the middle of a paragraph, the collapsed range before this paragraph will be returned so that it is not split. If the selection is at the end of a paragraph, the collapsed range after this paragraph will be returned.
Note: If the selection is placed in an empty block, the range in that block will be returned. If that range is then passed to
insertContent, the block will be fully replaced by the inserted widget block.Parameters
selection : ModelSelection | ModelDocumentSelectionThe selection based on which the insertion position should be calculated.
[ place ] : 'auto' | 'after' | 'before'The place where to look for optimal insertion range. The
autovalue will determine itself the best position for insertion. Thebeforevalue will try to find a position before selection. Theaftervalue will try to find a position after selection.
Returns
ModelRangeThe optimal range.
-
_checkContextMatch( context, def ) → booleanprivatemodule:engine/model/schema~ModelSchema#_checkContextMatch -
_clearCache() → voidprivatemodule:engine/model/schema~ModelSchema#_clearCache -
_compile() → voidprivatemodule:engine/model/schema~ModelSchema#_compile -
_evaluateAttributeChecks( context, attributeName ) → undefined | booleanprivatemodule:engine/model/schema~ModelSchema#_evaluateAttributeChecksCalls attribute check callbacks to decide whether
attributeNamecan be set on the last element ofcontext. It uses both generic and specific (defined forattributeName) callbacks. If neither callback makes a decision,undefinedis returned.Note that the first callback that makes a decision "wins", i.e., if any callback returns
trueorfalse, then the processing is over and that result is returned.Parameters
context : ModelSchemaContextattributeName : string
Returns
undefined | boolean
-
_evaluateChildChecks( context, def ) → undefined | booleanprivatemodule:engine/model/schema~ModelSchema#_evaluateChildChecksCalls child check callbacks to decide whether
defis allowed incontext. It uses both generic and specific (defined fordefitem) callbacks. If neither callback makes a decision,undefinedis returned.Note that the first callback that makes a decision "wins", i.e., if any callback returns
trueorfalse, then the processing is over and that result is returned.Parameters
context : ModelSchemaContextdef : ModelSchemaCompiledItemDefinition
Returns
undefined | boolean
-
_getValidRangesForRange( range, attribute ) → Iterable<ModelRange>privatemodule:engine/model/schema~ModelSchema#_getValidRangesForRangeTakes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges inside the given range on which the attribute can be applied.
This is a helper function for
getValidRanges.Parameters
range : ModelRangeThe range to process.
attribute : stringThe name of the attribute to check.
Returns
Iterable<ModelRange>Ranges in which the attribute is allowed.
Events
-
change:{property}( eventInfo, name, value, oldValue )inheritedmodule:engine/model/schema~ModelSchema#event:change:{property}Fired when a property changed value.
observable.set( 'prop', 1 ); observable.on<ObservableChangeEvent<number>>( 'change:prop', ( evt, propertyName, newValue, oldValue ) => { console.log( `${ propertyName } has changed from ${ oldValue } to ${ newValue }` ); } ); observable.prop = 2; // -> 'prop has changed from 1 to 2'Copy codeParameters
eventInfo : EventInfoAn object containing information about the fired event.
name : stringThe property name.
value : TValueThe new property value.
oldValue : TValueThe previous property value.
-
checkAttribute( eventInfo, args )module:engine/model/schema~ModelSchema#event:checkAttributeEvent fired when the
checkAttributemethod is called. It allows plugging in additional behavior, for example implementing rules which cannot be defined using the declarativeModelSchemaItemDefinitioninterface.Note: The
addAttributeCheckmethod is a more handy way to register callbacks. Internally, it registers a listener to this event but comes with a simpler API and it is the recommended choice in most of the cases.The
checkAttributemethod fires an event because it is decorated with it. Thanks to that you can use this event in various ways, but the most important use case is overriding the standard behavior of thecheckAttribute()method. Let's see a typical listener template:schema.on( 'checkAttribute', ( evt, args ) => { const context = args[ 0 ]; const attributeName = args[ 1 ]; }, { priority: 'high' } );Copy codeThe listener is added with a
highpriority to be executed before the default method is really called. Theargscallback parameter contains arguments passed tocheckAttribute( context, attributeName ). However, thecontextparameter is already normalized to aModelSchemaContextinstance, so you do not have to worry about the various ways howcontextmay be passed tocheckAttribute().So, in order to implement a rule "disallow
boldin a text which is in aheading1, you can add such a listener:schema.on( 'checkAttribute', ( evt, args ) => { const context = args[ 0 ]; const attributeName = args[ 1 ]; if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) { // Prevent next listeners from being called. evt.stop(); // Set the checkAttribute()'s return value. evt.return = false; } }, { priority: 'high' } );Copy codeAllowing attributes in specific contexts will be a far less common use case, because it is normally handled by the
allowAttributesrule fromModelSchemaItemDefinition. But if you have a complex scenario whereboldshould be allowed only in elementfoowhich must be in elementbar, then this would be the way:schema.on( 'checkAttribute', ( evt, args ) => { const context = args[ 0 ]; const attributeName = args[ 1 ]; if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) { // Prevent next listeners from being called. evt.stop(); // Set the checkAttribute()'s return value. evt.return = true; } }, { priority: 'high' } );Copy codeParameters
eventInfo : EventInfoAn object containing information about the fired event.
args : tupleThe
checkAttribute()'s arguments.
-
checkChild( eventInfo, args )module:engine/model/schema~ModelSchema#event:checkChildEvent fired when the
checkChildmethod is called. It allows plugging in additional behavior, for example implementing rules which cannot be defined using the declarativeModelSchemaItemDefinitioninterface.Note: The
addChildCheckmethod is a more handy way to register callbacks. Internally, it registers a listener to this event but comes with a simpler API and it is the recommended choice in most of the cases.The
checkChildmethod fires an event because it is decorated with it. Thanks to that you can use this event in various ways, but the most important use case is overriding standard behavior of thecheckChild()method. Let's see a typical listener template:schema.on( 'checkChild', ( evt, args ) => { const context = args[ 0 ]; const childDefinition = args[ 1 ]; }, { priority: 'high' } );Copy codeThe listener is added with a
highpriority to be executed before the default method is really called. Theargscallback parameter contains arguments passed tocheckChild( context, child ). However, thecontextparameter is already normalized to aModelSchemaContextinstance andchildto aModelSchemaCompiledItemDefinitioninstance, so you do not have to worry about the various ways howcontextandchildmay be passed tocheckChild().Note:
childDefinitionmay beundefinedifcheckChild()was called with a non-registered element.So, in order to implement a rule "disallow
heading1inblockQuote", you can add such a listener:schema.on( 'checkChild', ( evt, args ) => { const context = args[ 0 ]; const childDefinition = args[ 1 ]; if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) { // Prevent next listeners from being called. evt.stop(); // Set the checkChild()'s return value. evt.return = false; } }, { priority: 'high' } );Copy codeAllowing elements in specific contexts will be a far less common use case, because it is normally handled by the
allowInrule fromModelSchemaItemDefinition. But if you have a complex scenario wherelistItemshould be allowed only in elementfoowhich must be in elementbar, then this would be the way:schema.on( 'checkChild', ( evt, args ) => { const context = args[ 0 ]; const childDefinition = args[ 1 ]; if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) { // Prevent next listeners from being called. evt.stop(); // Set the checkChild()'s return value. evt.return = true; } }, { priority: 'high' } );Copy codeParameters
eventInfo : EventInfoAn object containing information about the fired event.
args : tupleThe
checkChild()'s arguments.
-
set:{property}( eventInfo, name, value, oldValue )inheritedmodule:engine/model/schema~ModelSchema#event:set:{property}Fired when a property value is going to be set but is not set yet (before the
changeevent is fired).You can control the final value of the property by using the event's
returnproperty.observable.set( 'prop', 1 ); observable.on<ObservableSetEvent<number>>( 'set:prop', ( evt, propertyName, newValue, oldValue ) => { console.log( `Value is going to be changed from ${ oldValue } to ${ newValue }` ); console.log( `Current property value is ${ observable[ propertyName ] }` ); // Let's override the value. evt.return = 3; } ); observable.on<ObservableChangeEvent<number>>( 'change:prop', ( evt, propertyName, newValue, oldValue ) => { console.log( `Value has changed from ${ oldValue } to ${ newValue }` ); } ); observable.prop = 2; // -> 'Value is going to be changed from 1 to 2' // -> 'Current property value is 1' // -> 'Value has changed from 1 to 3'Copy codeNote: The event is fired even when the new value is the same as the old value.
Parameters
eventInfo : EventInfoAn object containing information about the fired event.
name : stringThe property name.
value : TValueThe new property value.
oldValue : TValueThe previous property value.