import {useEffect, useRef, useState} from 'react' import {useQueryClient} from '@tanstack/react-query' import {Check, ChevronDown, UserRound} from 'lucide-react' import { DEFAULT_ACCOUNT_ID, isAccountId, setAccountId, useAccountId, useAccountRecents, } from '@/lib/accountStore' function formatAccount(id: string): string { // 000000000000 -> 0000-0000-0000, matching how AWS groups account ids. return id.replace(/(\d{4})(\d{4})(\d{4})/, '$1-$2-$3') } export function AccountSwitcher() { const accountId = useAccountId() const recents = useAccountRecents() const queryClient = useQueryClient() const [open, setOpen] = useState(false) const [draft, setDraft] = useState('') const [error, setError] = useState(null) const containerRef = useRef(null) useEffect(() => { if (!open) return const onClick = (event: MouseEvent) => { if (!containerRef.current?.contains(event.target as Node)) setOpen(false) } const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') setOpen(false) } document.addEventListener('mousedown', onClick) document.addEventListener('keydown', onKey) return () => { document.removeEventListener('mousedown', onClick) document.removeEventListener('keydown', onKey) } }, [open]) function applyAccount(id: string) { if (!setAccountId(id)) { setError('Account id must be exactly 12 digits.') return } setDraft('') setError(null) setOpen(false) // Resources are account-scoped, so anything cached under the previous // account must not leak into the new view. void queryClient.invalidateQueries() } function submitDraft() { const trimmed = draft.trim() if (!isAccountId(trimmed)) { setError('Account id must be exactly 12 digits.') return } applyAccount(trimmed) } return (
{open && (
Switch account
{recents.map((id) => ( ))}
{ event.preventDefault() submitDraft() }} > { setDraft(event.target.value.replace(/\D/g, '')) setError(null) }} />
{error &&
{error}
}
)}
) }