summaryrefslogtreecommitdiff
path: root/projects/2-stay-motivated/main.js
blob: 97c6bf0f8f4fb98eacd4819ddce05c280b754079 (plain)
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
function getRandomId(prefix) {
  return `${prefix}-${Math.round(Date.now() * Math.random())}`
}

function makeGrid() {
  let gridItems = []
  let gridIds = []
  for (let i = 1; i <= 365; i++) {
    let id = getRandomId('grid-item')
    gridIds.push(id)
    gridItems.push(Templates.gridItem(false, id))
  }
  let gridTemplate = Templates.gridContainer(gridItems.join(''))
  return {
    template: gridTemplate,
    ids: gridIds
  }
}

function makeForm(value) {
  let id = 'motivation-form'
  let template = Templates.form(
    'What are you working on?',
    getRandomId(''),
    id,
    value
  )
  return { template, id }
}

function bindGridClickHandlers(ids) {
  for (let id of ids) {
    let gridItem = document.getElementById(id)
    gridItem.addEventListener('click', function() {
      gridItem.classList.toggle('grid-item__highlighted')
    })
  }
}

function mount(rootNode, content) {
  rootNode.innerHTML = Templates.container(content)
}

function mountGrid(rootNode, content, gridIds) {
  mount(rootNode, content)
  bindGridClickHandlers(gridIds)
}

window.onload = function() {
  let rootNode = document.getElementById('root')
  let grid = makeGrid()
  let form = makeForm()
  mount(rootNode, form.template)
  let formNode = document.getElementById(form.id)
  formNode.addEventListener('keydown', function(event) {
    if (event.key == 'Enter') {
      form = makeForm(formNode.value)
      mountGrid(rootNode, form.template + grid.template, grid.ids)
    }
  })
}