Clack Documentation

repository·main·Indexed 27 days ago

https://github.com/bombshell-dev/clack

A library for creating interactive command-line interfaces in JavaScript and TypeScript. It consists of two main packages: @clack/prompts, which provides opinionated, ready-to-use components like text, password, select, and multiline prompts, and @clack/core, which offers headless, unstyled primitives such as the Prompt base class and specific prompt implementations for full visual control. Includes utilities for spinners, progress bars, grouped prompts, and styled logging.

Tokens
6.8K
Snippets
28
Records
45
Agent score
93%

What's inside Clack

  1. Overview of Clack for JavaScript CLIs

    main

    Clack provides stylish, interactive prompts for building JavaScript command-line interfaces (CLIs). It is split into two main packages depending on your needs:

    • @clack/prompts: Provides opinionated, ready-to-use prompt components for quick implementation.
    • @clack/core: Provides headless, unstyled prompt primitives for developers who want full control over the visual presentation.
  2. Overview of @clack/core primitives

    main
    @clack/core provides low-level primitives for building custom command-line applications. It exposes a base Prompt class and specific prompt implementations including TextPrompt, SelectPrompt, and ConfirmPrompt. Each prompt instance allows for a custom render function to control the CLI output.
  3. Handle user cancellation (CTRL + C)

    main

    The isCancel function detects if a user has cancelled a prompt (e.g., via CTRL + C). Use the cancel utility to display a clean cancellation message and exit the process gracefully.

    import { isCancel, cancel, text } from '@clack/prompts';
    
    const value = await text({
      message: 'What is the meaning of life?',
    });
    
    if (isCancel(value)) {
      cancel('Operation cancelled.');
      process.exit(0);
    }
  4. Implement a custom TextPrompt with @clack/core

    main

    To create a custom text input, instantiate TextPrompt and provide a render function. Inside the render function, you can access this.userInputWithCursor to manage the visual state of the input. Use the isCancel utility to check if the user aborted the prompt (e.g., via Ctrl+C).

    import { TextPrompt, isCancel } from '@clack/core';
    
    const p = new TextPrompt({
      render() {
        return `What's your name?\n${this.userInputWithCursor}`;
      },
    });
    
    const name = await p.prompt();
    if (isCancel(name)) {
      process.exit(0);
    }
  5. Stream log messages

    main

    Use the stream API to log messages from an iterable (including async iterables), which is useful when interacting with streaming LLMs.

    import { stream } from '@clack/prompts';
    
    stream.info((function *() { yield 'Info!'; })());
    stream.success((function *() { yield 'Success!'; })());
    stream.step((function *() { yield 'Step!'; })());
    stream.warn((function *() { yield 'Warn!'; })());
    stream.error((function *() { yield 'Error!'; })());
    stream.message((function *() { yield 'Hello'; yield ", World" })(), { symbol: color.cyan('~') });
  6. Group multiple prompts together

    main

    Use group to organize multiple prompts into a single logical unit. The group accepts a JSON object where keys are names and values are functions returning prompts. You can provide an onCancel callback to handle user cancellation for the entire group.

    import * as p from '@clack/prompts';
    
    const group = await p.group(
      {
        name: () => p.text({ message: 'What is your name?' }),
        age: () => p.text({ message: 'What is your age?' }),
        color: ({ results }) =>
          p.multiselect({
            message: `What is your favorite color ${results.name}?`,
            options: [
              { value: 'red', label: 'Red' },
              { value: 'green', label: 'Green' },
              { value: 'blue', label: 'Blue' },
            ],
          }),
      },
      {
        onCancel: ({ results }) => {
          p.cancel('Operation cancelled.');
          process.exit(0);
        },
      }
    );
    
    console.log(group.name, group.age, group.color);
  7. Use taskLog for continuous sub-process output

    main

    The taskLog utility allows you to render the output of a sub-process continuously and clear it upon success, providing a clean interface for long-running tasks.

    import { taskLog } from '@clack/prompts';
    
    const log = taskLog({
    	title: 'Running npm install'
    });
    
    for await (const line of npmInstall()) {
    	log.message(line);
    }
    
    if (success) {
    	log.success('Done!');
    } else {
    	log.error('Failed!');
    }
  8. Execute multiple tasks in spinners

    main

    The tasks utility allows you to execute multiple asynchronous tasks within a spinner interface.

    import { tasks } from '@clack/prompts';
    
    await tasks([
      {
        title: 'Installing via npm',
        task: async (message) => {
          // Do installation here
          return 'Installed via npm';
        },
      },
    ]);
  9. Log messages with different levels

    main

    Use the log utility to print styled messages to the console. Supported levels include info, success, step, warn, and error.

    import { log } from '@clack/prompts';
    
    log.info('Info!');
    log.success('Success!');
    log.step('Step!');
    log.warn('Warn!');
    log.error('Error!');
    log.message('Hello, World', { symbol: color.cyan('~') });
  10. Configure the Date prompt with DateOptions

    main

    When using the DatePrompt (or the corresponding date prompt function in @clack/prompts), you can provide a DateOptions object to control its behavior.

    Key options include:

    • format: A DateFormat string ('YMD', 'MDY', or 'DMY') to define the order of year, month, and day.
    • locale: A string representing a BCP 47 language tag. If provided, the prompt will attempt to detect the appropriate date format and separator using Intl.DateTimeFormat.
    • separator: A custom string used to separate date segments (e.g., /, -). If format is provided, this defaults to / if not specified.
    • defaultValue: The Date object returned if the user cancels or provides an invalid input.
    • initialValue: The Date object used to pre-fill the prompt segments.
    • minDate: The earliest valid Date allowed.
    • maxDate: The latest valid Date allowed.