1- 'use client' ;
2-
31import * as TabsPrimitive from '@radix-ui/react-tabs' ;
4- import { useEffect , useId , useMemo , useState } from 'react' ;
2+ import { useMemo } from 'react' ;
53
64import CodeTabs from '#ui/Common/CodeTabs' ;
75
86import type { FC , ReactElement } from 'react' ;
97
8+ import CodeTabsWithHash from './CodeTabsWithHash' ;
9+
1010type MDXCodeTabsProps = {
1111 children : Array < ReactElement < unknown > > ;
1212 languages : string ;
@@ -27,8 +27,7 @@ const MDXCodeTabs: FC<MDXCodeTabsProps> = ({
2727 groupId,
2828 ...props
2929} ) => {
30- const id = useId ( ) ;
31- const prefix = groupId ? `tab-${ groupId } ` : `tab-${ id } ` ;
30+ const prefix = groupId ?? 'tab' ;
3231
3332 const { tabs, languages } = useMemo ( ( ) => {
3433 const occurrences : Record < string , number > = { } ;
@@ -61,43 +60,12 @@ const MDXCodeTabs: FC<MDXCodeTabsProps> = ({
6160 return { tabs, languages } ;
6261 } , [ rawLanguages , rawDisplayNames , prefix ] ) ;
6362
64- const [ activeTab , setActiveTab ] = useState ( ( ) => {
65- if ( typeof window !== 'undefined' && window . location . hash ) {
66- const hash = window . location . hash . slice ( 1 ) ;
67- const matched = tabs . find ( t => t . anchorId === hash ) ;
68- if ( matched ) {
69- return matched . key ;
70- }
71- }
72- return tabs [ Number ( defaultTab ) ] ?. key ?? tabs [ 0 ] . key ;
73- } ) ;
74-
75- useEffect ( ( ) => {
76- const handleHashChange = ( ) => {
77- const hash = window . location . hash . slice ( 1 ) ;
78- const matched = tabs . find ( t => t . anchorId === hash ) ;
79- if ( matched ) {
80- setActiveTab ( matched . key ) ;
81- }
82- } ;
83-
84- window . addEventListener ( 'hashchange' , handleHashChange ) ;
85- return ( ) => window . removeEventListener ( 'hashchange' , handleHashChange ) ;
86- } , [ tabs ] ) ;
87-
88- const handleValueChange = ( value : string ) => {
89- setActiveTab ( value ) ;
90- const matched = tabs . find ( t => t . key === value ) ;
91- if ( matched ) {
92- window . history . replaceState ( null , '' , `#${ matched . anchorId } ` ) ;
93- }
94- } ;
63+ const Component = groupId ? CodeTabsWithHash : CodeTabs ;
9564
9665 return (
97- < CodeTabs
66+ < Component
9867 tabs = { tabs }
99- value = { activeTab }
100- onValueChange = { handleValueChange }
68+ defaultValue = { tabs [ Number ( defaultTab ) ] . key }
10169 { ...props }
10270 >
10371 { languages . map ( ( _ , index ) => (
@@ -109,7 +77,7 @@ const MDXCodeTabs: FC<MDXCodeTabsProps> = ({
10977 { codes [ index ] }
11078 </ TabsPrimitive . Content >
11179 ) ) }
112- </ CodeTabs >
80+ </ Component >
11381 ) ;
11482} ;
11583
0 commit comments