aboutsummaryrefslogtreecommitdiff
path: root/public/main.js
blob: 97f11f4440fc31f9d72b0f12273249dcc4c1ea4d (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
62
63
64
65
66
67
// Helpers

function appendElement(parentElement, tag) {
  element = document.createElement(tag)
  parentElement.appendChild(element)
  return element
}
  
function appendText(parentElement, text) {
  element = document.createTextNode(text)
  parentElement.appendChild(element)
  return element
}

tonalities_b = ['C', 'D♭', 'D', 'E♭', 'E', 'F', 'G♭', 'G', 'A♭', 'A', 'B♭', 'B']
tonalities_s = ['C', 'C♯', 'D', 'D♯', 'E', 'F', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B']

function getRoot(c) {
  if (c.indexOf('♯') > -1 || c.indexOf('♭') > -1) {
    return c.substring(0, 2)
  } else {
    return c[0]
  }
}

function getShift(t1, t2) {
  return tonalities_b.indexOf(getRoot(t2)) - tonalities_b.indexOf(getRoot(t1))
}

function applyShift(tonalities, t1, s) {
  let root = getRoot(t1)
  const mode = t1.substring(root.length)
  const index = tonalities_b.indexOf(root) > -1 ? tonalities_b.indexOf(root) : tonalities_s.indexOf(root)
  root = tonalities[(index + s + tonalities.length) % tonalities.length]
  return `${root}${mode}`
}


const node = document.querySelector('[data-tonality]')
let tonality = node.dataset.tonality
mode = tonality[tonality.length - 1] == 'm' ? 'm' : ''

label = appendElement(node, 'label')
label['className'] = 'g-Chords__Tonality'
label.onchange = (e) => {
  const shift = getShift(tonality, e.target.value)
  tonality = e.target.value
  tonalities = tonality === 'F' || tonality.indexOf('♭') > -1 ? tonalities_b : tonalities_s
  document.querySelectorAll('.g-Chords__Chord').forEach(chord => {
    if (chord.innerText !== '%') {
      chord.innerText = applyShift(tonalities, chord.innerText, shift)
    }
  })
}

appendText(label, 'Tonalité :')

select = appendElement(label, 'select')
select['name'] = 'tonality'
tonalities_b.forEach(t => {
  option = appendElement(select, 'option')
  option['value'] = t
  if (tonality == `${t}${mode}`) {
    option['selected'] = true
  }
  appendText(option, `${t}${mode}`)
})