Skip to content

Commit

Permalink
Add formatMessage color option (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
zanminkian authored Sep 16, 2024
1 parent 6d00f6b commit 6afd342
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
18 changes: 16 additions & 2 deletions pkg/src/message.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
import c from 'picocolors'
import picocolors from 'picocolors'
import {
formatMessagePath as fp,
getPkgPathValue,
replaceLast
} from './utils.js'

/** @type { import('picocolors/types.js').Colors | undefined } */
let _picocolorsHasColors
/** @type { import('picocolors/types.js').Colors | undefined } */
let _picocolorsNoColors

/**
* @param {import('../index.d.ts').Message} m
* @param {import('./utils.js').Pkg} pkg
* @param {import('../utils.d.ts').FormatMessageOptions} opts
*/
export function formatMessage(m, pkg) {
export function formatMessage(m, pkg, opts = {}) {
/** @type { import('picocolors/types.js').Colors } */
let c = picocolors
if (opts.color === true) {
c = _picocolorsHasColors ??= picocolors.createColors(true)
} else if (opts.color === false) {
c = _picocolorsNoColors ??= picocolors.createColors(false)
}

/** @param {string[]} path */
const pv = (path) => getPkgPathValue(pkg, path)

Expand Down
13 changes: 12 additions & 1 deletion pkg/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,20 @@ import type { Message } from './index.js'

type Pkg = Record<string, any>

export interface FormatMessageOptions {
/**
* Whether the returned string should contain color.
* - `true`: Force has color.
* - `false`: Force no color.
* - `undefined`: Default to whether the environment supports color.
*/
color?: boolean | undefined
}

export declare function formatMessagePath(path: string[]): string
export declare function getPkgPathValue(pkg: Pkg, path: string[]): any
export declare function formatMessage(
msg: Message,
pkg: Pkg
pkg: Pkg,
opts?: FormatMessageOptions
): string | undefined

0 comments on commit 6afd342

Please sign in to comment.