feat(ui): introduce toggle button and use it for actions
[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 // console.log(`----begin----`)
38 // for (const key in localStorage) {
39 // if (key.startsWith('shared-toggle-button-')) {
40 // console.log(key, getFromLocalStorage<boolean>(key, props.status ?? false))
41 // }
42 // }
43 // console.log(`----end----`)
44 if (getFromLocalStorage<boolean>(id, props.status ?? false)) {
45 props.on?.()
46 } else {
47 props.off?.()
48 }
49 }
50 </script>
51
52 <style>
53 .on {
54 background-color: lightgrey;
55 }
56 </style>