Composition engine
The composition engine links several keys into a chain. Each key reads and rewrites a CompositionContext and passes the next state through lastFlag; a chain can carry arbitrary values and register undo actions. It suits input such as 3 d (count + action) or d w (operator + target).
Prerequisites
| Chapter | Why you need it |
|---|---|
| Multi-key Sequences | Sequences match keys; composition also carries state |
| Intermediate Binding | when and named conditions apply to composition entries |
Model
type CompositionContext<T = unknown> = {
value: T
lastFlag: string | null
steps: string[]
}valueis any data carried through the chain.lastFlagis the flag left by the previous key;nullat the head.stepslists executed keys for undo and debugging.
A CompositionKey:
| Field | Type | Effect |
|---|---|---|
key | string | Trigger key |
flags | { need, become }[] | Transition table: when the previous flag is need, this key sets become |
needs | string[] | Which previous flags this key accepts |
alternativeFlag | string | Flag used at the head or when no transition matches |
optional | boolean | The key may start a chain with nothing pending |
timeout | number | Next-key timeout; defaults to the engine defaultTimeout (400ms) |
exclusive | boolean | Swallow a mismatched key and keep waiting instead of cancelling |
execute | (ctx) => ctx | null | Rewrites the context; null terminates the chain |
undoAction | (ctx) => ctx | null | Inverse operation; null stops the undo walk |
isEndKey | string[] | End the chain when the current lastFlag is listed |
SwallowKeyWhenChainInterrupted | boolean | Swallow the breaking key when execute returns null or validation fails |
when / mode / category / affectOverlay / executeWhenNoOverlay | — | Same as other bindings |
affectOverlay is the phase field for composition and mapping entries; globalKeys / globalSequence use affectLayer instead. They are different options.
How the flag is chosen
- Head (
lastFlag === null): usealternativeFlag. - Continuation: if
lastFlagmatches aneedinflags, use itsbecome; otherwise usealternativeFlag. - If
executesetslastFlagexplicitly, the engine does not override it.
How a key is selected
Several entries may share a trigger key. Selection order:
- Entries whose
needsmatch the currentlastFlag; at the head, entries withoptional: trueorneeds: []. - More modifier segments win (
ctrl+sovers). - Longer
needslists win (stricter contract).
Registration
registryCompositionKey(entry: CompositionKey): voidconst { registryCompositionKey } = useKeyboard()
useEffect(() => {
registryCompositionKey({
key: '3',
flags: [],
needs: [],
optional: true,
alternativeFlag: 'times',
execute: (ctx) => ({ ...ctx, value: 3, lastFlag: 'times', steps: [...ctx.steps, '3'] }),
})
registryCompositionKey({
key: 'd',
flags: [],
needs: ['times'],
alternativeFlag: 'action',
execute: (ctx) => {
if (typeof ctx.value !== 'number') return null
deleteLines(ctx.value)
return null
},
})
}, [registryCompositionKey])removeCompositionKey(key) removes every entry for that trigger key and returns whether any existed; it does not abort a pending chain. clearAllCompositionKeys() clears the table.
updateCompositionKey(key, flags, updates) locates an entry by key + flags and merges fields, returning whether it found one. Several entries can share a key and be distinguished by flags:
updateCompositionKey('d', [{ need: 'times', become: 'action' }], { timeout: 800 })Registering a semantically identical entry twice is a no-op; entries that differ only by category are separate registrations and each fires only on its own screens.
A full chain: count, execute, undo
registryCompositionKey({
key: '3',
flags: [],
needs: [],
optional: true,
alternativeFlag: 'count',
execute: (ctx) => ({
...ctx,
value: 3,
steps: [...ctx.steps, '3'],
}),
})
registryCompositionKey({
key: 'd',
flags: [{ need: 'count', become: 'deleted' }],
needs: ['count'],
alternativeFlag: 'deleted',
execute: (ctx) => {
if (typeof ctx.value !== 'number') return null
return {
...ctx,
value: deleteLines(ctx.value),
steps: [...ctx.steps, 'd'],
}
},
undoAction: (ctx) => ({
...ctx,
value: restoreLines(ctx.value),
steps: [],
}),
})Pressing 3 starts the chain and sets lastFlag to count; pressing d within the timeout advances it to deleted via flags. The timeout records the chain, and undoComposition() runs d's undoAction in reverse, then the default no-op for 3. A mismatched key before d drops the chain without recording it; add exclusive: true to keep waiting instead.
How a chain ends
| Outcome | Trigger | Undo buffer | Event |
|---|---|---|---|
| Recorded | Timeout, isEndKey, execute returns null, abortComposition() | Yes | completed; explicit abort is aborted |
| Dropped | A key matches no entry, or a value guard rejects it | No | broken |
- With
exclusive: true, a mismatched key is swallowed and the chain keeps waiting; the eventual timeout records it. - When
isEndKeymatches,executestill runs (side effects are kept), but its returned context is discarded and the key itself is not recorded—only the keys before it are. executereturningnullterminates deliberately; the terminating key is likewise not recorded. The breaking key continues to lower stages by default;SwallowKeyWhenChainInterrupted: trueswallows it. Either way, a key that settles the chain is never re-read as a chain head: even when the same physical key is also registered as a head, its callbacks run once.- A value-guard failure (input or output) clears the pending chain and warns outside production.
Value validation
setValueSchema(schema: ValueSchema)ValueSchema is Record<flagName, (value) => boolean>. The engine validates the input value under the current lastFlag before execute, and the output value under the new flag after it; flags without a guard pass.
setValueSchema({
times: (v): v is number => typeof v === 'number',
action: (v) => typeof v === 'number',
})Undo
undoComposition(steps = 1, options?: { isolated?: boolean; byKey?: boolean })stepscounts chains by default;byKey: truecounts individual keys.isolated: false(default) passes the context across chains;truestarts each chain from its own savedctx.- Returns the context after undo, or
nullwhen nothing is buffered. - Requesting more than buffered throws:
Cannot undo N sequence(s): only M buffered.(key(s)withbyKey). - When an
undoActionreturnsnull, the walk stops; that entry and everything older stay buffered.
const { undoComposition, bufferedCompositionCount, clearCompositionBuffers } = useKeyboard()
undoComposition()
undoComposition(2, { byKey: true })
bufferedCompositionCount()
clearCompositionBuffers()Events
subscribeComposition(fn: () => void): () => void
getLastCompositionEvent(): CompositionEvent | null| Event | When |
|---|---|
started | A head key executed |
continued | A continuation key executed |
completed | The chain completed and was recorded |
aborted | abortComposition() |
broken | A key matched nothing; the chain was dropped |
consumed | An exclusive chain swallowed a mismatched key |
undone | undoComposition() finished; steps is the actual count |
cleared | clearCompositionBuffers() |
getCompositionContext() returns a shallow copy of the current context; hasPendingComposition() reports whether a chain is pending.
Interaction with mappings
Mappings run before composition. addMapping(base, target) redirects an external sequence base to a chain of registered composition keys target; the target chain goes through the same validation, termination, and undo logic as typed input. Pending mapping and composition states are mutually exclusive, and mappings win. See Mapping keys.
Boundaries
- Composition entries share
when/mode/category/affectOverlaywith other bindings;affectOverlay: trueruns before the layer broadcast. categoryis compared by reference against the current top screen: omitted or"*"means all screens,[]means none. Entries that differ only bycategoryare separate registrations and do not dedupe each other.- A key without a pending chain and without
optionalcannot start one. - A screen switch does not clear the undo buffer; call
clearCompositionBuffers()when needed. abortComposition()also cancels a pending mapping sequence.- One key can have several entries;
removeCompositionKeyremoves all of them.
