-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
main.js
100 lines (83 loc) · 2.83 KB
/
main.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//@ts-check
// This script will be run within the webview itself
// It cannot access the main VS Code APIs directly.
(function () {
const vscode = acquireVsCodeApi();
const oldState = vscode.getState() || { colors: [] };
/** @type {Array<{ value: string }>} */
let colors = oldState.colors;
updateColorList(colors);
document.querySelector('.add-color-button').addEventListener('click', () => {
addColor();
});
// Handle messages sent from the extension to the webview
window.addEventListener('message', event => {
const message = event.data; // The json data that the extension sent
switch (message.type) {
case 'addColor':
{
addColor();
break;
}
case 'clearColors':
{
colors = [];
updateColorList(colors);
break;
}
}
});
/**
* @param {Array<{ value: string }>} colors
*/
function updateColorList(colors) {
const ul = document.querySelector('.color-list');
ul.textContent = '';
for (const color of colors) {
const li = document.createElement('li');
li.className = 'color-entry';
const colorPreview = document.createElement('div');
colorPreview.className = 'color-preview';
colorPreview.style.backgroundColor = `#${color.value}`;
colorPreview.addEventListener('click', () => {
onColorClicked(color.value);
});
li.appendChild(colorPreview);
const input = document.createElement('input');
input.className = 'color-input';
input.type = 'text';
input.value = color.value;
input.addEventListener('change', (e) => {
const value = e.target.value;
if (!value) {
// Treat empty value as delete
colors.splice(colors.indexOf(color), 1);
} else {
color.value = value;
}
updateColorList(colors);
});
li.appendChild(input);
ul.appendChild(li);
}
// Update the saved state
vscode.setState({ colors: colors });
}
/**
* @param {string} color
*/
function onColorClicked(color) {
vscode.postMessage({ type: 'colorSelected', value: color });
}
/**
* @returns string
*/
function getNewCalicoColor() {
const colors = ['020202', 'f1eeee', 'a85b20', 'daab70', 'efcb99'];
return colors[Math.floor(Math.random() * colors.length)];
}
function addColor() {
colors.push({ value: getNewCalicoColor() });
updateColorList(colors);
}
}());