aboutsummaryrefslogtreecommitdiff
path: root/src/state.ts
blob: 634319aa04082cf43b270af0c2a85ee56b6a6333 (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
import * as Serialization from 'serialization'

const L = window.L

// State

var nextIndex: Index = 0

export type State = Marker[]
export type Index = number

var state: State = []

export interface Marker {
  pos: L.Pos,
  name: string,
  color: string,
  icon: string,
  radius: number,
}

export function reset(s: State) {
  state = s
  nextIndex = s.length
}

// CRUD

export function add(marker: Marker): Index {
  const index = nextIndex
  state[index] = marker
  nextIndex += 1
  pushState()
  return index
}

export function update(index: Index, marker: Marker) {
  state[index] = marker
  pushState()
}

export function remove(index: Index) {
  delete state[index]
  pushState()
}

// History

function pushState() {
  const encoded = Serialization.encode(Object.values(state))
  history.pushState('', '', `#${encoded}`)
}

// Inspection

export function colors() {
  return [...new Set(Object.values(state).map(({ color }) => color))]
}

export function last(): Marker | undefined {
  const nonempty = Object.values(state)
  return nonempty.length > 0
    ? nonempty.slice(-1)[0]
    : undefined
}