aboutsummaryrefslogtreecommitdiff
path: root/packages/create-astro/src/gradient.ts
blob: 2d4c48d81858bd47c31064369e267a2fd002a40c (plain) (blame)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import chalk from 'chalk';
import ora from 'ora';
import type { Ora } from 'ora';

const gradientColors = [
	`#ff5e00`,
	`#ff4c29`,
	`#ff383f`,
	`#ff2453`,
	`#ff0565`,
	`#ff007b`,
	`#f5008b`,
	`#e6149c`,
	`#d629ae`,
	`#c238bd`,
];

export const rocketAscii = '■■▶';

// get a reference to scroll through while loading
// visual representation of what this generates:
// gradientColors: "..xxXX"
// referenceGradient: "..xxXXXXxx....xxXX"
const referenceGradient = [
	...gradientColors,
	// draw the reverse of the gradient without
	// accidentally mutating the gradient (ugh, reverse())
	...[...gradientColors].reverse(),
	...gradientColors,
];

// async-friendly setTimeout
const sleep = (time: number) =>
	new Promise((resolve) => {
		setTimeout(resolve, time);
	});

function getGradientAnimFrames() {
	const frames = [];
	for (let start = 0; start < gradientColors.length * 2; start++) {
		const end = start + gradientColors.length - 1;
		frames.push(
			referenceGradient
				.slice(start, end)
				.map((g) => chalk.bgHex(g)(' '))
				.join('')
		);
	}
	return frames;
}

function getIntroAnimFrames() {
	const frames = [];
	for (let end = 1; end <= gradientColors.length; end++) {
		const leadingSpacesArr = Array.from(
			new Array(Math.abs(gradientColors.length - end - 1)),
			() => ' '
		);
		const gradientArr = gradientColors.slice(0, end).map((g) => chalk.bgHex(g)(' '));
		frames.push([...leadingSpacesArr, ...gradientArr].join(''));
	}
	return frames;
}

/**
 * Generate loading spinner with rocket flames!
 * @param text display text next to rocket
 * @returns Ora spinner for running .stop()
 */
export async function loadWithRocketGradient(text: string): Promise<Ora> {
	const frames = getIntroAnimFrames();
	const intro = ora({
		spinner: {
			interval: 30,
			frames,
		},
		text: `${rocketAscii} ${text}`,
	});
	intro.start();
	await sleep((frames.length - 1) * intro.interval);
	intro.stop();
	const spinner = ora({
		spinner: {
			interval: 80,
			frames: getGradientAnimFrames(),
		},
		text: `${rocketAscii} ${text}`,
	}).start();

	return spinner;
}