cliui

repository·master·Indexed 18 days ago

https://github.com/yargs/cliui

A utility for creating complex, multi-column command-line interfaces with support for padding, alignment, and text wrapping. It features a Layout DSL for quick formatting using special characters and supports Deno and ECMAScript Modules (ESM) as of v7. The library provides methods like div() for creating rows and columns, span() for spanning rows, and toString() to render the final formatted layout.

Tokens
1.7K
Snippets
10
Records
15
Agent score
63%

What's inside cliui

  1. Use the Layout DSL for quick formatting

    master

    When passing a single string to ui.div(), you can use special characters to define the layout structure:

    • \n: Interpreted as new rows.
    • \t: Interpreted as new columns.
    • \s: Interpreted as padding.

    Example:

    var ui = require('./')({
      width: 60
    })
    
    ui.div(
      'Usage: node ./bin/foo.js\n' +
      '  <regex>\t  provide a regex\n' +
      '  <glob>\t  provide a glob\t [required]'
    )
    
    console.log(ui.toString())
  2. Use cliui with Deno or ESM

    master

    As of v7, cliui supports Deno and ECMAScript Modules (ESM).

    import cliui from "cliui";
    import chalk from "chalk";
    // Deno: import cliui from "https://deno.land/x/cliui/deno.ts";
    
    const ui = cliui({});
    // ... usage same as CJS
  3. Create a multi-column CLI layout

    master

    Use cliui to build complex command-line interfaces with columns, padding, and alignment. You can pass strings or configuration objects to define rows and columns. Use .toString() to retrieve the final formatted string.

    const ui = require('cliui')()
    const {Chalk} = require('chalk');
    const chalk = new Chalk();
    
    ui.div('Usage: $0 [command] [options]')
    
    ui.div({
      text: 'Options:',
      padding: [2, 0, 1, 0]
    })
    
    ui.div(
      {
        text: "-f, --file",
        width: 20,
        padding: [0, 4, 0, 4]
      },
      {
        text: "the file to load." +
          chalk.green("(if this description is long it wraps).")
        ,
        width: 20
      },
      {
        text: chalk.red("[required]"),
        align: 'right'
      }
    )
    
    console.log(ui.toString())
  4. Configure cliui instance options

    master

    When initializing cliui(), you can pass a configuration object:

    • width (integer): Specifies the maximum width of the UI. If not provided, it attempts to detect the window width, falling back to 80.
    • wrap (boolean): Enables or disables text wrapping within a column.
    const ui = cliui({ width: 60, wrap: true });
  5. Configure UIOptions

    master

    When initializing cliui, you can provide a UIOptions object to control the layout behavior:

    • width (number): The total width of the layout. If not provided, it defaults to the terminal's column width (or 80 if unavailable).
    • wrap (boolean, optional): Whether to enable word wrapping. Defaults to true if not specified.
    • rows (string[], optional): Pre-defined rows for the UI.
  6. Create rows and columns with div()

    master

    The div() method is the primary way to add rows to your layout. It accepts an array of Column objects or plain strings.

    If you pass a single string containing tabs (\t) and newlines (\n), cliui will automatically apply a Layout DSL to parse it into a table structure.

    Column Object Properties:

    • text (string): The content of the column.
    • width (number, optional): Explicit width for the column.
    • align ('right' | 'left' | 'center', optional): Horizontal alignment of text.
    • padding (number[], optional): An array of 4 numbers representing [top, right, bottom, left] padding.
    • border (boolean, optional): If true, renders a border around the column content.
    ui.div(
      { text: 'Name', width: 10, border: true },
      { text: 'Value', align: 'right' }
    );
    
    // Using Layout DSL with a single string
    ui.div("Name\tValue\nAlice\t10\nBob\t20");
  7. Initialize cliui in ESM environments

    master

    In ESM environments, you can import the default export ui to initialize cliui with pre-configured dependencies for handling string widths, stripping ANSI escape codes, and wrapping ANSI-encoded text. This ensures consistent terminal output behavior.

    import ui from 'cliui';
    
    const layout = ui({
      // options for cliui
    });
  8. Render the layout to a string with toString()

    master

    To get the final formatted string representation of your layout, call toString(). This method processes all rows, applies alignment, padding, borders, and word wrapping, and joins the lines into a single string. Lines marked as hidden are excluded from the output.

    const output = ui.toString();
    console.log(output);
  9. Initialize cliui for multi-column layouts

    master

    To create a new UI instance for building CLI layouts, use the cliui function. It requires a mixin object containing utility functions for string manipulation and a partial UIOptions object.

    Required Mixin Interface:

    • stringWidth(str: string): number
    • stripAnsi(str: string): string
    • wrap(str: string, width: number, options: { hard: boolean }): string[]
    import { cliui } from 'cliui';
    
    // Example mixin implementation
    const mixin = {
      stringWidth: (s) => s.length, // Simplified for example
      stripAnsi: (s) => s,
      wrap: (s, w) => [s].split('\n')
    };
    
    const ui = cliui({ width: 80, wrap: true }, mixin);
  10. Create spanning rows with span()

    master

    Use the span() method to create a row that spans across the entire width of the layout. This is useful for headers or separators. It behaves like div() but marks the resulting columns as having span: true, which affects how they are rendered inline with subsequent rows.

    ui.span('This is a full-width header');