button

The ButtonGroup component creates an interactive row of clickable buttons in the terminal. It supports mouse clicks, keyboard navigation (arrow keys + Enter), and customizable styling with hover effects. It extends EventEmitter for type-safe event handling.

Example of ts-better-console buttons in action

Constructor

new ButtonGroup(
buttons: ButtonOptions[],
options?: ButtonGroupOptions,
)

Parameters

  • buttons: An array of ButtonOptions objects, each defining a button's label, click handler, and optional style/hover style.
  • options: An optional ButtonGroupOptions object to configure the gap between buttons (defaults to 2), border style, alignment ("left", "center", "right", "start", "end"), and position ("inline", "top", "bottom").

Methods

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

Events

  • "click": Emitted when a button is clicked or activated via Enter. Passes (label: string, index: number).
  • "exit": Emitted when the button group is destroyed (via q, Ctrl+C, or destroy()).

Usage

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

const buttons = new ButtonGroup([
{
label: "Accept",
onClick: () => console.log("Accepted!"),
style: { color: "white", backgroundColor: "green" },
hoverStyle: { color: "white", backgroundColor: "cyan", styles: ["bold"] },
},
{
label: "Decline",
onClick: () => console.log("Declined!"),
style: { color: "white", backgroundColor: "red" },
},
]);

// Listen for click events
buttons.on("click", (label, index) => {
console.log(`Clicked: ${label} at index ${index}`);
});

// Show the buttons
buttons.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!