From 063d8ef9eaf874a941f4459e831057dd0a1b7ddd Mon Sep 17 00:00:00 2001 From: Joris Date: Tue, 5 Jul 2022 21:55:41 +0200 Subject: Rewrite in TS --- src/state.ts | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/state.ts (limited to 'src/state.ts') diff --git a/src/state.ts b/src/state.ts new file mode 100644 index 0000000..634319a --- /dev/null +++ b/src/state.ts @@ -0,0 +1,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 +} -- cgit v1.2.3