-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
100 lines (81 loc) · 2.13 KB
/
app.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
99
100
const cols = document.querySelectorAll('.col')
document.addEventListener('keydown', (event) => {
event.preventDefault()
if (event.code.toLowerCase() === 'space') {
setRandomColors()
}
})
document.addEventListener('click', (event) => {
const type = event.target.dataset.type
if (type === 'lock') {
const node =
event.target.tagName.toLowerCase() === 'i'
? event.target
: event.target.children[0]
node.classList.toggle('fa-lock-open')
node.classList.toggle('fa-lock')
} else if (type === 'copy') {
copyToClickboard(event.target.textContent)
}
})
function gerenerateRandomColor() {
// RGB
// #FF0000
// #00FF00
// #0000FF
const hexCodes = '0123456789ABCDEF'
let color = ''
for (let i = 0; i < 6; i++) {
color += hexCodes[Math.floor(Math.random() * hexCodes.length)]
}
return '#' + color
}
function copyToClickboard(text) {
return navigator.clipboard.writeText(text)
}
function setRandomColors(isInitial) {
const colors = isInitial ? getColorsFromHash() : []
cols.forEach((col, index) => {
const isLocked = col.querySelector('i').classList.contains('fa-lock')
const text = col.querySelector('h2')
const button = col.querySelector('button')
if (isLocked) {
colors.push(text.textContent)
return
}
const color = isInitial
? colors[index]
? colors[index]
: chroma.random()
: chroma.random()
if (!isInitial) {
colors.push(color)
}
text.textContent = color
col.style.background = color
setTextColor(text, color)
setTextColor(button, color)
})
updateColorsHash(colors)
}
function setTextColor(text, color) {
const luminance = chroma(color).luminance()
text.style.color = luminance > 0.5 ? 'black' : 'white'
}
function updateColorsHash(colors = []) {
document.location.hash = colors
.map((col) => {
return col.toString().substring(1)
})
.join('-')
}
function getColorsFromHash() {
if (document.location.hash.length > 1) {
return document.location.hash
.substring(1)
.split('-')
.map((color) => '#' + color)
}
return []
}
setRandomColors(true)