# colorix

> 🖌️ Colorize strings with LITERAL ANSI encodings!

Latest version **2.0.2** (published 2023-03-24) · GPL-3.0 license · 0 weekly downloads

## Install

```sh
npm install colorix
pnpm add colorix
yarn add colorix
bun add colorix
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.0.2 |
| Published | 2023-03-24 |
| First published | 2023-01-28 |
| Weekly downloads | 0 |
| License | GPL-3.0 |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 4 |
| Unpacked size | 118.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 2 |
| Author | cuppachino |
| Maintainers | cuppachino |
| Keywords | ansi, color, colors, console, terminal, pretty |

## Links

- npm: https://www.npmjs.com/package/colorix
- Repository: https://github.com/Cuppachino/colorix
- Homepage: https://github.com/Cuppachino/colorix#readme
- Issues: https://github.com/Cuppachino/colorix/issues
- npm.io page: https://npm.io/package/colorix

## Dependencies (4)

- [strip-ansi](https://npm.io/package/strip-ansi.md) ^7.0.1
- [supports-color](https://npm.io/package/supports-color.md) ^9.3.1
- [@cuppachino/type-space](https://npm.io/package/@cuppachino/type-space.md) ^1.16.0
- [@type-challenges/utils](https://npm.io/package/@type-challenges/utils.md) ^0.1.1

## Alternatives

- [postcss-color-hex-alpha](https://npm.io/package/postcss-color-hex-alpha.md) — 6.4M weekly downloads
- [randomcolor](https://npm.io/package/randomcolor.md) — 348.0K weekly downloads
- [bows](https://npm.io/package/bows.md) — 1.3K weekly downloads
- [ep_prefer_color_scheme](https://npm.io/package/ep_prefer_color_scheme.md) — 260 weekly downloads
- [coc-yank](https://npm.io/package/coc-yank.md) — 61 weekly downloads

## Recent versions

- 2.0.2 (latest) — 2023-03-24
- 2.0.1 — 2023-03-24
- 2.0.0 — 2023-03-24
- 1.3.3 — 2023-03-05
- 1.3.2 — 2023-03-05
- 1.3.1 — 2023-02-19
- 1.3.0 — 2023-02-19
- 1.2.3 — 2023-02-17
- 1.2.2 — 2023-02-16
- 1.2.1 — 2023-02-16
- 1.2.0 — 2023-02-16
- 1.0.3 — 2023-01-29
- 1.0.2 — 2023-01-29
- 1.0.1 — 2023-01-28
- 1.0.0 — 2023-01-28

## README

# Colorix

Colorix provides a simple way to define and layer color presets, and helps you recognize and track ANSI escape sequences in your code. Each module uses template literals (and a bit of magic 🪄) to construct a type representation of the color sequences applied to your strings.

```ts
import cx from 'colorix'

const goblinInk = cx('bgGreen', 'black', 'bold')
console.log(goblinInk('hello goblin', '!'))
```

![goblin-example](./public/globin-example.jpg)

## With TypeScript, *always* know when a string has <u>hidden characters</u>

```ts
declare const goblinMessage: Colorix<['bgGreen', 'black', 'bold'], ['hello goblin', '!']>
// => `\u001B[42;30;1mhello goblin!\u001B[0m`
```

### This is useful with primitive strings as well

```ts
declare const goblinMessage: Colorix<['bgGreen', 'black', 'bold'], [string, ...string[]]>
// => `\u001B[42;30;1m${string}\u001B[0m`
```

## How it works

```ts
// create a theme by passing colors to the first function.
declare const cx: <Colors extends Color[]>(
  ...colors: Colors
) => // then pass stringifiable values to the second function to colorize them.
<Strings extends Stringifiable[]>(
  ...strings: Strings
) => // the returned value is an ansified string.
Colorix<Colors, Strings>
```

## Installation

Add `colorix` to your project using your favorite package manager.

### NPM

```hs
npm install colorix
```

### PNPM

```llvm
pnpm add colorix
```

### Yarn

```llvm
yarn add colorix
```

## How to support terminals without color

### `safe`, `colorixSafe`, `cxs`

You can use `safe` to check if the terminal supports color before applying a preset.

```ts
import cx, { safe } from 'colorix'
const errorInk = cx('bold', 'red')

console.log(errorInk('That tasted purple...'))
// "\u001B[mThat tasted purple...\u001B[0m"

console.log(safe(errorInk)('That tasted purple...'))
// "That tasted purple..." | "\u001B[mThat tasted purple...\u001B[0m"
```

Alternatively, use `colorixSafe` / `cxs` for an `Ink` preset that *only* applies colors if the terminal supports it.

```ts
import { cxs, colorixSafe } from 'colorix'

const safeErrorInk = cxs('bold', 'red') // or colorixSafe('bold', 'red')
console.log(safeErrorInk('That tasted purple...'))
```

## Bonus Features

### `ColorixError`

Fun way to colorize error messages without worrying about the terminal supporting color, or importing `colorix` / `cx` / `safe` into many files.

```ts
import { ColorixError } from 'colorix'

const BasicError = new ColorixError(
  'simple message that is always safe to display'
)
const PrettyError = new ColorixError((cx) =>
  cx(
    'white',
    'bgBlue',
    'dim',
    'bold'
  )(
    'Pretty Message',
    cx('reset')(' '),
    cx('underline', 'green')(
      'npmjs.com/package/colorix',
      cx('reset', 'italic')(' '),
      '(this message will always be stripped of color if supportsColor is false)'
    )
  )
)

throw PrettyError
```

### `PrettyError`

For an "out-of-the-box" solution, use `PrettyError`. It provides the same naming and fallback message behavior as `Colorix` without an api for customizing the rest of the error.

```ts
import { PrettyError } from 'colorix'

const IOError = PrettyError('IOError', 'An unknown IO error occurred.')

try {
  throw new IOError()
} catch (err) {
  console.log(err)
}

try {
  throw new IOError('Illegal write operation.', 'more info...')
} catch (err) {
  console.log(err)
}
```

![pretty-error-example](./public/pretty-error-example.png)

![colorix-error-example](./public/colorix-error-example.png)

## Exports

### `default`, `colorix`, `cx`

|                        Colorix                        | Description                                                                                                                                                                                |
| :---------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     [`default` / `cx` / `colorix`](src/index.mts)     | Create presets for colorizing [`Stringifiable`](https://github.com/Cuppachino/type-space/blob/9f1a2d71db0c6ef0e3c74b7f4cbdbe7efc390dcb/src/stringifiable.ts) values. |
| [`cxs` / `colorixSafe`](src/modules/colorix-safe.mts) | Create presets for colorizing when the terminal supports it [`Stringifiable`](https://github.com/Cuppachino/type-space/blob/9f1a2d71db0c6ef0e3c74b7f4cbdbe7efc390dcb/src/stringifiable.ts). |
|            [`safe`](src/modules/safe.mts)             | Call a colorix preset safely `safe(cx( ...colors ))`. |
|    [`ColorixError`](src/modules/colorix-error.mts)    | Create child `Error` classes with colorized messages. |

### Constants

| Name                              | Description                                                          |
| :-------------------------------- | :------------------------------------------------------------------- |
| [`CSI`](src/ansi.mts)             | control sequence introducer (`"\x1b["`)                              |
| [`SGRT`](src/ansi.mts)            | select graphic rendition terminator (`"m"`)                          |
| [`FOREGROUND`](src/colors.mts)    | readonly foreground lookup object                                    |
| [`BACKGROUND`](src/colors.mts)    | readonly background lookup object                                    |
| [`MODIFIER`](src/colors.mts)      | readonly modifier lookup object                                      |
| [`COLORS`](src/colors.mts)        | readonly color lookup object (foreground, background, and modifiers) |
| [`hasBasicColors`](src/index.mts) | boolean indicating if the terminal supports basic colors             |
| [`has256Colors`](src/index.mts)   | boolean indicating if the terminal supports 256 colors               |
| [`has16mColors`](src/index.mts)   | boolean indicating if the terminal supports 16 million colors        |
| [`supportsColor`](src/index.mts)  | boolean indicating if the terminal supports any color                |

### Types

| Generic                                         | Description                                             |
| :---------------------------------------------- | :------------------------------------------------------ |
| [`Colorix`](src/types/colorix.mts)              | utility for creating literals wrapped in ANSI sequences |
| [`ColorSequence`](src/types/color-sequence.mts) | utility for creating literal ANSI sequences             |

| Alias                                           | Description                                                                   |
| :---------------------------------------------- | :---------------------------------------------------------------------------- |
| [`ResetSequence`](src/types/color-sequence.mts) | literal reset sequence that is always appended to the end of a color sequence |
| [`ColorTable`](src/types/colors.mts)            | readonly record of color aliases and color codes                              |
| [`Color`](src/types/colors.mts)                 | a foreground, background, or modifier color (`keyof ColorTable`)              |
| [`ColorCode`](src/types/colors.mts)             | an SGR color code                                                             |
| [`Foreground`](src/types/colors.mts)            | a foreground color                                                            |
| [`Background`](src/types/colors.mts)            | a background color                                                            |
| [`Modifier`](src/types/colors.mts)              | a modifier color                                                              |

#### Color Tables

| Foreground  | Code | Foreground Bright | Code |
| :---------- | :--: | :---------------- | :--: |
| `"black"`   |  30  | `"gray"`          |  90  |
| `"red"`     |  31  | `"redBright"`     |  91  |
| `"green"`   |  32  | `"greenBright"`   |  92  |
| `"yellow"`  |  33  | `"yellowBright"`  |  93  |
| `"blue"`    |  34  | `"blueBright"`    |  94  |
| `"magenta"` |  35  | `"magentaBright"` |  95  |
| `"cyan"`    |  36  | `"cyanBright"`    |  96  |
| `"white"`   |  37  | `"whiteBright"`   |  97  |

| Background    | Code | Background Bright   | Code |
| :------------ | :--: | :------------------ | :--: |
| `"bgBlack"`   |  40  | `"bgGray"`          | 100  |
| `"bgRed"`     |  41  | `"bgRedBright"`     | 101  |
| `"bgGreen"`   |  42  | `"bgGreenBright"`   | 102  |
| `"bgYellow"`  |  43  | `"bgYellowBright"`  | 103  |
| `"bgBlue"`    |  44  | `"bgBlueBright"`    | 104  |
| `"bgMagenta"` |  45  | `"bgMagentaBright"` | 105  |
| `"bgCyan"`    |  46  | `"bgCyanBright"`    | 106  |
| `"bgWhite"`   |  47  | `"bgWhiteBright"`   | 107  |

| Modifier          | Code |
| :---------------- | :--: |
| `"reset"`         |  0   |
| `"bold"`          |  1   |
| `"dim"`           |  2   |
| `"italic"`        |  3   |
| `"underline"`     |  4   |
| `"inverse"`       |  7   |
| `"hidden"`        |  8   |
| `"strikethrough"` |  9   |

---
_Source: https://npm.io/package/colorix · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
