aboutsummaryrefslogtreecommitdiff
path: root/src/view/options.ts
blob: 0782fe45525900d634fea9a0a688557dcdef6219 (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
68
69
70
import * as Chord from 'chord'

// Model version: upgrade whenever the model is updated. Options are loaded
// only if versions match.
const version = '2'

export interface Model {
  major: Chord.Chords
  minor: Chord.Chords
  seventh: Chord.Chords
  minorSeventh: Chord.Chords
  majorSeventh: Chord.Chords
  bpm: number
  beatsPerChord: number
}

let init: Model = {
  major: new Set(Chord.plains),
  minor: new Set(),
  seventh: new Set(),
  minorSeventh: new Set(),
  majorSeventh: new Set(),
  bpm: 90,
  beatsPerChord: 4
}

export function load(): Model {
  let storedVersion = localStorage['version']

  if (storedVersion === undefined || storedVersion !== version) {
    return init
  } else {
    let str = localStorage['options']
    return str && fromString(str) || init
  }
}

export function save(options: Model): void {
  localStorage['version'] = version
  localStorage['options'] = toString(options)
}

function toString(o: Model): string {
  return JSON.stringify({
    major: [...o.major],
    minor: [...o.minor],
    seventh: [...o.seventh],
    minorSeventh: [...o.minorSeventh],
    majorSeventh: [...o.majorSeventh],
    bpm: o.bpm,
    beatsPerChord: o.beatsPerChord
  })
}

function fromString(str: string): Model | undefined {
  const o = JSON.parse(str)
  if (o === undefined) {
    return undefined
  } else {
    return {
      major: new Set(o.major),
      minor: new Set(o.minor),
      seventh: new Set(o.seventh),
      minorSeventh: new Set(o.minorSeventh),
      majorSeventh: new Set(o.majorSeventh),
      bpm: o.bpm,
      beatsPerChord: o.beatsPerChord
    }
  }
}