|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import * as TabsPrimitive from '@radix-ui/react-tabs'; |
| 4 | +import { useCallback, useMemo } from 'react'; |
| 5 | + |
| 6 | +import CodeTabs from '#ui/Common/CodeTabs'; |
| 7 | +import { useHashContext } from '#ui/contexts/HashContext'; |
| 8 | + |
| 9 | +import type { ComponentProps, FC } from 'react'; |
| 10 | + |
| 11 | +import MDXCodeTabs from './index'; |
| 12 | + |
| 13 | +type CodeTabsWithHashProps = ComponentProps<typeof MDXCodeTabs> & { |
| 14 | + groupId: string; |
| 15 | +}; |
| 16 | + |
| 17 | +const NAME_OVERRIDES: Record<string, string | undefined> = { |
| 18 | + mjs: 'ESM', |
| 19 | +}; |
| 20 | + |
| 21 | +const CodeTabsWithHash: FC<CodeTabsWithHashProps> = ({ |
| 22 | + languages: rawLanguages, |
| 23 | + displayNames: rawDisplayNames, |
| 24 | + children: codes, |
| 25 | + defaultTab = '0', |
| 26 | + groupId, |
| 27 | + ...props |
| 28 | +}) => { |
| 29 | + const { hash, setHash } = useHashContext(); |
| 30 | + |
| 31 | + const { tabs, languages } = useMemo(() => { |
| 32 | + const occurrences: Record<string, number> = {}; |
| 33 | + const languages = rawLanguages.split('|'); |
| 34 | + const displayNames = rawDisplayNames?.split('|') ?? []; |
| 35 | + |
| 36 | + const tabs = languages.map((language, index) => { |
| 37 | + const base = |
| 38 | + displayNames[index]?.trim() || |
| 39 | + NAME_OVERRIDES[language] || |
| 40 | + language.toUpperCase(); |
| 41 | + |
| 42 | + const count = occurrences[base] ?? 0; |
| 43 | + occurrences[base] = count + 1; |
| 44 | + |
| 45 | + const label = count > 0 ? `${base} (${count + 1})` : base; |
| 46 | + |
| 47 | + return { |
| 48 | + key: `${language}-${index}`, |
| 49 | + label, |
| 50 | + id: `${groupId}-${language}-${index}`.replace(/[^a-zA-Z0-9-_]/g, '-'), |
| 51 | + }; |
| 52 | + }); |
| 53 | + |
| 54 | + return { tabs, languages }; |
| 55 | + }, [rawLanguages, rawDisplayNames, groupId]); |
| 56 | + |
| 57 | + const activeTab = |
| 58 | + tabs.find(t => t.id === hash)?.key ?? tabs[Number(defaultTab)].key; |
| 59 | + |
| 60 | + const handleValueChange = useCallback( |
| 61 | + (value: string) => { |
| 62 | + const matched = tabs.find(t => t.key === value); |
| 63 | + if (matched?.id) { |
| 64 | + setHash(matched.id); |
| 65 | + } |
| 66 | + }, |
| 67 | + [tabs, setHash] |
| 68 | + ); |
| 69 | + |
| 70 | + return ( |
| 71 | + <CodeTabs |
| 72 | + tabs={tabs} |
| 73 | + value={activeTab} |
| 74 | + onValueChange={handleValueChange} |
| 75 | + {...props} |
| 76 | + > |
| 77 | + {languages.map((_, index) => ( |
| 78 | + <TabsPrimitive.Content |
| 79 | + forceMount |
| 80 | + key={tabs[index].key} |
| 81 | + value={tabs[index].key} |
| 82 | + > |
| 83 | + {codes[index]} |
| 84 | + </TabsPrimitive.Content> |
| 85 | + ))} |
| 86 | + </CodeTabs> |
| 87 | + ); |
| 88 | +}; |
| 89 | +export default CodeTabsWithHash; |
0 commit comments