import { ChangeEvent, ReactElement, ReactNode, useCallback, useEffect, useMemo, useState, } from 'react' import { IconButton, Popover, PopoverBody, PopoverContent, PopoverTrigger, Switch, } from '@chakra-ui/react' import cx from 'classnames' type SwitchCardProps = { children?: ReactNode icon: ReactElement label: string isCollapsed?: boolean localStorageNamespace: string expandedMinWidth?: string } export const SwitchCard = ({ children, icon, label, isCollapsed, localStorageNamespace, expandedMinWidth, }: SwitchCardProps) => { const [isActive, setIsActive] = useState(false) const localStorageActiveKey = useMemo( () => `voltaserve_${localStorageNamespace}_switch_card_active`, [localStorageNamespace], ) useEffect(() => { let active = false if (typeof localStorage !== 'undefined') { const value = localStorage.getItem(localStorageActiveKey) if (value) { active = JSON.parse(value) } else { localStorage.setItem(localStorageActiveKey, JSON.stringify(false)) } } if (active) { setIsActive(true) } else { setIsActive(false) } }, [localStorageActiveKey, setIsActive]) const handleChange = useCallback( (event: ChangeEvent) => { setIsActive(event.target.checked) localStorage.setItem( localStorageActiveKey, JSON.stringify(event.target.checked), ) }, [localStorageActiveKey], ) if (isCollapsed) { return ( {children} ) } else { return (
{icon} {label}
{isActive && (
{children}
)}
) } }