menu

The Menu component creates an interactive selectable menu in the terminal with keyboard and mouse support. It displays a list of items with customizable icons, focus styles, and emits events on selection. It extends EventEmitter for type-safe event handling.

Example of ts-better-console menu component in action

Constructor

new Menu(
items: MenuItemOptions[],
options?: MenuOptions,
)

Parameters

  • items: An array of MenuItemOptions objects, each defining a menu item's label and optional style/focus style.
  • options: An optional MenuOptions object to configure selected/unselected icons (defaults to / ), default index, item style, and focus style.

Methods

  • show(): Renders the menu and starts listening for mouse and keyboard input. Hides the cursor and enables raw mode.
  • destroy(): Stops listening, restores terminal state, and emits the "exit" event.

Events

  • "select": Emitted when an item is selected via click or Enter. Passes (label: string, index: number).
  • "exit": Emitted when the menu is destroyed (via q, Ctrl+C, or destroy()).

Usage

import { Menu } from "ts-better-console";

const menu = new Menu([
{ label: "Option 1" },
{ label: "Option 2" },
{ label: "Option 3" },
]);

menu.on("select", (label, index) => {
console.log(`Selected: ${label}`);
});

menu.show();

Want to support this project?

If you find ts-better-console useful and want to support its development, consider starring the GitHub repository or buying me a coffee! Your support helps me dedicate more time to improving the library and adding new features.

Want to contribute to this project?

Contributions are welcome! If you're interested in improving the library, fixing bugs, or adding new features, feel free to check out the GitHub repository and submit a pull request. Whether you're a seasoned developer or new to open source, your contributions can make a difference!