| 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 $emit = defineEmits(['clicked']) |
| 21 | |
| 22 | const id = props.shared === true ? `shared-toggle-button-${props.id}` : `toggle-button-${props.id}` |
| 23 | |
| 24 | const state = ref<{ status: boolean }>({ |
| 25 | status: getFromLocalStorage<boolean>(id, props.status ?? false) |
| 26 | }) |
| 27 | |
| 28 | const click = (): void => { |
| 29 | if (props.shared === true) { |
| 30 | for (const key in localStorage) { |
| 31 | if (key !== id && key.startsWith('shared-toggle-button-')) { |
| 32 | setToLocalStorage<boolean>(key, false) |
| 33 | state.value.status = getFromLocalStorage<boolean>(key, false) |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | setToLocalStorage<boolean>(id, !getFromLocalStorage<boolean>(id, props.status ?? false)) |
| 38 | state.value.status = getFromLocalStorage<boolean>(id, props.status ?? false) |
| 39 | if (getFromLocalStorage<boolean>(id, props.status ?? false)) { |
| 40 | props.on?.() |
| 41 | } else { |
| 42 | props.off?.() |
| 43 | } |
| 44 | $emit('clicked', getFromLocalStorage<boolean>(id, props.status ?? false)) |
| 45 | } |
| 46 | </script> |
| 47 | |
| 48 | <style> |
| 49 | .on { |
| 50 | background-color: lightgrey; |
| 51 | } |
| 52 | </style> |