vapor/console-kit

Fancier text coloring

NathanFlurry opened this issue · 4 comments

Name of Feature

Introduction

Sometimes, it's handy to change colors of text in a console. Right now, it's not a very fluent process to do that.

Motivation

The goal is to make styling text in the console a much easier process.

Proposed solution

Create an class called Styler. This class would look something like this:

class Styler: CustomStringConvertible {
    var str: String
    var color: ConsoleColor = .none
    var bgColor: ConsoleColor = .none
    var modifier: ConsoleModifier = .none // e.g. bold, dim, underline, etc.

    var description: String {
        // Stylize the string and reset after string finished
    }

    init(str: String) {
        self.str = str
    }

    // Modifiers
    var red: Styler {
        color = .red
        return self
    }
    var blue: Styler {
        color = .blue
        return self
    }
    ...
    var bold: Styler {
        modifier = ConsoleModifier(raw: modifier.rawValue | ConsoleModifier.bold)
        return self
    }
}

Then, it could be used like this:

console.info("Plain text, \( Styler("blue text").blue ), \( Styler("bold text").bold.bgGreen.white ), \( Styler("no text").hidden.bgBlue.white ).")

With a bit more tweaking, it could be used for nested styling.

Note: The idea was borrowed from here.

Impact

This will not change any existing applications.

Alternatives considered

We could stick with the existing way of styling colors, which is a bit painful.

One of the big issues with this is Styler does not know what ConsoleProtocol it came from. Different consoles will have different methods for styling text. That's part of the reason for the difficult syntax.

It would need to be something like console.style("blah", .blue)

or a let styler = Styler(formatter:customformatter)

console.plain("Plain text").styled("blue text").blue.styled("bold text").bold.bgGreen.white.styled("no text").hidden.bgBlue.white.info()

its a builder entry points .plain and .styled and the builder can closed with:

xxx.info()
xxx.error()
xxx.warning()

or with only one entry point and when no modifier is attached, then this text is not styled

console.text("Plain text").text("blue text").blue.text("bold text").bold.bgGreen.white.text("no text").hidden.bgBlue.white.info()

Closing due to inactivity. Please feel free to reopen.