Skip to content

Commit

Permalink
dev: release v2.2.0 (#17)
Browse files Browse the repository at this point in the history
This release adds:

- 256 Color and True Color support and enabler for Windows Console
- `White` and `HiWhite` as inbuilt colors
- Terminal detection for Unix and Windows System and also for rounding off True Color into 4 bit or 8 bit as max supported by the terminal.
- Deprecates `box.Output` for Windows
- Major Code Cleanup
- More comments for better understanding of the CodeBase
- Doc improvements
  • Loading branch information
Delta456 authored Dec 5, 2020
1 parent 34c982c commit 02f7563
Show file tree
Hide file tree
Showing 10 changed files with 329 additions and 174 deletions.
95 changes: 58 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Box CLI Maker is a Highly Customized Terminal Box Creator.
## Features

- Make Terminal Box in 8️⃣ inbuilt different styles
- 16 Inbuilt Colors and Custom (24 bit) Colors Support 🎨
- 16 Inbuilt Colors and True Color Support 🎨
- Custom Title Positions
- Make your own Terminal Box style 📦
- Align the text according to the need
Expand All @@ -42,8 +42,8 @@ package main
import "github.com/Delta456/box-cli-maker/v2"

func main() {
Box := box.New(box.Config{Px: 2, Py: 5, Type: "Single", Color: "Cyan"})
Box.Print("Box CLI Maker", "Highly Customized Terminal Box Maker")
Box := box.New(box.Config{Px: 2, Py: 5, Type: "Single", Color: "Cyan"})
Box.Print("Box CLI Maker", "Highly Customized Terminal Box Maker")
}
```

Expand All @@ -70,7 +70,7 @@ func main() {
- Parameters
- `title` : Title of the Box
- `lines` : Content to be written inside the Box

`Box.String(title, lines string) string` return `string` representation of Box.

- Parameters
Expand Down Expand Up @@ -125,20 +125,19 @@ func main() {

<img src="img/bottom.png" alt="bottom" width="400"/>


### Making custom Box

You can make your custom Box by using the inbuilt Box struct provided by the module.

```go
type Box struct {
TopRight string // TopRight corner used for Symbols
TopLeft string // TopLeft corner used for Symbols
Vertical string // Symbols used for Vertical Bars
BottomRight string // BottomRight corner used for Symbols
BottomLeft string // BotromLeft corner used for Symbols
Horizontal string // Symbols used for Horizontal Bars
Config // Configuration for the Box to be made
TopRight string // TopRight corner used for Symbols
TopLeft string // TopLeft corner used for Symbols
Vertical string // Symbols used for Vertical Bars
BottomRight string // BottomRight corner used for Symbols
BottomLeft string // BotromLeft corner used for Symbols
Horizontal string // Symbols used for Horizontal Bars
Config // Configuration for the Box to be made
}
```

Expand All @@ -152,7 +151,7 @@ import "github.com/Delta456/box-cli-maker/v2"
func main() {
config := box.Config{Px: 2, Py: 3, Type: "", TitlePos: "Inside"}
boxNew := box.Box{TopRight: "*", TopLeft: "*", BottomRight: "*", BottomLeft: "*", Horizontal: "-", Vertical: "|", Config: config}
boxNew.Print("Box CLI Maker", "Make Highly Customized Terminal Boxes")
boxNew.Println("Box CLI Maker", "Make Highly Customized Terminal Boxes")
}
```

Expand All @@ -162,37 +161,45 @@ Output:

### Color Types

It has color support from [fatih/color](https://github.com/fatih/color) module from which this module uses `FgColor` and `FgHiColor`. `Color` is a key for the following maps:
It has color support from [gookit/color](github.com/gookit/color) module from which this module uses `FgColor` and `FgHiColor`. `Color` is a key for the following maps:

```go
var fgColors = map[string]color.Attribute{
"Black": color.FgBlack,
"Blue": color.FgBlue,
"Red": color.FgRed,
"Green": color.FgGreen,
"Yellow": color.FgYellow,
"Cyan": color.FgCyan,
"Magenta": color.FgMagenta,
fgColors map[string]color.Color = {
"Black": color.FgBlack,
"Blue": color.FgBlue,
"Red": color.FgRed,
"Green": color.FgGreen,
"Yellow": color.FgYellow,
"Cyan": color.FgCyan,
"Magenta": color.FgMagenta,
"White": color.FgWhite,
}

var fgHiColors = map[string]color.Attribute{
"HiBlack": color.FgHiBlack,
"HiBlue": color.FgHiBlue,
"HiRed": color.FgHiRed,
"HiGreen": color.FgHiGreen,
"HiYellow": color.FgHiYellow,
"HiCyan": color.FgHiCyan,
"HiMagenta": color.FgHiMagenta,
fgHiColors map[string]color.Color = {
"HiBlack": color.FgDarkGray,
"HiBlue": color.FgLightBlue,
"HiRed": color.FgLightRed,
"HiGreen": color.FgLightGreen,
"HiYellow": color.FgLightYellow,
"HiCyan": color.FgLightCyan,
"HiMagenta": color.FgLightMagenta,
"HiWhite": color.FgLightWhite,
}
```

If you want High Intensity Colors then the Color name should start with `Hi`. If Color option is empty or invalid then Box with default Color is formed.
If you want High Intensity Colors then the Color name must start with `Hi`. If Color option is empty or invalid then Box with default Color is formed.

True Color is possible though you need to provide it as `uint` or `[3]uint` and make sure that the terminals which will be targetted must have it supported.

You can also have more 16 Colors but the terminals must be 24 bit and the `Color` field must be provided either as `[3]uint` or `uint` though the elements of the array must be in a range of `[0x0, 0xFF]` and `uint` must be in a range of `[0x000000, 0xFFFFFF]`.
`[3]uint`'s element all must be in a range of `[0, 0xFF]` and `uint` in range of `[0x000000, 0xFFFFFF]`.

If you want to use the string representation of the `Box` and print them for [`Windows Console`](https://en.wikipedia.org/wiki/Windows_Console) then you would have to use `box.Output` as the passing stream to the respective functions.
As convenience, if the terminal's doesn't support True Color then it will round off according to the terminal's max supported colors which makes it easier for the users not to worry about other terminal for most of the cases.

`Windows Console` is 4 bit (16 colors) so Custom Colors will not work for them but the `Box` will be printed correctly without the Color effect.
Here's a list of 24 bit [supported terminals](https://gist.github.com/XVilka/8346728) and 8 bit [supported terminals](https://fedoraproject.org/wiki/Features/256_Color_Terminals).

This module also enables **True Color** and **256 Colors** support on Windows Console through [Virtual Terminal Processing](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) but you need have at least [Windows 10 Version 1511](https://en.wikipedia.org/wiki/Windows_10_version_history_(version_1511)) for 256 colors or [Windows 10 Version 1607](https://en.wikipedia.org/wiki/Windows_10_version_history_(version_1607)) for True Color Support.

4 bit Color are now supported by every terminal now so there is no list for them unlike the above ones.

### Note

Expand All @@ -204,11 +211,25 @@ As different terminals have different font by default so the right vertical alig

It uses [mattn/go-runewidth](https://github.com/mattn/go-runewidth) for Unicode and Emoji support though there are some limitations:

- `Windows Terminal` and `Windows SubSystem Linux` are the only know terminals which can render Unicode and Emojis properly on Windows.
- Marathi Text only works on very few Terminals as less support it.
- It is recommended not to use Online Playgrounds like [`Go Playground`](https://play.golang.org/) and [`Repl.it`](https://repl.it) because they use a font that only has ASCII support and other Character Set is used which becomes problematic for finding the length as the font changes during runtime.
- `Windows Terminal` and `Mintty` are the only know terminal emulators which can render Unicode and Emojis properly on Windows.
- Indic Text only works on very few Terminals as less support it.
- It is recommended not to use this for Online Playgrounds like [`Go Playground`](https://play.golang.org/) and [`Repl.it`](https://repl.it), `CI/CDs` etc. because they use a font that only has ASCII support and other Character Set is used which becomes problematic for finding the length as the font changes during runtime.
- Change your font which supports Unicode and Emojis else the right vertical alignment will break.

#### Terminal Color Detection

It is possible to round off true color provided to 8 bit or 16 bit according to your terminal's maximum capacity.

There is no **standardized way** of detecting the terminal's maximum color capacity so the way of detecting your terminal might not work for you. If this can be fixed for you then you can always make a PR.

If you think that the module can't detect True Color of the terminal then you must set your environment variable `COLORTERM` to `truecolor` or `24bit` for True Color support.

If you are targetting 8 bit color based terminals and if the module couln't detect it then set your environment variable `TERM` to name of the terminal emulator with `256color` as suffix like `xterm-256color`.

There might be no color effect for very old terminals like [`Windows Console (Legacy Mode)`](https://docs.microsoft.com/en-us/windows/console/legacymode) or environment variable `TERM` give `DUMB` so it will output some garbage value or a warning if used.

In `Online Playgrounds`, `CI/CDs`, `Browsers` etc, it is recommended **not** to use this module with color effect as few may have it but this is hard to detect in general. If you think that it's possible then open an issue and address the solution!

### Acknowledgements

I thank the following people and their packages whom I have studied and was able to port to Go accordingly.
Expand Down
72 changes: 22 additions & 50 deletions box.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ package box

import (
"fmt"
"os"
"runtime"
"strings"

"github.com/fatih/color"
"github.com/gookit/color"
"github.com/mattn/go-runewidth"
)

Expand Down Expand Up @@ -98,47 +96,24 @@ func (b Box) toString(title string, lines []string) string {
Bar := strings.Repeat(b.Horizontal, n-2)
TopBar := b.TopLeft + Bar + b.TopRight
BottomBar := b.BottomLeft + Bar + b.BottomRight

// Check b.TitlePos
if b.TitlePos != "Inside" {
TitleBar := repeatWithString(b.Horizontal, n-2, title)
if b.TitlePos == "Top" {
TopBar = b.TopLeft + TitleBar + b.TopRight
} else if b.TitlePos == "Bottom" {
BottomBar = b.BottomLeft + TitleBar + b.BottomRight
} else {
// Duplicate warning done here if the String() Method is used
// Duplicate warning done here if the String() method is used
// instead of using Print() and Println() methods
errorMsg("[warning]: invalid value provided for TitlePos, using default")
// Using goto here to inorder to exit the current if branch
goto inside
}
}
inside:
if b.Color != nil {
if str, ok := b.Color.(string); ok {
if strings.HasPrefix(str, "Hi") {
if _, ok := fgHiColors[str]; ok {
Style := color.New(fgHiColors[str]).SprintfFunc()
TopBar = Style(TopBar)
BottomBar = Style(BottomBar)
}
} else if _, ok := fgColors[str]; ok {
Style := color.New(fgColors[str]).SprintfFunc()
TopBar = Style(TopBar)
BottomBar = Style(BottomBar)
} else {
errorMsg("[warning]: invalid value provided to Color, using default")
}
} else if hex, ok := b.Color.(uint); ok {
TopBar = rgbHex(hex, TopBar)
BottomBar = rgbHex(hex, BottomBar)
} else if rgb, ok := b.Color.([3]uint); ok {
TopBar = rgbArray(rgb, TopBar)
BottomBar = rgbArray(rgb, BottomBar)
} else {
fmt.Fprintln(os.Stderr, fmt.Sprintf("expected string, [3]uint or uint not %T using default", b.Color))
}
}
// Check type of b.Color then assign the Colors to TopBar and BottomBar accordingly
TopBar, BottomBar = b.checkColorType(TopBar, BottomBar)
if b.TitlePos == "Inside" && runewidth.StringWidth(TopBar) != runewidth.StringWidth(BottomBar) {
panic("cannot create a Box with different sizes of Top and Bottom Bars")
}
Expand Down Expand Up @@ -207,23 +182,32 @@ func (b Box) obtainColor() string {
if b.Color == nil { // if nil then just return the string
return b.Vertical
}
// Check if type of b.Color is string
if str, ok := b.Color.(string); ok {
// Hi Intensity Color
if strings.HasPrefix(str, "Hi") {
if _, ok := fgHiColors[str]; ok {
Style := color.New(fgHiColors[str]).SprintfFunc()
return Style(b.Vertical)
return fgHiColors[str].Sprintf(b.Vertical)
}
} else if _, ok := fgColors[str]; ok {
Style := color.New(fgColors[str]).SprintfFunc()
return Style(b.Vertical)
return fgColors[str].Sprintf(b.Vertical)
}
errorMsg("[warning]: invalid value provided to Color, using default")
// Return a warning as Color provided as a string is unknown and
// return without the color effect
return b.Vertical
// Check if type of b.Color is uint
} else if hex, ok := b.Color.(uint); ok {
return rgbHex(hex, b.Vertical)
// Break down the hex into r, g and b respectively
hexArray := [3]uint{hex >> 16, hex >> 8 & 0xff, hex & 0xff}
col := color.RGB(uint8(hexArray[0]), uint8(hexArray[1]), uint8(hexArray[2]))
return b.roundOffColorVertical(col)
// Check if type of b.Color is [3]uint
} else if rgb, ok := b.Color.([3]uint); ok {
return rgbArray(rgb, b.Vertical)
col := color.RGB(uint8(rgb[0]), uint8(rgb[1]), uint8(rgb[2]))
return b.roundOffColorVertical(col)
}
// Panic if b.Color is an unexpected type
panic(fmt.Sprintf("expected string, [3]uint or uint not %T", b.Color))
}

Expand All @@ -250,13 +234,7 @@ func (b Box) Print(title, lines string) {
}
}
lines2 = append(lines2, strings.Split(lines, n1)...)
if runtime.GOOS == "windows" {
// Windows Console is 4 bit (16 colors only supported) so if the custom color
// is out of their range then just correctly print the Box without the color effect
fmt.Fprint(Output, b.toString(title, lines2))
} else {
fmt.Print(b.toString(title, lines2))
}
color.Print(b.toString(title, lines2))
}

// Println adds a newline before and after the Box
Expand All @@ -282,11 +260,5 @@ func (b Box) Println(title, lines string) {
}
}
lines2 = append(lines2, strings.Split(lines, n1)...)
if runtime.GOOS == "windows" {
// Windows Console is 4 bit (16 colors only supported) so if the custom color
// is out of their range then just correctly print the Box without the color effect
fmt.Fprintf(Output, "\n%s\n", b.toString(title, lines2))
} else {
fmt.Printf("\n%s\n", b.toString(title, lines2))
}
color.Printf("\n%s\n", b.toString(title, lines2))
}
10 changes: 7 additions & 3 deletions box_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func TestInbuiltStyles(t *testing.T) {

func TestPrintColorBox(t *testing.T) {
StyleCases := []string{"Single", "Double", "Single Double", "Double Single", "Bold", "Round", "Hidden", "Classic"}
ColorTypes := []string{"Black", "Blue", "Red", "Green", "Yellow", "Cyan", "Magenta", "HiBlack", "HiBlue", "HiRed", "HiGreen", "HiYellow", "HiCyan", "HiMagenta"}
ColorTypes := []string{"Black", "Blue", "Red", "Green", "Yellow", "Cyan", "Magenta", "White", "HiBlack", "HiBlue", "HiRed", "HiGreen", "HiYellow", "HiCyan", "HiMagenta", "HiWhite"}

for i := 0; i < len(StyleCases); i++ {
for j := 0; j < len(ColorTypes); j++ {
Expand Down Expand Up @@ -103,8 +103,12 @@ func TestUnicodeString(t *testing.T) {
// English, Japanese, Chinese(Traditional), Korean, French, Spanish, Latin, Greek
titles := []string{"Box CLI Maker", "ボックスメーカー", "盒子製造商", "박스 메이커", "Créateur de boîte CLI", "Fabricante de cajas", "Qui fecit me arca CLI", "Κουτί CLI Maker"}
lines := []string{"Make Highly Customized Terminal Boxes", "高度にカスタマイズされた端子ボックスを作成する", "製作高度定制的接線盒", "고도로 맞춤화 된 터미널 박스 만들기", "Créez des boîtes à bornes hautement personnalisées", "Haga cajas de terminales altamente personalizadas", "Fac multum Customized Terminal Pyxidas", "Δημιουργήστε πολύ προσαρμοσμένα τερματικά κουτιά"}
StyleCases := []string{"Single", "Double", "Single Double", "Double Single", "Bold", "Round", "Hidden", "Classic"}
for i := 0; i < len(titles); i++ {
Box := New(Config{Px: 2, Py: 5})
Box.Println(titles[i], lines[i])
for j := 0; j < len(StyleCases); j++ {
Box := New(Config{Px: 2, Py: 5, Type: StyleCases[j]})
Box.Println(titles[i], lines[i])

}
}
}
Loading

0 comments on commit 02f7563

Please sign in to comment.