import type { ReactNode } from 'react'; import { useMemo, useState } from 'react'; import { TabsContent, TabsList, Tabs as TabsPrimitive, TabsTrigger } from '@/components/ui/tabs'; import { styles } from './styles'; import { findCodeLanguage, findCodeTitle, slugify, toElementArray } from './utils'; export interface CodeGroupProps { children?: ReactNode; } export function CodeGroup({ children }: CodeGroupProps) { const blocks = useMemo(() => { const counts = new Map(); return toElementArray<{ title?: string }>(children).map((child, index) => { const explicitTitle = child.props?.title; const titleValue = (typeof explicitTitle === 'string' && explicitTitle.trim()) || findCodeTitle(child) || findCodeLanguage(child) || `snippet ${index + 1}`; const keyBase = slugify(titleValue, `snippet-${index + 1}`); const count = counts.get(keyBase) || 0; counts.set(keyBase, count + 1); return { id: count ? `${keyBase}-${count + 1}` : keyBase, title: count ? `${titleValue} ${count + 1}` : titleValue, content: child, }; }); }, [children]); const [selectedKey, setSelectedKey] = useState(blocks[0]?.id); const selected = blocks.some(block => block.id === selectedKey) ? selectedKey : blocks[0]?.id; if (!blocks.length) { return null; } if (blocks.length === 1) { return (
{blocks[0].content}
); } return ( {blocks.map(block => ( {block.title} ))} {blocks.map(block => ( {block.content} ))} ); }