UNPKG

1.88 kBJavaScriptView Raw
1'use strict'
2
3const { LEVELS, LEVEL_NAMES } = require('./constants')
4
5const nocolor = input => input
6const plain = {
7 default: nocolor,
8 60: nocolor,
9 50: nocolor,
10 40: nocolor,
11 30: nocolor,
12 20: nocolor,
13 10: nocolor,
14 message: nocolor
15}
16
17const chalk = require('chalk')
18const ctx = new chalk.Instance({ level: 3 })
19const colored = {
20 default: ctx.white,
21 60: ctx.bgRed,
22 50: ctx.red,
23 40: ctx.yellow,
24 30: ctx.green,
25 20: ctx.blue,
26 10: ctx.grey,
27 message: ctx.cyan
28}
29
30function colorizeLevel (level, colorizer) {
31 if (Number.isInteger(+level)) {
32 return Object.prototype.hasOwnProperty.call(LEVELS, level)
33 ? colorizer[level](LEVELS[level])
34 : colorizer.default(LEVELS.default)
35 }
36 const levelNum = LEVEL_NAMES[level.toLowerCase()] || 'default'
37 return colorizer[levelNum](LEVELS[levelNum])
38}
39
40function plainColorizer (level) {
41 return colorizeLevel(level, plain)
42}
43plainColorizer.message = plain.message
44
45function coloredColorizer (level) {
46 return colorizeLevel(level, colored)
47}
48coloredColorizer.message = colored.message
49
50/**
51 * Factory function get a function to colorized levels. The returned function
52 * also includes a `.message(str)` method to colorize strings.
53 *
54 * @param {bool} [useColors=false] When `true` a function that applies standard
55 * terminal colors is returned.
56 *
57 * @returns {function} `function (level) {}` has a `.message(str)` method to
58 * apply colorization to a string. The core function accepts either an integer
59 * `level` or a `string` level. The integer level will map to a known level
60 * string or to `USERLVL` if not known. The string `level` will map to the same
61 * colors as the integer `level` and will also default to `USERLVL` if the given
62 * string is not a recognized level name.
63 */
64module.exports = function getColorizer (useColors = false) {
65 return useColors ? coloredColorizer : plainColorizer
66}