Select prompt
Build a menu that lets you choose a framework with the arrow keys and Enter.
effect-boxes creates the layout and styling. Effect's Prompt.Custom reads
input and redraws the menu.
┃ Select a framework
┃ ⏵ React
┃ Vue
┃ Svelte
↓ down • ↑ up • enter selectBefore you start
Complete Getting started, then read Using Ansi,
Rendering, and Using Cmd.
This tutorial uses Effect 4 and Effect.gen.
Install the packages and the TypeScript runner:
npm install effect-boxes "effect@^4" "@effect/platform-node@^4"
npm install --save-dev tsxUse an interactive terminal at least 40 columns wide and 8 rows high. The clearing logic counts layout rows and assumes that lines do not wrap.
Save the complete example as SelectPrompt.ts and run
npx tsx SelectPrompt.ts. The step snippets below are continuations of that file.
Use the complete example if you want to copy and run the program directly.
Step 1: Define choices and state
Import the modules and define a nonempty list of choices. The cursor is a zero-based index into that list.
import { Data, Effect, Match, Terminal } from "effect";
import { Prompt } from "effect/cli";
import { NodeRuntime, NodeServices } from "@effect/platform-node";
import { Ansi, Box, Cmd } from "effect-boxes";
type Choice<A> = {
readonly title: string;
readonly value: A;
};
const choices: ReadonlyArray<Choice<string>> = [
{ title: "React", value: "react" },
{ title: "Vue", value: "vue" },
{ title: "Svelte", value: "svelte" },
];
const Action = Data.taggedEnum<Prompt.ActionDefinition>();Step 2: Build the layout
Add renderLayout. The active menu includes a border and keyboard hints.
After submission, the same function returns a one-line confirmation.
const renderLayout = (
cursor: number,
submitted: boolean
): Box.Box<Ansi.AnsiStyle> => {
const label = Box.text("Select a framework").pipe(Box.annotate(Ansi.bold));
if (submitted) {
const selected = choices[cursor];
return Box.hsep(
[
Box.text("✔").pipe(Box.annotate(Ansi.green)),
label,
Box.text(selected?.title ?? "").pipe(Box.annotate(Ansi.cyan)),
],
1,
Box.top
);
}
const items = choices.map((choice, index) => {
const selected = index === cursor;
const indicator = Box.char(selected ? "⏵" : " ").pipe(
Box.annotate(Ansi.cyan)
);
const title = Box.text(choice.title).pipe(
Box.annotate(selected ? Ansi.bold : Ansi.dim)
);
return Box.hsep([indicator, title], 1, Box.top);
});
const chrome = Box.vcat([label, ...items], Box.left).pipe(
Box.pad(0, 1),
Box.border("thick", { sides: { top: false, bottom: false, right: false } })
);
const hint = Box.text("↓ down • ↑ up • enter select").pipe(
Box.annotate(Ansi.dim),
Box.moveRight(2)
);
return Box.vcat([chrome, Box.emptyBox(1, 0), hint], Box.left);
};The preview above uses renderLayout(0, false). Moving the cursor changes
which choice has the arrow and bold text.
Step 3: Render, process input, and clear the previous frame
Add the handlers and the prompt. Prompt.Custom calls render once at
startup. For NextFrame and Submit, it calls clear with the previous state
before rendering the next state. clear does not run as exit cleanup.
const handlers: Prompt.Handlers<number, string> = {
render: (cursor, action) =>
Effect.succeed(
Action.$match(action, {
NextFrame: () =>
Box.renderPrettySync(Cmd.cursorHide) +
Box.renderPrettySync(renderLayout(cursor, false)).replaceAll(
"\n",
"\r\n"
) +
Box.renderPrettySync(Cmd.cursorNextLine(1)),
Submit: () =>
Box.renderPrettySync(renderLayout(cursor, true)) +
Box.renderPrettySync(Cmd.cursorNextLine(1)),
Beep: () => "\u0007",
})
),
process: (input, cursor) =>
Effect.succeed(
Match.value(input).pipe(
Match.when({ key: { name: "down" } }, () =>
Action.NextFrame({ state: (cursor + 1) % choices.length })
),
Match.when({ key: { name: "up" } }, () =>
Action.NextFrame({
state: (cursor - 1 + choices.length) % choices.length,
})
),
Match.when({ key: { name: "return" } }, () => {
const selected = choices[cursor];
return selected
? Action.Submit({ value: selected.value })
: Action.Beep();
}),
Match.orElse(() => Action.NextFrame({ state: cursor }))
)
),
clear: (cursor) =>
Box.renderPretty(Cmd.clearLines(renderLayout(cursor, false).rows + 1)),
};
const select = Prompt.Custom(0, handlers);Each active frame hides the cursor and ends at the start of the next line.
clearLines erases that empty line and every menu row, then returns to the
first column of the first row. The next render replaces the menu in place.
The newline replacement makes each menu row start at column zero in raw mode.
Input keys have a key.name property. Up and Down wrap around the choices.
Enter submits the selected value. Other keys keep the current selection.
All three action cases have render handlers. Beep writes only a bell,
so it does not append another copy of the menu.
Effect's prompt implementation restores cursor visibility on success, failure,
and interruption. The Node terminal layer handles Ctrl+C before process
runs, so a Ctrl+C key handler is unnecessary here.
Step 4: Run the prompt
Add the program and one runtime call at the end of the file:
const program = Effect.gen(function* () {
const result = yield* select;
const terminal = yield* Terminal.Terminal;
yield* terminal.display(`You chose: ${result}\r\n`);
}).pipe(
Effect.catchTag("QuitError", () =>
Effect.gen(function* () {
const terminal = yield* Terminal.Terminal;
yield* terminal.display("Cancelled.\r\n");
})
)
);
NodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)));Press Down once, then Enter. The confirmation shows Vue, followed by
You chose: vue. Press Ctrl+C during selection to end the prompt and print
Cancelled.. The same select value can run again without retaining a render flag.
Complete example
Copy this file without adding the step snippets again. It contains one
NodeRuntime.runMain call.
Next steps
Change the choice titles and values, then run the prompt again. For layouts that update individual regions, read Using Reactive.