---
title: Core
description: Learn about the core functionality of Clack
---
import { Tabs, TabItem } from '@astrojs/starlight/components';

The `@clack/core` package provides the fundamental building blocks for creating interactive command-line interfaces. It's designed to be flexible, extensible, and easy to use.

## Key Features

- **Low-level primitives**: Base components for building custom prompts
- **Type-safe**: Built with TypeScript for better developer experience
- **Flexible rendering**: Customizable rendering system for prompts
- **Cancel handling**: Built-in support for handling user cancellation
- **Event system**: Comprehensive event handling for user interactions
- **Input validation**: Built-in support for input validation
- **Abort signal support**: Integration with AbortController for cancellation
- **Custom I/O streams**: Support for custom input/output streams
- **Configurable guide lines**: Toggle the default Clack border with `withGuide`

## Installation

To start using the core package, first install it:

<Tabs>
	<TabItem label="npm" icon="seti:npm">
		```bash
		npm install @clack/core
		```
	</TabItem>
	<TabItem label="pnpm" icon="pnpm">
		```bash
		pnpm add @clack/core
		```
	</TabItem>
	<TabItem label="Yarn" icon="seti:yarn">
		```bash
		yarn add @clack/core
		```
	</TabItem>
</Tabs>

Then import the components you need:

```ts twoslash
import {
  // Prompt classes
  TextPrompt,
  SelectPrompt,
  ConfirmPrompt,
  PasswordPrompt,
  MultiSelectPrompt,
  GroupMultiSelectPrompt,
  SelectKeyPrompt,
  AutocompletePrompt,
  DatePrompt,

  // Layout helpers
  block,
  getColumns,
  getRows,
  wrapTextWithPrefix,

  // Utilities
  isCancel,
  updateSettings,
  settings,

  // Types
  type ClackSettings,
  type PromptOptions,
  type ConfirmOptions,
  type PasswordOptions,
  type MultiSelectOptions,
  type GroupMultiSelectOptions,
  type SelectKeyOptions,
  type AutocompleteOptions,
  type DateFormat,
  type DateOptions,
  type DateParts,
} from '@clack/core';
```

The package exports both the prompt classes and their corresponding options types (e.g., `ConfirmOptions`, `PasswordOptions`) for TypeScript users.

## Package Structure

The core package is organized into two main directories:

- `prompts/`: Contains the base prompt implementations
- `utils/`: Contains utility functions and helpers

## Core Components

### Base Prompt Class

The `Prompt` class serves as the foundation for all prompt types. It provides:

- Custom rendering capabilities
- Input handling
- State management
- Event system
- Validation support
- Abort signal integration

#### Key Methods

```ts
interface Prompt {
  // Event handling
  on<T extends string>(event: T, cb: (value: any) => void): void;
  once<T extends string>(event: T, cb: (value: any) => void): void;
  emit<T extends string>(event: T, ...data: any[]): void;

  // Core functionality
  prompt(): Promise<string | symbol>;
  close(): void;
}
```

#### Available Events

The `Prompt` interface provides several events that can be handled:

```ts twoslash
// @errors: 2304 2314 2345 7006 2353 2459
// @noErrors
import { Prompt } from '@clack/core';

// Example usage
const p = new Prompt({
  render: () => 'Enter your name:'
});

// Handle value changes
p.on('value', (value?: string) => {
  console.log('Value changed:', value);
});

// Handle submission
p.on('submit', (value?: string) => {
  console.log('Submitted:', value);
});

// Handle cancellation
p.on('cancel', () => {
  console.log('Operation cancelled');
});
```

### Available Prompts

1. **TextPrompt**: For text input
   - Supports validation
   - Placeholder text
   - Initial value
   - Separate `userInput` and `value` tracking; use **`userInputWithCursor`** when rendering so the raw buffer and cursor position match what the user sees

