Contexts¶
A Context<I : ContextIntention<I>>, at its core, is a simple key-value storage for (ContextParamType<T, I>, T) pairs and a ContextIntention, which defines their allowed parameter types.
The context system can also infer parameters from other parameters, for example, you don't need to provide a BLOCK_WORLD parameter if you provide a BLOCK parameter, and you can still read BLOCK_WORLD from the context.
You can find a list of default context intentions here. Each context intention object contains their allowed parameter types as properties and documents which autofillers (which infer context parameter values) are available.
Creating and using a Context¶
And this is how you create and use a Context:
// create context
val ctx: Context<BlockPlace> = Context.intention(BlockPlace /* (1)! */)
.param(BlockPlace.BLOCK, block)
.param(BlockPlace.BLOCK_TYPE, Blocks.EXAMPLE_BLOCK.get())
.build()
// read from context
val world: World = ctx[BlockPlace.BLOCK_WORLD] // (2)!
val whoPlaced: Player? = ctx[BlockPlace.SOURCE_PLAYER] // (3)!
// context usage: place block
BlockUtils.placeBlock(ctx)
-
The
ContextIntentionBlockPlacespecifies the set of allowed context param types that are available, for exampleBlockPlace.BLOCKorBlockPlace.BLOCK_TYPE. It also specifies how context parameter values can be inferred from each other, for example,BLOCK_WORLDcan be inferred from the BukkitBLOCK. -
This reads the
BLOCK_WORLDparameter from the context, which is inferred from the providedBLOCKparameter. SinceBLOCK_WORLDis a required parameter for theBlockPlaceintention, we can be sure that it is present in the context and thus non-null. -
This reads the
SOURCE_PLAYERparameter from the context, which is optional for theBlockPlaceintention. The returned value is nullable as it is not a required parameter type in this intention. In this specific case, the player will be null because no suitable parameter that could be used to infer the player (likeSOURCE_UUID) was defined.
Custom ContextParameterType¶
You can register a custom parameter type for an intention like this:
For required parameters, use addRequiredParamType:
If your parameter should have a default value, use addDefaultingParamType
Custom Autofiller¶
Once you have registered a custom parameter type, you may also want to register an autofiller for it. This can be done via ContextIntention.addAutofiller:
BlockPlace.addAutofiller(
BLOCK_NAME,
Autofiller.from(BlockPlace.BLOCK_TYPE) { type: BlockType ->
Component.text(type.toString())
}
)
Custom ContextIntention¶
Of course, you can also create a completely custom ContextIntention. For that, create a singleton object that inherits from AbstractContextIntention: