Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Sindre Sorhus' open source work is supported by the community on <ahref="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <ahref="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a>
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
Multiple arguments will be separated by space.
### chalk.level
Specifies the level of color support.
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
constctx=newchalk.Instance({level:0});
```
| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
### chalk.stderr and chalk.stderr.supportsColor
`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
## Styles
### Modifiers
-`reset` - Resets the current color chain.
-`bold` - Make text bold.
-`dim` - Emitting only a small amount of light.
-`italic` - Make text italic. *(Not widely supported)*
-`underline` - Make text underline. *(Not widely supported)*
-`inverse`- Inverse background and foreground colors.
-`hidden` - Prints the text, but makes it invisible.
-`strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
-`visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
### Colors
-`black`
-`red`
-`green`
-`yellow`
-`blue`
-`magenta`
-`cyan`
-`white`
-`blackBright` (alias: `gray`, `grey`)
-`redBright`
-`greenBright`
-`yellowBright`
-`blueBright`
-`magentaBright`
-`cyanBright`
-`whiteBright`
### Background colors
-`bgBlack`
-`bgRed`
-`bgGreen`
-`bgYellow`
-`bgBlue`
-`bgMagenta`
-`bgCyan`
-`bgWhite`
-`bgBlackBright` (alias: `bgGray`, `bgGrey`)
-`bgRedBright`
-`bgGreenBright`
-`bgYellowBright`
-`bgBlueBright`
-`bgMagentaBright`
-`bgCyanBright`
-`bgWhiteBright`
## Tagged template literal
Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
```js
constchalk=require('chalk');
constmiles=18;
constcalculateFeet=miles=>miles*5280;
console.log(chalk`
There are {bold 5280 feet} in a mile.
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728)(16 million colors) on supported terminal apps.
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
-[`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
-[`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
## Windows
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
## Origin story
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
## chalk for enterprise
Available as part of the Tidelift Subscription.
The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
-[chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
-[ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
-[supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
Color-convert is a color conversion library for JavaScript and node.
It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
```js
varconvert=require('color-convert');
convert.rgb.hsl(140,200,100);// [96, 48, 59]
convert.keyword.rgb('blue');// [0, 0, 255]
varrgbChannels=convert.rgb.channels;// 3
varcmykChannels=convert.cmyk.channels;// 4
varansiChannels=convert.ansi16.channels;// 1
```
# Install
```console
$npm install color-convert
```
# API
Simply get the property of the _from_ and _to_ conversion that you're looking for.
All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
All functions that accept multiple arguments also support passing an array.
Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
```js
varconvert=require('color-convert');
convert.rgb.hex(123,45,67);// '7B2D43'
convert.rgb.hex([123,45,67]);// '7B2D43'
```
## Routing
Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
# Contribute
If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
TypeScript and Flow definitions for CSS, generated by [data from MDN](https://github.com/mdn/data). It provides autocompletion and type checking for CSS properties and values.
**TypeScript**
```ts
import*asCSSfrom'csstype';
conststyle:CSS.Properties={
colour:'white',// Type error on property
textAlign:'middle',// Type error on value
};
```
**Flow**
```js
// @flow strict
import*asCSSfrom'csstype';
conststyle:CSS.Properties<>={
colour:'white',// Type error on property
textAlign:'middle',// Type error on value
};
```
_Further examples below will be in TypeScript!_
## Getting started
```sh
$ npm install csstype
$ # or
$ yarn add csstype
```
## Table of content
-[Style types](#style-types)
-[At-rule types](#at-rule-types)
-[Pseudo types](#pseudo-types)
-[Generics](#generics)
-[Usage](#usage)
-[What should I do when I get type errors?](#what-should-i-do-when-i-get-type-errors)
-[Version 3.0](#version-30)
-[Contributing](#contributing)
## Style types
Properties are categorized in different uses and in several technical variations to provide typings that suits as many as possible.
String literals of pseudo classes and pseudo elements
-`Pseudos`
Extends:
-`AdvancedPseudos`
Function-like pseudos e.g. `:not(:first-child)`. The string literal contains the value excluding the parenthesis: `:not`. These are separated because they require an argument that results in infinite number of variations.
-`SimplePseudos`
Plain pseudos e.g. `:hover` that can only be **one** variation.
## Generics
All interfaces has two optional generic argument to define length and time: `CSS.Properties<TLength = string | 0, TTime = string>`
-**Length** is the first generic parameter and defaults to `string | 0` because `0` is the only [length where the unit identifier is optional](https://drafts.csswg.org/css-values-3/#lengths). You can specify this, e.g. `string | number`, for platforms and libraries that accepts any numeric value as length with a specific unit.
```tsx
conststyle:CSS.Properties<string|number>={
width:100,
};
```
-**Time** is the second generic argument and defaults to `string`. You can specify this, e.g. `string | number`, for platforms and libraries that accepts any numeric value as length with a specific unit.
```tsx
conststyle:CSS.Properties<string|number,number>={
transitionDuration:1000,
};
```
## Usage
```ts
import*asCSSfrom'csstype';
conststyle:CSS.Properties={
width:'10px',
margin:'1em',
};
```
In some cases, like for CSS-in-JS libraries, an array of values is a way to provide fallback values in CSS. Using `CSS.PropertiesFallback` instead of `CSS.Properties` will add the possibility to use any property value as an array of values.
```ts
import*asCSSfrom'csstype';
conststyle:CSS.PropertiesFallback={
display:['-webkit-flex','flex'],
color:'white',
};
```
There's even string literals for pseudo selectors and elements.
Hyphen cased (kebab cased) properties are provided in `CSS.PropertiesHyphen` and `CSS.PropertiesHyphenFallback`. It's not **not** added by default in `CSS.Properties`. To allow both of them, you can simply extend with `CSS.PropertiesHyphen` or/and `CSS.PropertiesHyphenFallback`.
Adding type checked CSS properties to a `HTMLElement`.
```ts
import*asCSSfrom'csstype';
conststyle:CSS.Properties={
color:'red',
margin:'1em',
};
letbutton=document.createElement('button');
Object.assign(button.style,style);
```
## What should I do when I get type errors?
The goal is to have as perfect types as possible and we're trying to do our best. But with CSS Custom Properties, the CSS specification changing frequently and vendors implementing their own specifications with new releases sometimes causes type errors even if it should work. Here's some steps you could take to get it fixed:
_If you're using CSS Custom Properties you can step directly to step 3._
1.**First of all, make sure you're doing it right.** A type error could also indicate that you're not :wink:
- Some CSS specs that some vendors has implemented could have been officially rejected or haven't yet received any official acceptance and are therefor not included
- If you're using TypeScript, [type widening](https://blog.mariusschulz.com/2017/02/04/TypeScript-2-1-literal-type-widening) could be the reason you get `Type 'string' is not assignable to...` errors
2.**Have a look in [issues](https://github.com/frenic/csstype/issues) to see if an issue already has been filed. If not, create a new one.** To help us out, please refer to any information you have found.
3. Fix the issue locally with **TypeScript** (Flow further down):
- The recommended way is to use **module augmentation**. Here's a few examples:
```ts
// My css.d.ts file
import * as CSS from 'csstype';
declare module 'csstype' {
interface Properties {
// Add a missing property
WebkitRocketLauncher?: string;
// Add a CSS Custom Property
'--theme-color'?: 'black' | 'white';
// ...or allow any other property
[index: string]: any;
}
}
```
- The alternative way is to use **type assertion**. Here's a few examples:
```ts
const style: CSS.Properties = {
// Add a missing property
['WebkitRocketLauncher' as any]: 'launching',
// Add a CSS Custom Property
['--theme-color' as any]: 'black',
};
```
Fix the issue locally with **Flow**:
- Use **type assertion**. Here's a few examples:
```js
const style: $Exact<CSS.Properties<*>> = {
// Add a missing property
[('WebkitRocketLauncher': any)]: 'launching',
// Add a CSS Custom Property
[('--theme-color': any)]: 'black',
};
```
## Version 3.0
-**All property types are exposed with namespace**
E.g. `Color` and `Box`. Because the generation of data types may suddenly be removed or renamed.
-**TypeScript hack for autocompletion**
Uses `(string & {})` for literal string unions and `(number & {})` for literal number unions ([related issue](https://github.com/microsoft/TypeScript/issues/29729)). Utilize `PropertyValue<T>` to unpack types from e.g. `(string & {})` to `string`.
-**New generic for time**
Read more on the ["Generics"](#generics) section.
-**Flow types improvements**
Flow Strict enabled and exact types are used.
## Contributing
**Never modify `index.d.ts` and `index.js.flow` directly. They are generated automatically and committed so that we can easily follow any change it results in.** Therefor it's important that you run `$ git config merge.ours.driver true` after you've forked and cloned. That setting prevents merge conflicts when doing rebase.
### Commands
-`yarn build` Generates typings and type checks them
-`yarn watch` Runs build on each save
-`yarn test` Runs the tests
-`yarn lazy` Type checks, lints and formats everything