2. **SelectPrompt**: For selection from options
   - Custom rendering
   - Option filtering
   - Disabled options support
   - Text wrapping support

3. **ConfirmPrompt**: For yes/no confirmations
   - Yes/No shortcuts
   - Custom messages

4. **AutocompletePrompt**: For searchable selection
   - Type-ahead filtering
   - Custom filtering logic via the `filter` option
   - Multiple selection support (`multiple: true`)
   - Dynamic options (function or array)
   - As of v1.2.0, the built-in default filter runs only when `filter` is set explicitly **or** when `options` is not a getter—so lazy `options` getters are not pre-filtered unexpectedly

5. **PasswordPrompt**: For secure input
   - Character masking
   - Validation support
   - `clearOnError` option to reset on validation failure
   - Empty submit resolves to `""`, matching `TextPrompt` and `Promise<string | symbol>` (v1.4.2)

6. **MultiSelectPrompt**: For multiple selections
   - Checkbox interface
   - Selection limits
   - Custom rendering
   - Disabled options support
   - Invert selection support

7. **GroupMultiSelectPrompt**: For grouped selections
   - Hierarchical options
   - Group selection (`selectableGroups` option)
   - Custom rendering
   - Group spacing control

8. **SelectKeyPrompt**: For key-based selection
   - Custom key bindings
   - Multiple selection support

9. **DatePrompt**: For structured date entry
   - Segment-based editing (year, month, day) with `DateFormat` (`YMD`, `MDY`, or `DMY`)
   - Optional `locale` for segment order and separator via `Intl`
   - Optional `separator` override for display
   - `minDate` / `maxDate` bounds and `DateParts` segment values

10. **Multi-line input**: Use [`multiline()`](/docs/clack/packages/prompts#multi-line-text) from `@clack/prompts` for multi-line text entry (since v1.3.0). `@clack/core` provides the underlying prompt primitive; extend `Prompt` directly only when you need custom multi-line TTY behavior.

## Layout utilities

These helpers are useful when building custom prompts or lists that respect terminal width:

- **`getColumns(output?)` / `getRows(output?)`**: Terminal size for the given writable (defaults to `stdout`).
- **`wrapTextWithPrefix(output, text, prefix, ...)`**: Wrap lines to the terminal width while repeating a prefix on each line (used heavily by prompts for guide-aligned output).
- **`block`**: Lower-level TTY helper (raw mode, keypress handling, optional cursor hide) used when building custom full-screen or overlay flows; most apps use the prompt classes instead.

## Global Settings

The core package provides global settings that affect all prompts:

```ts twoslash
import { updateSettings, settings } from '@clack/core';

// Update global settings
updateSettings({
  // Custom key aliases for navigation
  aliases: {
    w: 'up',
    a: 'left',
    s: 'down',
    d: 'right',
  },
  // Disable guide lines globally
  withGuide: false,
  // Custom messages for i18n
  messages: {
    cancel: 'Operación cancelada',
    error: 'Se produjo un error',
  },
});

// Access current settings
console.log(settings.messages.cancel);
```

### Key Aliases

Default keybindings include Vim-style navigation:

| Key | Action |
|-----|--------|
| `k` | up |
| `j` | down |
| `h` | left |
| `l` | right |
| `Escape` | cancel |

You can add custom aliases but cannot disable the default keybindings.

### Guide Lines

The `withGuide` setting controls the display of Clack's signature border lines. Set to `false` to render prompts without the decorative guide.

## Creating Custom Prompts

You can create custom prompts by extending the base `Prompt` class:

```ts twoslash
// @errors: 2339
import { Prompt } from '@clack/core';

// Example of extending the base Prompt class
class CustomPrompt extends Prompt<string> {
  constructor(options: { message: string }) {
    super({
      ...options,
      render() {
        return `${options.message}\n${this.value ?? ''}`;
      }
    });
  }
}
```

For detailed examples and usage patterns, check out our [examples guide](/docs/clack/guides/examples).