refactor(ui): trivial code cleanups
[e-mobility-charging-stations-simulator.git] / ui / web / src / components / buttons / ToggleButton.vue
1 <template>
2 <Button :class="{ on: state.status }" @click="click()">
3 <slot></slot>
4 </Button>
5 </template>
6
7 <script setup lang="ts">
8 import { ref } from 'vue'
9 import Button from '@/components/buttons/Button.vue'
10 import { getFromLocalStorage, setToLocalStorage } from '@/composables'
11
12 const props = defineProps<{
13 id: string
14 status?: boolean
15 shared?: boolean
16 on?: () => void
17 off?: () => void
18 }>()
19
20 const id = props.shared === true ? `shared-toggle-button-${props.id}` : `toggle-button-${props.id}`
21
22 const state = ref({
23 status: getFromLocalStorage<boolean>(id, props.status ?? false)
24 })
25
26 const click = (): void => {
27 if (props.shared) {
28 for (const key in localStorage) {
29 if (key !== id && key.startsWith('shared-toggle-button-')) {
30 setToLocalStorage<boolean>(key, false)
31 state.value.status = getFromLocalStorage<boolean>(key, false)
32 }
33 }
34 }
35 setToLocalStorage<boolean>(id, !getFromLocalStorage<boolean>(id, props.status ?? false))
36 state.value.status = getFromLocalStorage<boolean>(id, props.status ?? false)
37 if (getFromLocalStorage<boolean>(id, props.status ?? false)) {
38 props.on?.()
39 } else {
40 props.off?.()
41 }
42 }
43 </script>
44
45 <style>
46 .on {
47 background-color: lightgrey;
48 }
49 </style>