Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: color utils #200

Merged
merged 2 commits into from Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 13 additions & 1 deletion LICENSE
Expand Up @@ -22,7 +22,7 @@ SOFTWARE.

---

Prompt support is based on https://github.com/natemoo-re/clack/
Prompt support is based on https://github.com/natemoo-re/clack

MIT License

Expand All @@ -33,3 +33,15 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
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.

---

Color support is based on https://github.com/jorgebucaran/colorette

Copyright © Jorge Bucaran <https://jorgebucaran.com>

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.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -293,6 +293,9 @@ import {
leftAlign,
align,
box,
colors,
getColor,
colorize,
} from "consola/utils";

// CommonJS
Expand Down
1 change: 0 additions & 1 deletion package.json
Expand Up @@ -79,7 +79,6 @@
"@types/node": "^20.3.2",
"@vitest/coverage-v8": "^0.32.2",
"changelogen": "^0.5.3",
"colorette": "^2.0.20",
"defu": "^6.1.2",
"eslint": "^8.43.0",
"eslint-config-unjs": "^0.2.1",
Expand Down
3 changes: 0 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions src/reporters/fancy.ts
@@ -1,6 +1,6 @@
import stringWidth from "string-width";
import isUnicodeSupported from "is-unicode-supported";
import * as colors from "colorette";
import { colors } from "../utils/color";
import { parseStack } from "../utils/error";
import { FormatOptions, LogObject } from "../types";
import { LogLevel, LogType } from "../constants";
Expand Down Expand Up @@ -79,12 +79,12 @@

