'use client'; import type { FC, ReactElement, ReactNode } from 'react'; import { Children, createContext, isValidElement, useContext, useEffect, useRef, useState, } from 'react'; import { CheckIcon, CopyIcon } from './icons'; /** * Signals to nested `Pre` components that they live inside a Tabs shell, so * they render bare (no own chrome) and sit seamlessly inside the code-block * box. */ export const TabsContext = createContext(false); export function useInTabs() { return useContext(TabsContext); } type TabItem = string | ReactElement; type TabObjectItem = { label: TabItem; disabled?: boolean; }; function isTabObjectItem(item: unknown): item is TabObjectItem { return !!item && typeof item === 'object' && 'label' in item; } type TabsProps = { items: (TabItem | TabObjectItem)[]; children: ReactNode; storageKey?: string; defaultIndex?: number; }; export const Tabs: FC = ({ items, children, storageKey, defaultIndex = 0 }) => { const [selectedIndex, setSelectedIndex] = useState(defaultIndex); const [copied, setCopied] = useState(false); const panelRef = useRef(null); useEffect(() => { if (!storageKey) return; function onStorage(event: StorageEvent) { if (event.key === storageKey) { setSelectedIndex(Number(event.newValue)); } } const stored = Number(localStorage.getItem(storageKey)); if (!Number.isNaN(stored)) { setSelectedIndex(stored); } window.addEventListener('storage', onStorage); return () => window.removeEventListener('storage', onStorage); // eslint-disable-next-line react-hooks/exhaustive-deps -- only on mount }, []); function selectTab(index: number) { if (storageKey) { const newValue = String(index); localStorage.setItem(storageKey, newValue); // Same-tab listeners don't fire `storage`, so dispatch it manually to // sync every synced block on the page. window.dispatchEvent(new StorageEvent('storage', { key: storageKey, newValue })); return; } setSelectedIndex(index); } async function copy() { const text = panelRef.current?.querySelector('pre')?.textContent ?? panelRef.current?.textContent ?? ''; await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2000); } const panels = Children.toArray(children).filter(isValidElement); const activeIndex = Math.min(selectedIndex, panels.length - 1); return (
{items.map((item, index) => { const disabled = isTabObjectItem(item) && item.disabled; const label = isTabObjectItem(item) ? item.label : item; const active = index === activeIndex; return ( ); })}
{panels[activeIndex]}
); }; type TabProps = { children: ReactNode; }; export const Tab: FC = ({ children }) => { return <>{children}; };