The definition of a schema context.
Contexts can be created in multiple ways:
- By defining a node – in this cases this node and all its ancestors will be used.
- By defining a position in the document – in this case all its ancestors will be used.
- By defining an array of nodes – in this case this array defines the entire context.
- By defining a name of node - in this case node will be "mocked". It is not recommended because context
will be unrealistic (e.g. attributes of these nodes are not specified). However, at times this may be the only
way to define the context (e.g. when checking some hypothetical situation).
- By defining an array of node names (potentially, mixed with real nodes) – The same as name of node
but it is possible to create a path.
- By defining a
SchemaContext
instance - in this case the same instance as provided
will be returned.
Examples of context definitions passed to the Schema#checkChild()
method:
// Assuming that we have a $root > blockQuote > paragraph structure, the following code
// will check node 'foo' in the following context:
// [ rootElement, blockQuoteElement, paragraphElement ]
const contextDefinition = paragraphElement;
const childToCheck = 'foo';
schema.checkChild( contextDefinition, childToCheck );
// Also check in [ rootElement, blockQuoteElement, paragraphElement ].
schema.checkChild( model.createPositionAt( paragraphElement, 0 ), 'foo' );
// Check in [ rootElement, paragraphElement ].
schema.checkChild( [ rootElement, paragraphElement ], 'foo' );
// Check only fakeParagraphElement.
schema.checkChild( 'paragraph', 'foo' );
// Check in [ fakeRootElement, fakeBarElement, paragraphElement ].
schema.checkChild( [ '$root', 'bar', paragraphElement ], 'foo' );
All these checkChild()
calls will fire Schema#checkChild
events in which args[ 0 ]
is an instance of the context. Therefore, you can write a listener like this:
schema.on( 'checkChild', ( evt, args ) => {
const ctx = args[ 0 ];
console.log( Array.from( ctx.getNames() ) );
} );
Which will log the following:
[ '$root', 'blockQuote', 'paragraph' ]
[ '$root', 'paragraph' ]
[ '$root', 'bar', 'paragraph' ]
Note: When using the Schema#checkAttribute()
method
you may want to check whether a text node may have an attribute. A Text
is a
correct way to define a context so you can do this:
schema.checkAttribute( textNode, 'bold' );
But sometimes you want to check whether a text at a given position might've had some attribute,
in which case you can create a context by mixing in an array of elements with a '$text'
string:
// Check in [ rootElement, paragraphElement, textNode ].
schema.checkChild( [ ...positionInParagraph.getAncestors(), '$text' ], 'bold' );