if (logObj.type === "box") {
return box(
highlightBackticks(
characterFormat(

Check warning on line 82 in src/reporters/fancy.ts

View check run for this annotation

Codecov / codecov/patch

src/reporters/fancy.ts#L82

Added line #L82 was not covered by tests
message + (additional.length > 0 ? "\n" + additional.join("\n") : "")
),
{
title: logObj.title
? highlightBackticks(logObj.title as string)
? characterFormat(logObj.title as string)

Check warning on line 87 in src/reporters/fancy.ts

View check run for this annotation

Codecov / codecov/patch

src/reporters/fancy.ts#L87

Added line #L87 was not covered by tests
: undefined,
style: logObj.style as BoxOpts["style"],
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
@@ -1,5 +1,5 @@
export * from "./utils/box";

export * from "./utils/color";
export {
stripAnsi,
centerAlign,
Expand Down
5 changes: 2 additions & 3 deletions src/utils/box.ts
@@ -1,4 +1,4 @@
import * as colorette from "colorette";
import { getColor } from "./color";
import { stripAnsi } from "./string";

export type BoxBorderStyle = {
Expand Down Expand Up @@ -226,8 +226,7 @@
const boxLines = [];

// Get the characters for the box and colorize
const _color: (text: string) => string =
(colorette as any)[opts.style.borderColor] || ((text: string) => text);
const _color = getColor(opts.style.borderColor);

Check warning on line 229 in src/utils/box.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/box.ts#L229

Added line #L229 was not covered by tests
const borderStyle = {
...(typeof opts.style.borderStyle === "string"
? boxStylePresets[
Expand Down
138 changes: 138 additions & 0 deletions src/utils/color.ts
@@ -0,0 +1,138 @@
/**
* Based on https://github.com/jorgebucaran/colorette
* Read LICENSE file for more information
* https://github.com/jorgebucaran/colorette/blob/20fc196d07d0f87c61e0256eadd7831c79b24108/index.js
*/

import * as tty from "node:tty";

// TODO: Migrate to std-env
const {
env = {},
argv = [],
platform = "",
} = typeof process === "undefined" ? {} : process;
const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
const isForced = "FORCE_COLOR" in env || argv.includes("--color");
const isWindows = platform === "win32";
const isDumbTerminal = env.TERM === "dumb";
const isCompatibleTerminal =
tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
const isCI =
"CI" in env &&
("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
const isColorSupported =
!isDisabled &&
(isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);

function replaceClose(
index: number,
string: string,
close: string,
replace: string,
head = string.slice(0, Math.max(0, index)) + replace,
tail = string.slice(Math.max(0, index + close.length)),
next = tail.indexOf(close)
): string {
return head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
}

Check warning on line 38 in src/utils/color.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/color.ts#L28-L38

Added lines #L28 - L38 were not covered by tests

function clearBleed(
index: number,
string: string,
open: string,
close: string,
replace: string
) {
return index < 0
? open + string + close
: open + replaceClose(index, string, close, replace) + close;
}

Check warning on line 50 in src/utils/color.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/color.ts#L40-L50

Added lines #L40 - L50 were not covered by tests

function filterEmpty(
open: string,
close: string,
replace = open,
at = open.length + 1
) {
return (string: string) =>
string || !(string === "" || string === undefined)
? clearBleed(
("" + string).indexOf(close, at),
string,
open,
close,
replace
)
: "";

Check warning on line 67 in src/utils/color.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/color.ts#L59-L67

Added lines #L59 - L67 were not covered by tests
}

function init(open: number, close: number, replace?: string) {
return filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace);
}

const colorDefs = {
reset: init(0, 0),
bold: init(1, 22, "\u001B[22m\u001B[1m"),
dim: init(2, 22, "\u001B[22m\u001B[2m"),
italic: init(3, 23),
underline: init(4, 24),
inverse: init(7, 27),
hidden: init(8, 28),
strikethrough: init(9, 29),
black: init(30, 39),
red: init(31, 39),
green: init(32, 39),
yellow: init(33, 39),
blue: init(34, 39),
magenta: init(35, 39),
cyan: init(36, 39),
white: init(37, 39),
gray: init(90, 39),
bgBlack: init(40, 49),
bgRed: init(41, 49),
bgGreen: init(42, 49),
bgYellow: init(43, 49),
bgBlue: init(44, 49),
bgMagenta: init(45, 49),
bgCyan: init(46, 49),
bgWhite: init(47, 49),
blackBright: init(90, 39),
redBright: init(91, 39),
greenBright: init(92, 39),
yellowBright: init(93, 39),
blueBright: init(94, 39),
magentaBright: init(95, 39),
cyanBright: init(96, 39),
whiteBright: init(97, 39),
bgBlackBright: init(100, 49),
bgRedBright: init(101, 49),
bgGreenBright: init(102, 49),
bgYellowBright: init(103, 49),
bgBlueBright: init(104, 49),
bgMagentaBright: init(105, 49),
bgCyanBright: init(106, 49),
bgWhiteBright: init(107, 49),
};

export type ColorName = keyof typeof colorDefs;
export type ColorFunction = (text: string | number) => string;

function createColors(useColor = isColorSupported) {
return useColor
? colorDefs
: Object.fromEntries(Object.keys(colorDefs).map((key) => [key, String]));

Check warning on line 124 in src/utils/color.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/color.ts#L124

Added line #L124 was not covered by tests
}

export const colors = createColors() as Record<ColorName, ColorFunction>;

export function getColor(
color: ColorName,
fallback: ColorName = "reset"
): ColorFunction {
return colors[color] || colors[fallback];
}

Check warning on line 134 in src/utils/color.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/color.ts#L130-L134

Added lines #L130 - L134 were not covered by tests

export function colorize(color: ColorName, text: string | number): string {
return getColor(color)(text);
}

Check warning on line 138 in src/utils/color.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/color.ts#L137-L138

Added lines #L137 - L138 were not covered by tests
9 changes: 4 additions & 5 deletions src/utils/prompt.ts
@@ -1,8 +1,7 @@
/**
* Based on @clak/propmts (MIT - Copyright (c) Nate Moore - Check LICENSE)
* Based on https://github.com/natemoo-re/clack
* Read LICENSE file for more information
* https://github.com/natemoo-re/clack/blob/593f93d06c1a53c8424e9aaf0c1c63fbf6975527/packages/prompts/src/index.ts
*
* Forked to use custom symbols and colors
*/

import {
Expand All @@ -20,10 +19,10 @@ import {

import isUnicodeSupported from "is-unicode-supported";

import * as color from "colorette";

import { cursor, erase } from "sisteransi";

import { colors as color } from "./color";

export { isCancel } from "@clack/core";

const unicode = isUnicodeSupported();
Expand Down