TTY::Box

repository·master·Indexed 41 days ago

https://github.com/piotrmurach/tty-box

A component of the TTY toolkit for drawing frames and boxes in terminal emulators. It provides methods like TTY::Box.frame for custom boxes and semantic methods such as TTY::Box.info, TTY::Box.warn, TTY::Box.success, and TTY::Box.error for pre-styled message boxes. Supports absolute positioning, custom border types (:ascii, :light, :thick), alignment, padding, and foreground/background styling.

Tokens
3.3K
Snippets
15
Records
15
Agent score
51%

What's inside TTY::Box

  1. Install TTY::Box

    master

    You can install tty-box using Bundler by adding it to your Gemfile, or by installing the gem directly via the command line.

    Using Bundler: Add gem "tty-box" to your Gemfile and run bundle.

    Using gem command: Run gem install tty-box.

    # In your Gemfile
    gem "tty-box"
    $ bundle
    # or
    $ gem install tty-box
  2. Install and use TTY::Box

    master

    To use TTY::Box in your Ruby project, require the library. The main entry point is through the TTY::Box module, which provides methods for drawing boxes in the terminal.

    Note: This file acts as a simple entry point that requires the core logic from tty/box.

    require "tty-box"
  3. Draw a box using TTY::Box.frame

    master

    The primary way to draw a box is using the TTY::Box.frame method. You provide the lines of text to be included in the box, and you can pass an options hash to control layout and appearance (such as padding and align).

    Example of creating a box with centered text and padding:

    box = TTY::Box.frame "Drawing a box in", "terminal emulator", padding: 3, align: :center
    print box
    # =>
    # ┌───────────────────────┐
    # │                       │
    # │                       │
    # │                       │
    # │   Drawing a box in    │
    # │   terminal emulator   │
    # │                       │
    # │                       │
    # │                       │
    # └───────────────────────┘
  4. Configure box borders and styles

    master

    Border Types

    Set the :border keyword to one of the following:

    • :ascii
    • :light (default)
    • :thick

    Customizing Border Parts

    You can pass a hash to :border to customize specific parts or use false to remove them.

    Border parts: :top, :top_left, :top_right, :left, :right, :bottom_left, :bottom_right, :bottom.

    Border values: :line, :pipe, :cross, :divider_up, :divider_down, :divider_left, :divider_right, :corner_top_left, :corner_top_right, :corner_bottom_left, :corner_bottom_right.

    Styling

    Use the :style keyword to set foreground (:fg) and background (:bg) colors for both the content and the border. Use enable_color: true to force color output.

    # Customizing specific corners with :cross
    box = TTY::Box.frame(
      width: 10, height: 4,
      border: {
        top_left: :cross,
        top_right: :cross,
        bottom_left: :cross,
        bottom_right: :cross
      }
    )
    
    # Styling with colors
    TTY::Box.frame({
      enable_color: true,
      style: {
        fg: :bright_yellow,
        bg: :blue,
        border: {
          fg: :bright_yellow,
          bg: :blue
        }
      }
    })
  5. Position and dimension a box

    master

    Boxes can be positioned absolutely or sized based on the terminal window.

    • Absolute Positioning: Use :top and :left keyword arguments to place the box at a specific row and column (e.g., top: 5, left: 10).
    • Dimensions: Use :width and :height to set fixed sizes.
    • Terminal Sizing: To make a box span the entire terminal, combine TTY::Box with tty-screen to get TTY::Screen.width and TTY::Screen.height.
    # Fixed size and absolute position
    TTY::Box.frame(width: 30, height: 10, top: 5, left: 10)
    
    # Full terminal size (requires tty-screen)
    TTY::Box.frame(width: TTY::Screen.width, height: TTY::Screen.height)
  6. Use predefined message boxes

    master

    TTY::Box provides semantic methods for drawing common message types. These methods automatically apply specific icons and labels.

    • TTY::Box.info(content): Displays an information box (ℹ INFO).
    • TTY::Box.warn(content): Displays a warning box (⚠ WARNING).
    • TTY::Box.success(content): Displays a success box (✔ OK).
    • TTY::Box.error(content): Displays an error box (⨯ ERROR).
    print TTY::Box.info("Deploying application")
    print TTY::Box.warn("Deploying application")
    print TTY::Box.success("Deploying application")
    print TTY::Box.error("Deploying application")
  7. Add titles to a box frame

    master

    You can add text to specific corners of the box using the :title keyword. The value should be a hash where keys represent the position and values represent the title text.

    Available position keys:

    • :top_left
    • :top_center
    • :top_right
    • :bottom_left
    • :bottom_center
    • :bottom_right
    box = TTY::Box.frame(width: 30, height: 10, title: {top_left: "TITLE", bottom_right: "v1.0"})
    print box
  8. Format content with alignment and padding

    master

    Use :align to set content alignment to :left, :center, or :right.

    Use :padding to add space around the content. Padding can be defined as:

    • An integer (e.g., 1 is shorthand for [1,1,1,1]).
    • An array of two integers [left_right, top_bottom] (e.g., [1,3]).
    • An array of four integers [top, right, bottom, left] (e.g., [1,3,1,3]).
    # Centered content with padding
    box = TTY::Box.frame(width: 30, height: 10, align: :center, padding: 3) do
      "Drawing a box in terminal emulator"
    end
  9. Draw a box with TTY::Box.frame

    master

    The frame method is the primary way to draw a box. You can pass content as multiple arguments, a single string with newline characters, or via a block. If no content is provided, you must specify width and height to define the box dimensions.

    Ways to provide content:

    • Multiple arguments: TTY::Box.frame "Hello", "world!"
    • Newline characters: TTY::Box.frame "Hello\nworld!"
    • Block: TTY::Box.frame { "Hello world!" }
    # Basic usage with a single string
    print TTY::Box.frame "Hello world!"
    
    # Multi-line content via arguments
    print TTY::Box.frame "Hello", "world!"
    
    # Multi-line content via block
    print TTY::Box.frame(width: 30, height: 10) do
      "Drawing a box in terminal emulator"
    end
  10. Configure box styling with fg and bg colors

    master

    Styling is managed via the style hash. You can set foreground (fg) and background (bg) colors for the content, and separate colors for the border.

    Example configuration:

    style: {
      fg: :black,
      bg: :bright_blue,
      border: {
        fg: :black,
        bg: :bright_blue
      }
    }

    Colors should be valid symbols compatible with the Pastel gem (e.g., :red, :bright_yellow, :black).

    TTY::Box.new("Styled Content", style: { fg: :white, bg: :blue, border: { fg: :yellow, bg: :blue } }).render
  11. Use semantic message frames (info, success, warn, error)

    master

    The TTY::Box class provides several class methods for rendering pre-styled semantic frames. These methods automatically set titles, borders, and colors suitable for the message type.

    • TTY::Box.info(*messages, **opts): Blue background, ℹ INFO title.
    • TTY::Box.success(*messages, **opts): Green background, ✔ OK title.
    • TTY::Box.warn(*messages, **opts): Yellow background, ⚠ WARNING title.
    • TTY::Box.error(*messages, **opts): Red background, ⨯ ERROR title.

    All these methods accept the same **opts as the standard frame method, allowing you to override default styling or dimensions.

    puts TTY::Box.info("System is starting...")
    puts TTY::Box.success("Operation completed!")
    puts TTY::Box.warn("Disk space is low")
    puts TTY::Box.error("Critical failure")
  12. Initialize and configure a TTY::Box instance

    master

    To create a highly customized box, instantiate TTY::Box.new. You can pass content directly or via a block, and configure the following options:

    OptionTypeDescription
    topIntegerThe offset from the terminal top
    leftIntegerThe offset from the terminal left
    widthIntegerThe maximum width of the box
    heightIntegerThe maximum height of the box
    alignSymbolContent alignment (:left, :center, :right)
    paddingInteger or Array<Integer>Padding around content
    titleHashTitle for borders (keys: :top_left, :top_center, :top_right, :bottom_left, :bottom_center, :bottom_right)
    borderHash or SymbolBorder type (:ascii, :light, :thick)
    styleHashStyling for content and border (keys: fg, bg, and border: { fg, bg })
    enable_colorBooleanWhether to enable color (passed to Pastel)

    Note: If top or left are provided, the box will use cursor movement to render at that specific position in the terminal.

    box = TTY::Box.new("Hello World", 
      width: 40, 
      padding: 1, 
      align: :center, 
      border: :thick,
      title: { top_center: " MY BOX " }
    )
    puts box.render