-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
input.mjs
49 lines (42 loc) · 1.26 KB
/
input.mjs
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
import * as url from 'node:url';
import chalk from 'chalk';
import { input } from '@inquirer/prompts';
const hexRegEx = /(\d|[a-f])/gim;
const isHex = (value) =>
(value.match(hexRegEx) || []).length === value.length &&
(value.length === 3 || value.length === 6);
const demo = async () => {
let answer;
answer = await input({
message: "What's your favorite food?",
default: 'Croissant',
});
console.log('Answer:', answer);
answer = await input({
message: 'Enter an hex color?',
transformer(value = '', { isFinal }) {
const color = chalk.hex(isHex(value) ? value : 'fff');
return isFinal ? color.underline(value) : color(value);
},
validate: (value = '') => isHex(value) || 'Pass a valid hex value',
});
console.log('Answer:', answer);
answer = await input({
message: '(Slow validation) provide a number:',
validate: (value) =>
new Promise((resolve) => {
setTimeout(
() => resolve(!Number.isNaN(Number(value)) || 'You must provide a number'),
3000,
);
}),
});
console.log('Answer:', answer);
};
if (import.meta.url.startsWith('file:')) {
const modulePath = url.fileURLToPath(import.meta.url);
if (process.argv[1] === modulePath) {
demo();
}
}
export default demo;