Transforming action generators #
Rather than writing a generator from scratch, you can often
adapt an existing one, such as the ones provided as defaults.
Action
generators have map, filter, and
flatMap methods that work similarly to those in
Array. Weights are preserved when transforming a
generator. Use isAction to check what kind of
action you’re dealing with, which also narrows its type.
The difference between the two mapping methods is what the
function returns. With map, each action is replaced
by a single other action. With flatMap, each action
is replaced by an array of actions, picked uniformly, or by
another action generator. Returning an empty array from
flatMap drops the action.
Here’s the default typeBasicInput generator,
never typing Enter. It uses flatMap to drop actions
whose charset ends up empty:
import { CharSet, isAction } from "@antithesishq/bombadil/actions";
import { typeBasicInput } from "@antithesishq/bombadil/terminal/defaults";
export const typeWithoutEnter = typeBasicInput.flatMap((action) => {
if (!(isAction(action, "TypeText") && CharSet.is(action.TypeText))) {
return [action];
}
const set = action.TypeText.CharSet.filter(
(entry) =>
!(CharSet.Entry.is(entry, "Literal") && entry.Literal === "\r"),
);
return set.length > 0 ? [{ TypeText: { CharSet: set } }] : [];
});Only export the transformed typeBasicInput and
not the original definition. Otherwise Bombadil will still be
able to type Enter.
To enable a generator only in certain states, use
when with a boolean, a cell, or a function
returning a boolean. When the condition is false, the generator
isn’t run at all:
import { extract } from "@antithesishq/bombadil/terminal";
import { typeBasicInput } from "@antithesishq/bombadil/terminal/defaults";
const idle = extract(
(state) =>
!state.grid.rowText(state.grid.size.rows - 1).includes("Loading"),
);
export const typeWhenIdle = typeBasicInput.when(idle);