-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
92 lines (81 loc) · 3.09 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snip</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1></h1>
<main>
<section>
</section>
<button id="newEntryBtn">New entry</button>
</main>
<script>
const titleNode = document.querySelector('h1')
titleNode.innerText = (new Date()).toString()
// Load initial state from URL
const asciiData = window.location.hash.slice(1)
const decodedJsonStr = atob(asciiData)
const state = decodedJsonStr ? JSON.parse(decodedJsonStr) : []
const section = document.querySelector('section')
// Add initial state to DOM
state.forEach(entry => {
section.appendChild(makeForm(entry))
})
// Attach event listener to newEntryBtn
document.getElementById('newEntryBtn').addEventListener('click', event => {
const lastRank = parseInt(state.slice(-1) && state.slice(-1)[0] && state.slice(-1)[0].rank)
const newEntry = {
title: '',
completed: false,
rank: lastRank ? lastRank + 100 : 0,
}
const el = makeForm(newEntry)
section.appendChild(el)
el.querySelector('[type="text"]').focus()
state.push(newEntry)
})
// Returns a new <form> representing an entry
function makeForm(entry) {
const { title, completed, rank } = entry
const el = document.createElement('form')
const id = rndID()
entry.id = id
el.setAttribute('id', id)
el.setAttribute('autocomplete', 'off')
el.innerHTML = `
<input name="completed" type="checkbox" ${completed ? 'checked' : ''} />
<input name="title" type="text" value="${title}" />
`
el.querySelector('[name="completed"]').addEventListener('change', onCompletedChange)
el.querySelector('[name="title"]').addEventListener('change', onTitleChange)
el.addEventListener('submit', event => {
event.preventDefault() // don't submit when pressing enter
})
return el
}
function onCompletedChange(event) {
const { checked, form } = event.target
state.find(x => x.id == form.id).completed = checked
serialize()
}
function onTitleChange(event) {
const { value, form } = event.target
state.find(x => x.id == form.id).title = value
serialize()
}
// Returns a random, 6 characters alphanumeric string
function rndID() {
return Math.random().toString(18).substring(2, 5) + Math.random().toString(18).substring(2, 5)
}
// Appends serialized app state to URL
function serialize() {
const jsonStr = JSON.stringify(state)
history.pushState(null, '', '#' + btoa(jsonStr))
}
</script>
</body>
</html>