-
Notifications
You must be signed in to change notification settings - Fork 1
/
convertColor.js
76 lines (65 loc) · 2.16 KB
/
convertColor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const clipboardy = require('clipboardy')
const converter = require('convert-color-js')
const { prompt } = require('enquirer')
const c = require('ansi-colors')
function getConversionOptionsFromColor (color) {
let result
if (converter.isHex(color)) {
result = ['rgb', 'hsl' ]
} else if (converter.isHexa(color)) {
result = ['rgba', 'hsla' ]
} else if (converter.isRgb(color)) {
result = ['hex', 'hsl' ]
} else if (converter.isRgba(color)) {
result = ['hexa', 'hsla' ]
} else if (converter.isHsl(color)) {
result = ['hex', 'rgb' ]
} else if (converter.isHsla(color)) {
result = ['hexa', 'rgba' ]
}
return result
}
module.exports = async function convertColor(initialColor) {
let initialStage = initialColor === null ? 0 : 1
if (initialStage === 1) {
if (!converter.isValidColor(initialColor)) {
console.log(c.red('Invalid color. Run `convert-color --help` for usage.'))
return
}
}
if (initialStage === 0) {
// we need to prompt for initial color
let { color } = await prompt({
type: 'input',
name: 'color',
message: 'What is the color you want to convert?'
})
initialColor = color
}
if (!converter.isValidColor(initialColor)) {
console.log(c.red('Invalid color. Please enter a valid hex, rgb, or hsl string. Run `convert-color --help` for usage.'))
return
}
let conversionOptions = getConversionOptionsFromColor(initialColor)
if (!conversionOptions) {
console.log(c.red('Unable to get conversion options for color.'))
return
}
let { outputType } = await prompt({
type: 'select',
name: 'outputType',
message: 'Convert to which format:',
choices: conversionOptions
})
const output = converter.convert(initialColor, outputType)
if (output === undefined) {
// convertColor returns undefined if it cannot convert. this indicates an error.
console.log(c.red(`Unable to convert ${initialColor} to ${outputType}`))
return
} else {
// copy the output to the clipboard
clipboardy.writeSync(output)
// now we can update state
console.log(c.green(`Converted value is ${output}. It has been copied to your clipboard.`))
}
}