-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
98 lines (75 loc) · 2.32 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
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 copyToClickBoard (text){
return navigator.clipboard.writeText(text)
}
function generateRandomColor() {
const hexCodes = '0123456789ABCDEF'
let color =''
for(let i=0;i<6;i++)
{
color += hexCodes[Math.floor(Math.random()*hexCodes.length)]
}
return '#'+ color
}
function setRandomColors(isInitaial) {
const colors = isInitaial? 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 = isInitaial
?colors[index]
? colors[index]
: chroma.random()
:chroma.random()
if(!isInitaial){
colors.push(color)
}
colors.push(color)
text.textContent = color
col.style.background = generateRandomColor()
setTextColor(text,color)
setTextColor(button,color)
})
updateLocationHash(colors)
}
function setTextColor(text, color){
const luminance = chroma(color).luminance()
text.style.color = luminance > 0.5? 'black': 'white'
}
function updateLocationHash(colors = []){
document.location.hash = colors.map (col => 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)