From c4734b0c90d19f31e7ba7a467b197e3fb08f7fab Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 10:19:50 +0100 Subject: [PATCH 01/15] Tabs: add runtime checks for matching tabs/tabpanels --- packages/ui/src/tabs/context.tsx | 171 +++++++++++++++++++++++ packages/ui/src/tabs/panel.tsx | 15 +- packages/ui/src/tabs/root.tsx | 7 +- packages/ui/src/tabs/tab.tsx | 15 +- packages/ui/src/tabs/test/index.test.tsx | 139 ++++++++++++++++++ 5 files changed, 342 insertions(+), 5 deletions(-) create mode 100644 packages/ui/src/tabs/context.tsx diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx new file mode 100644 index 00000000000000..6319863c13a77b --- /dev/null +++ b/packages/ui/src/tabs/context.tsx @@ -0,0 +1,171 @@ +/** + * WordPress dependencies + */ +import { + createContext, + useContext, + useCallback, + useMemo, + useRef, + useEffect, +} from '@wordpress/element'; + +type TabValue = any; + +type TabsValidationContextType = { + registerTab: ( value: TabValue ) => () => void; + registerPanel: ( value: TabValue ) => () => void; +}; + +/** + * Whether validation is enabled. This is a build-time constant that allows + * bundlers to tree-shake all validation code in production builds. + */ +const VALIDATION_ENABLED = process.env.NODE_ENV !== 'production'; + +// Only create the context in development mode +const TabsValidationContext = VALIDATION_ENABLED + ? createContext< TabsValidationContextType | null >( null ) + : null; + +/** + * Hook to access the tabs validation context. + * Returns null in production or if not within a Tabs.Root. + */ +export function useTabsValidationContext() { + // This condition uses a build-time constant, so the else branch + // is completely removed in production builds via dead code elimination. + // eslint-disable-next-line react-hooks/rules-of-hooks -- build-time conditional + return VALIDATION_ENABLED ? useContext( TabsValidationContext! ) : null; +} + +/** + * Provider component that tracks registered tabs and panels, + * and validates that they match in development mode. + * + * In production, this component is a no-op and just renders children. + */ +export function TabsValidationProvider( { + children, +}: { + children: React.ReactNode; +} ) { + // This condition uses a build-time constant, so all validation logic + // is completely removed in production builds via dead code elimination. + if ( ! VALIDATION_ENABLED ) { + return children; + } + + /* eslint-disable react-hooks/rules-of-hooks -- build-time conditional above ensures consistent hook calls */ + const tabsRef = useRef< Set< TabValue > >( new Set() ); + const panelsRef = useRef< Set< TabValue > >( new Set() ); + const validationScheduledRef = useRef< ReturnType< + typeof setTimeout + > | null >( null ); + + const scheduleValidation = useCallback( () => { + // Clear any existing scheduled validation + if ( validationScheduledRef.current ) { + clearTimeout( validationScheduledRef.current ); + } + + // Schedule validation for the next tick to allow all registrations to complete + validationScheduledRef.current = setTimeout( () => { + const tabValues = tabsRef.current; + const panelValues = panelsRef.current; + + // Find tabs without matching panels + const tabsWithoutPanels: TabValue[] = []; + tabValues.forEach( ( value ) => { + if ( ! panelValues.has( value ) ) { + tabsWithoutPanels.push( value ); + } + } ); + + // Find panels without matching tabs + const panelsWithoutTabs: TabValue[] = []; + panelValues.forEach( ( value ) => { + if ( ! tabValues.has( value ) ) { + panelsWithoutTabs.push( value ); + } + } ); + + // Warn about mismatches + if ( tabsWithoutPanels.length > 0 ) { + // eslint-disable-next-line no-console + console.warn( + `Tabs: Found Tab(s) without matching Panel(s). ` + + `Each Tab should have a corresponding Panel with the same \`value\` prop. ` + + `Tab value(s) without panels: ${ tabsWithoutPanels + .map( ( v ) => JSON.stringify( v ) ) + .join( ', ' ) }` + ); + } + + if ( panelsWithoutTabs.length > 0 ) { + // eslint-disable-next-line no-console + console.warn( + `Tabs: Found Panel(s) without matching Tab(s). ` + + `Each Panel should have a corresponding Tab with the same \`value\` prop. ` + + `Panel value(s) without tabs: ${ panelsWithoutTabs + .map( ( v ) => JSON.stringify( v ) ) + .join( ', ' ) }` + ); + } + + validationScheduledRef.current = null; + }, 0 ); + }, [] ); + + const registerTab = useCallback( + ( value: TabValue ) => { + tabsRef.current.add( value ); + scheduleValidation(); + + // Return unregister function + return () => { + tabsRef.current.delete( value ); + scheduleValidation(); + }; + }, + [ scheduleValidation ] + ); + + const registerPanel = useCallback( + ( value: TabValue ) => { + panelsRef.current.add( value ); + scheduleValidation(); + + // Return unregister function + return () => { + panelsRef.current.delete( value ); + scheduleValidation(); + }; + }, + [ scheduleValidation ] + ); + + // Cleanup scheduled validation on unmount + useEffect( () => { + return () => { + if ( validationScheduledRef.current ) { + clearTimeout( validationScheduledRef.current ); + } + }; + }, [] ); + + const contextValue = useMemo( + () => ( { + registerTab, + registerPanel, + } ), + [ registerTab, registerPanel ] + ); + /* eslint-enable react-hooks/rules-of-hooks */ + + return ( + + { children } + + ); +} diff --git a/packages/ui/src/tabs/panel.tsx b/packages/ui/src/tabs/panel.tsx index 6ae551234172a1..644f2f72948453 100644 --- a/packages/ui/src/tabs/panel.tsx +++ b/packages/ui/src/tabs/panel.tsx @@ -1,6 +1,7 @@ -import { forwardRef } from '@wordpress/element'; +import { forwardRef, useEffect } from '@wordpress/element'; import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; +import { useTabsValidationContext } from './context'; import styles from './style.module.css'; import type { TabPanelProps } from './types'; @@ -11,11 +12,21 @@ import type { TabPanelProps } from './types'; * an [ARIA-compliant tabs pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/). */ export const Panel = forwardRef< HTMLDivElement, TabPanelProps >( - function TabPanel( { className, ...otherProps }, forwardedRef ) { + function TabPanel( { className, value, ...otherProps }, forwardedRef ) { + const validationContext = useTabsValidationContext(); + + // Register this panel's value for validation + useEffect( () => { + if ( validationContext && value !== undefined ) { + return validationContext.registerPanel( value ); + } + }, [ validationContext, value ] ); + return ( <_Tabs.Panel ref={ forwardedRef } className={ clsx( styles.tabpanel, className ) } + value={ value } { ...otherProps } /> ); diff --git a/packages/ui/src/tabs/root.tsx b/packages/ui/src/tabs/root.tsx index e7a825fdad0ff4..ddef00a3bd999a 100644 --- a/packages/ui/src/tabs/root.tsx +++ b/packages/ui/src/tabs/root.tsx @@ -1,5 +1,6 @@ import { forwardRef } from '@wordpress/element'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; +import { TabsValidationProvider } from './context'; import type { TabRootProps } from './types'; /** @@ -10,6 +11,10 @@ import type { TabRootProps } from './types'; */ export const Root = forwardRef< HTMLDivElement, TabRootProps >( function TabsRoot( { ...otherProps }, forwardedRef ) { - return <_Tabs.Root ref={ forwardedRef } { ...otherProps } />; + return ( + + <_Tabs.Root ref={ forwardedRef } { ...otherProps } /> + + ); } ); diff --git a/packages/ui/src/tabs/tab.tsx b/packages/ui/src/tabs/tab.tsx index 949d893536c29f..656497a5edeabb 100644 --- a/packages/ui/src/tabs/tab.tsx +++ b/packages/ui/src/tabs/tab.tsx @@ -1,8 +1,9 @@ -import { forwardRef } from '@wordpress/element'; +import { forwardRef, useEffect } from '@wordpress/element'; import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; import { chevronRight } from '@wordpress/icons'; import { Icon } from '../icon'; +import { useTabsValidationContext } from './context'; import styles from './style.module.css'; import type { TabProps } from './types'; @@ -13,13 +14,23 @@ import type { TabProps } from './types'; * an [ARIA-compliant tabs pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/). */ export const Tab = forwardRef< HTMLButtonElement, TabProps >( function Tab( - { className, children, ...otherProps }, + { className, children, value, ...otherProps }, forwardedRef ) { + const validationContext = useTabsValidationContext(); + + // Register this tab's value for validation + useEffect( () => { + if ( validationContext && value !== undefined ) { + return validationContext.registerTab( value ); + } + }, [ validationContext, value ] ); + return ( <_Tabs.Tab ref={ forwardedRef } className={ clsx( styles.tab, className ) } + value={ value } { ...otherProps } > { children } diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index 88c4bda488eebc..168bc887ee3e3f 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2256,5 +2256,144 @@ describe( 'Tabs', () => { ); } ); } ); + + describe( 'Development mode validation', () => { + it( 'should warn when a Tab has no matching Panel', async () => { + const consoleWarnSpy = jest + .spyOn( console, 'warn' ) + .mockImplementation( () => {} ); + + render( + + + One + Two + Three + + First panel + Second panel + { /* Missing panel for "three" */ } + + ); + + await waitForComponentToBeInitializedWithSelectedTab( 'One' ); + + // Wait for the validation to run (it's scheduled with setTimeout) + await waitFor( () => { + expect( consoleWarnSpy ).toHaveBeenCalledWith( + expect.stringContaining( + 'Found Tab(s) without matching Panel(s)' + ) + ); + } ); + + expect( consoleWarnSpy ).toHaveBeenCalledWith( + expect.stringContaining( '"three"' ) + ); + + consoleWarnSpy.mockRestore(); + } ); + + it( 'should warn when a Panel has no matching Tab', async () => { + const consoleWarnSpy = jest + .spyOn( console, 'warn' ) + .mockImplementation( () => {} ); + + render( + + + One + Two + + First panel + Second panel + Orphan panel + + ); + + await waitForComponentToBeInitializedWithSelectedTab( 'One' ); + + // Wait for the validation to run (it's scheduled with setTimeout) + await waitFor( () => { + expect( consoleWarnSpy ).toHaveBeenCalledWith( + expect.stringContaining( + 'Found Panel(s) without matching Tab(s)' + ) + ); + } ); + + expect( consoleWarnSpy ).toHaveBeenCalledWith( + expect.stringContaining( '"orphan"' ) + ); + + consoleWarnSpy.mockRestore(); + } ); + + it( 'should not warn when all Tabs and Panels match', async () => { + const consoleWarnSpy = jest + .spyOn( console, 'warn' ) + .mockImplementation( () => {} ); + + render( + + + One + Two + + First panel + Second panel + + ); + + await waitForComponentToBeInitializedWithSelectedTab( 'One' ); + + // Wait a bit to ensure validation has run + await new Promise( ( resolve ) => setTimeout( resolve, 50 ) ); + + expect( consoleWarnSpy ).not.toHaveBeenCalled(); + + consoleWarnSpy.mockRestore(); + } ); + + it( 'should warn about multiple mismatches', async () => { + const consoleWarnSpy = jest + .spyOn( console, 'warn' ) + .mockImplementation( () => {} ); + + render( + + + One + Orphan Tab 1 + Orphan Tab 2 + + First panel + Orphan panel + + ); + + await waitForComponentToBeInitializedWithSelectedTab( 'One' ); + + // Wait for the validation to run + await waitFor( () => { + expect( consoleWarnSpy ).toHaveBeenCalledTimes( 2 ); + } ); + + // Check for tabs without panels warning + expect( consoleWarnSpy ).toHaveBeenCalledWith( + expect.stringContaining( '"orphan-tab-1"' ) + ); + expect( consoleWarnSpy ).toHaveBeenCalledWith( + expect.stringContaining( '"orphan-tab-2"' ) + ); + + // Check for panels without tabs warning + expect( consoleWarnSpy ).toHaveBeenCalledWith( + expect.stringContaining( '"orphan-panel"' ) + ); + + consoleWarnSpy.mockRestore(); + } ); + } ); } ); /* eslint-enable jest/no-conditional-expect */ From 5dcd3bac7f0ea069fbb8ee8d572ed1bb758e323e Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 10:21:45 +0100 Subject: [PATCH 02/15] Tabs: Add runtime check to make sure all components are wrapped in Tabs.Root --- packages/ui/src/tabs/context.tsx | 16 +++++++++ packages/ui/src/tabs/list.tsx | 2 ++ packages/ui/src/tabs/panel.tsx | 3 +- packages/ui/src/tabs/tab.tsx | 3 +- packages/ui/src/tabs/test/index.test.tsx | 41 ++++++++++++++++++++++++ 5 files changed, 63 insertions(+), 2 deletions(-) diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index 6319863c13a77b..436fc3a09a7685 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -39,6 +39,22 @@ export function useTabsValidationContext() { return VALIDATION_ENABLED ? useContext( TabsValidationContext! ) : null; } +/** + * Hook that throws an error in development if the component + * is not wrapped in a Tabs.Root. + * + * @param componentName The name of the component (for the error message). + */ +export function useRequireTabsRoot( componentName: string ) { + const context = useTabsValidationContext(); + + if ( VALIDATION_ENABLED && context === null ) { + throw new Error( + `\`${ componentName }\` must be used within a \`Tabs.Root\` component.` + ); + } +} + /** * Provider component that tracks registered tabs and panels, * and validates that they match in development mode. diff --git a/packages/ui/src/tabs/list.tsx b/packages/ui/src/tabs/list.tsx index f90a3676d76d32..ac00a5603f779f 100644 --- a/packages/ui/src/tabs/list.tsx +++ b/packages/ui/src/tabs/list.tsx @@ -2,6 +2,7 @@ import { forwardRef, useEffect, useState } from '@wordpress/element'; import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; import { useMergeRefs } from '@wordpress/compose'; +import { useRequireTabsRoot } from './context'; import styles from './style.module.css'; import type { TabListProps } from './types'; @@ -26,6 +27,7 @@ export const List = forwardRef< HTMLDivElement, TabListProps >( }, forwardedRef ) { + useRequireTabsRoot( 'Tabs.List' ); const [ listEl, setListEl ] = useState< HTMLDivElement | null >( null ); const [ overflow, setOverflow ] = useState< { first: boolean; diff --git a/packages/ui/src/tabs/panel.tsx b/packages/ui/src/tabs/panel.tsx index 644f2f72948453..9dd788d6b1ecd0 100644 --- a/packages/ui/src/tabs/panel.tsx +++ b/packages/ui/src/tabs/panel.tsx @@ -1,7 +1,7 @@ import { forwardRef, useEffect } from '@wordpress/element'; import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; -import { useTabsValidationContext } from './context'; +import { useTabsValidationContext, useRequireTabsRoot } from './context'; import styles from './style.module.css'; import type { TabPanelProps } from './types'; @@ -13,6 +13,7 @@ import type { TabPanelProps } from './types'; */ export const Panel = forwardRef< HTMLDivElement, TabPanelProps >( function TabPanel( { className, value, ...otherProps }, forwardedRef ) { + useRequireTabsRoot( 'Tabs.Panel' ); const validationContext = useTabsValidationContext(); // Register this panel's value for validation diff --git a/packages/ui/src/tabs/tab.tsx b/packages/ui/src/tabs/tab.tsx index 656497a5edeabb..ea7c36a53e51e0 100644 --- a/packages/ui/src/tabs/tab.tsx +++ b/packages/ui/src/tabs/tab.tsx @@ -3,7 +3,7 @@ import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; import { chevronRight } from '@wordpress/icons'; import { Icon } from '../icon'; -import { useTabsValidationContext } from './context'; +import { useTabsValidationContext, useRequireTabsRoot } from './context'; import styles from './style.module.css'; import type { TabProps } from './types'; @@ -17,6 +17,7 @@ export const Tab = forwardRef< HTMLButtonElement, TabProps >( function Tab( { className, children, value, ...otherProps }, forwardedRef ) { + useRequireTabsRoot( 'Tabs.Tab' ); const validationContext = useTabsValidationContext(); // Register this tab's value for validation diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index 168bc887ee3e3f..bfdf0e3b313f1d 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2258,6 +2258,47 @@ describe( 'Tabs', () => { } ); describe( 'Development mode validation', () => { + describe( 'components used outside of Root', () => { + // Suppress React's error boundary logging for these tests + beforeEach( () => { + jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + } ); + + afterEach( () => { + ( console.error as jest.Mock ).mockRestore(); + } ); + + it( 'should throw when Tabs.Tab is used outside of Tabs.Root', () => { + expect( () => { + render( Orphan Tab ); + } ).toThrow( + '`Tabs.Tab` must be used within a `Tabs.Root` component.' + ); + } ); + + it( 'should throw when Tabs.Panel is used outside of Tabs.Root', () => { + expect( () => { + render( + Orphan Panel + ); + } ).toThrow( + '`Tabs.Panel` must be used within a `Tabs.Root` component.' + ); + } ); + + it( 'should throw when Tabs.List is used outside of Tabs.Root', () => { + expect( () => { + render( + + One + + ); + } ).toThrow( + '`Tabs.List` must be used within a `Tabs.Root` component.' + ); + } ); + } ); + it( 'should warn when a Tab has no matching Panel', async () => { const consoleWarnSpy = jest .spyOn( console, 'warn' ) From debb45658eb544febe4eb0125ac2eed872e0cd4f Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 10:31:12 +0100 Subject: [PATCH 03/15] Use String() instead of JSON.stringify to prevent errors with certain edge cases --- packages/ui/src/tabs/context.tsx | 4 ++-- packages/ui/src/tabs/test/index.test.tsx | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index 436fc3a09a7685..22e4c0a886bc1b 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -113,7 +113,7 @@ export function TabsValidationProvider( { `Tabs: Found Tab(s) without matching Panel(s). ` + `Each Tab should have a corresponding Panel with the same \`value\` prop. ` + `Tab value(s) without panels: ${ tabsWithoutPanels - .map( ( v ) => JSON.stringify( v ) ) + .map( String ) .join( ', ' ) }` ); } @@ -124,7 +124,7 @@ export function TabsValidationProvider( { `Tabs: Found Panel(s) without matching Tab(s). ` + `Each Panel should have a corresponding Tab with the same \`value\` prop. ` + `Panel value(s) without tabs: ${ panelsWithoutTabs - .map( ( v ) => JSON.stringify( v ) ) + .map( String ) .join( ', ' ) }` ); } diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index bfdf0e3b313f1d..53efdfe5552857 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2329,7 +2329,7 @@ describe( 'Tabs', () => { } ); expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( '"three"' ) + expect.stringContaining( 'three' ) ); consoleWarnSpy.mockRestore(); @@ -2364,7 +2364,7 @@ describe( 'Tabs', () => { } ); expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( '"orphan"' ) + expect.stringContaining( 'orphan' ) ); consoleWarnSpy.mockRestore(); @@ -2422,15 +2422,15 @@ describe( 'Tabs', () => { // Check for tabs without panels warning expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( '"orphan-tab-1"' ) + expect.stringContaining( 'orphan-tab-1' ) ); expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( '"orphan-tab-2"' ) + expect.stringContaining( 'orphan-tab-2' ) ); // Check for panels without tabs warning expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( '"orphan-panel"' ) + expect.stringContaining( 'orphan-panel' ) ); consoleWarnSpy.mockRestore(); From 3eeb09270d76d7d4ede39edb5fcaa43fc15e2d18 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 10:40:35 +0100 Subject: [PATCH 04/15] Don't run hooks conditionally, split dev vs prod implementations entirely --- packages/ui/src/tabs/context.tsx | 95 ++++++++++++++++++++++---------- 1 file changed, 65 insertions(+), 30 deletions(-) diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index 22e4c0a886bc1b..902bd24f3e3d47 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -1,6 +1,3 @@ -/** - * WordPress dependencies - */ import { createContext, useContext, @@ -23,32 +20,41 @@ type TabsValidationContextType = { */ const VALIDATION_ENABLED = process.env.NODE_ENV !== 'production'; -// Only create the context in development mode +// Context is only created in development mode. +// When VALIDATION_ENABLED is true, this is guaranteed to be a valid Context. const TabsValidationContext = VALIDATION_ENABLED ? createContext< TabsValidationContextType | null >( null ) - : null; + : ( null as unknown as React.Context< TabsValidationContextType | null > ); + +/** + * Development-only hook to access the tabs validation context. + */ +function useTabsValidationContextDev() { + return useContext( TabsValidationContext ); +} + +/** + * Production no-op hook. + */ +function useTabsValidationContextProd() { + return null; +} /** * Hook to access the tabs validation context. * Returns null in production or if not within a Tabs.Root. */ -export function useTabsValidationContext() { - // This condition uses a build-time constant, so the else branch - // is completely removed in production builds via dead code elimination. - // eslint-disable-next-line react-hooks/rules-of-hooks -- build-time conditional - return VALIDATION_ENABLED ? useContext( TabsValidationContext! ) : null; -} +export const useTabsValidationContext = VALIDATION_ENABLED + ? useTabsValidationContextDev + : useTabsValidationContextProd; /** - * Hook that throws an error in development if the component - * is not wrapped in a Tabs.Root. - * - * @param componentName The name of the component (for the error message). + * Development-only hook that throws if not within Tabs.Root. */ -export function useRequireTabsRoot( componentName: string ) { - const context = useTabsValidationContext(); +function useRequireTabsRootDev( componentName: string ) { + const context = useTabsValidationContextDev(); - if ( VALIDATION_ENABLED && context === null ) { + if ( context === null ) { throw new Error( `\`${ componentName }\` must be used within a \`Tabs.Root\` component.` ); @@ -56,23 +62,32 @@ export function useRequireTabsRoot( componentName: string ) { } /** - * Provider component that tracks registered tabs and panels, - * and validates that they match in development mode. + * Production no-op hook. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function useRequireTabsRootProd( componentName: string ) { + // No-op in production +} + +/** + * Hook that throws an error in development if the component + * is not wrapped in a Tabs.Root. * - * In production, this component is a no-op and just renders children. + * @param componentName The name of the component (for the error message). + */ +export const useRequireTabsRoot = VALIDATION_ENABLED + ? useRequireTabsRootDev + : useRequireTabsRootProd; + +/** + * Development-only provider that tracks registered tabs and panels, + * and validates that they match. */ -export function TabsValidationProvider( { +function TabsValidationProviderDev( { children, }: { children: React.ReactNode; } ) { - // This condition uses a build-time constant, so all validation logic - // is completely removed in production builds via dead code elimination. - if ( ! VALIDATION_ENABLED ) { - return children; - } - - /* eslint-disable react-hooks/rules-of-hooks -- build-time conditional above ensures consistent hook calls */ const tabsRef = useRef< Set< TabValue > >( new Set() ); const panelsRef = useRef< Set< TabValue > >( new Set() ); const validationScheduledRef = useRef< ReturnType< @@ -177,7 +192,6 @@ export function TabsValidationProvider( { } ), [ registerTab, registerPanel ] ); - /* eslint-enable react-hooks/rules-of-hooks */ return ( @@ -185,3 +199,24 @@ export function TabsValidationProvider( { ); } + +/** + * Production no-op provider that just renders children. + */ +function TabsValidationProviderProd( { + children, +}: { + children: React.ReactNode; +} ) { + return <>{ children }; +} + +/** + * Provider component that tracks registered tabs and panels, + * and validates that they match in development mode. + * + * In production, this component is a no-op and just renders children. + */ +export const TabsValidationProvider = VALIDATION_ENABLED + ? TabsValidationProviderDev + : TabsValidationProviderProd; From 643884c46056b6783bdaf1ca5415606abfd2c6c0 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 10:44:08 +0100 Subject: [PATCH 05/15] Re-use tabvalue type --- packages/ui/src/tabs/context.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index 902bd24f3e3d47..1d6dc86b29070a 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -7,7 +7,12 @@ import { useEffect, } from '@wordpress/element'; -type TabValue = any; +import type { TabProps } from './types'; + +/** + * The type for tab/panel value props, derived from the actual TabProps. + */ +type TabValue = TabProps[ 'value' ]; type TabsValidationContextType = { registerTab: ( value: TabValue ) => () => void; From eced9d829c55931d3a3426ab9c3eb672f4396b38 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 10:55:32 +0100 Subject: [PATCH 06/15] CHANGELOG --- packages/ui/CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/ui/CHANGELOG.md b/packages/ui/CHANGELOG.md index 1f2a0454abedc5..3016b2eac857e5 100644 --- a/packages/ui/CHANGELOG.md +++ b/packages/ui/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Internal + +- `Tabs`: Add development-mode validation for Tab/Panel value matching and Root wrapper requirement ([#75170](https://github.com/WordPress/gutenberg/pull/75170)). + ## 0.9.0 (2026-03-18) ### New Features From 561910b3ab6c532f9567b863befd662f4705137e Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 11:12:11 +0100 Subject: [PATCH 07/15] Fix TS errors --- packages/ui/src/tabs/panel.tsx | 1 + packages/ui/src/tabs/tab.tsx | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/ui/src/tabs/panel.tsx b/packages/ui/src/tabs/panel.tsx index 9dd788d6b1ecd0..f8f2744352918b 100644 --- a/packages/ui/src/tabs/panel.tsx +++ b/packages/ui/src/tabs/panel.tsx @@ -21,6 +21,7 @@ export const Panel = forwardRef< HTMLDivElement, TabPanelProps >( if ( validationContext && value !== undefined ) { return validationContext.registerPanel( value ); } + return undefined; }, [ validationContext, value ] ); return ( diff --git a/packages/ui/src/tabs/tab.tsx b/packages/ui/src/tabs/tab.tsx index ea7c36a53e51e0..f3589d16d9c2d1 100644 --- a/packages/ui/src/tabs/tab.tsx +++ b/packages/ui/src/tabs/tab.tsx @@ -25,6 +25,7 @@ export const Tab = forwardRef< HTMLButtonElement, TabProps >( function Tab( if ( validationContext && value !== undefined ) { return validationContext.registerTab( value ); } + return undefined; }, [ validationContext, value ] ); return ( From 000d2e919b580d130b188ba68e55c79c8029dd9e Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 11:20:51 +0100 Subject: [PATCH 08/15] Use @wordpress/jest-console for better console assertions --- package-lock.json | 1 + packages/ui/global.d.ts | 1 + packages/ui/package.json | 1 + packages/ui/src/tabs/test/index.test.tsx | 77 ++++++++---------------- 4 files changed, 29 insertions(+), 51 deletions(-) diff --git a/package-lock.json b/package-lock.json index adc99623078299..6dac45df17178d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -62683,6 +62683,7 @@ "@testing-library/jest-dom": "^6.9.1", "@types/jest": "^29.5.14", "@types/node": "^20.17.10", + "@wordpress/jest-console": "file:../jest-console", "storybook": "^10.2.8" }, "engines": { diff --git a/packages/ui/global.d.ts b/packages/ui/global.d.ts index 07d96c55dc3554..707804b8732422 100644 --- a/packages/ui/global.d.ts +++ b/packages/ui/global.d.ts @@ -3,3 +3,4 @@ // To ensure that global types are included, we need to // explicitly reference them here. import '@testing-library/jest-dom'; +import '@wordpress/jest-console'; diff --git a/packages/ui/package.json b/packages/ui/package.json index 92164b9690f824..40ab191ddd7473 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -61,6 +61,7 @@ "@testing-library/jest-dom": "^6.9.1", "@types/jest": "^29.5.14", "@types/node": "^20.17.10", + "@wordpress/jest-console": "file:../jest-console", "storybook": "^10.2.8" }, "peerDependencies": { diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index 53efdfe5552857..e61452f429f1b7 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2259,13 +2259,21 @@ describe( 'Tabs', () => { describe( 'Development mode validation', () => { describe( 'components used outside of Root', () => { - // Suppress React's error boundary logging for these tests + // Suppress React's error boundary logging for these tests. + // We use manual mocking because @wordpress/jest-console's toHaveErrored() + // has issues when running in the full test suite context. + let originalConsoleError: typeof console.error; + beforeEach( () => { - jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + // eslint-disable-next-line no-console + originalConsoleError = console.error; + // eslint-disable-next-line no-console + console.error = jest.fn(); } ); afterEach( () => { - ( console.error as jest.Mock ).mockRestore(); + // eslint-disable-next-line no-console + console.error = originalConsoleError; } ); it( 'should throw when Tabs.Tab is used outside of Tabs.Root', () => { @@ -2300,10 +2308,6 @@ describe( 'Tabs', () => { } ); it( 'should warn when a Tab has no matching Panel', async () => { - const consoleWarnSpy = jest - .spyOn( console, 'warn' ) - .mockImplementation( () => {} ); - render( @@ -2321,25 +2325,16 @@ describe( 'Tabs', () => { // Wait for the validation to run (it's scheduled with setTimeout) await waitFor( () => { - expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( - 'Found Tab(s) without matching Panel(s)' - ) - ); + expect( console ).toHaveWarned(); } ); - expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( 'three' ) + // Verify the warning mentions the orphan tab value + expect( console ).toHaveWarnedWith( + 'Tabs: Found Tab(s) without matching Panel(s). Each Tab should have a corresponding Panel with the same `value` prop. Tab value(s) without panels: three' ); - - consoleWarnSpy.mockRestore(); } ); it( 'should warn when a Panel has no matching Tab', async () => { - const consoleWarnSpy = jest - .spyOn( console, 'warn' ) - .mockImplementation( () => {} ); - render( @@ -2356,25 +2351,16 @@ describe( 'Tabs', () => { // Wait for the validation to run (it's scheduled with setTimeout) await waitFor( () => { - expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( - 'Found Panel(s) without matching Tab(s)' - ) - ); + expect( console ).toHaveWarned(); } ); - expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( 'orphan' ) + // Verify the warning mentions the orphan panel value + expect( console ).toHaveWarnedWith( + 'Tabs: Found Panel(s) without matching Tab(s). Each Panel should have a corresponding Tab with the same `value` prop. Panel value(s) without tabs: orphan' ); - - consoleWarnSpy.mockRestore(); } ); it( 'should not warn when all Tabs and Panels match', async () => { - const consoleWarnSpy = jest - .spyOn( console, 'warn' ) - .mockImplementation( () => {} ); - render( @@ -2391,16 +2377,10 @@ describe( 'Tabs', () => { // Wait a bit to ensure validation has run await new Promise( ( resolve ) => setTimeout( resolve, 50 ) ); - expect( consoleWarnSpy ).not.toHaveBeenCalled(); - - consoleWarnSpy.mockRestore(); + expect( console ).not.toHaveWarned(); } ); it( 'should warn about multiple mismatches', async () => { - const consoleWarnSpy = jest - .spyOn( console, 'warn' ) - .mockImplementation( () => {} ); - render( @@ -2417,23 +2397,18 @@ describe( 'Tabs', () => { // Wait for the validation to run await waitFor( () => { - expect( consoleWarnSpy ).toHaveBeenCalledTimes( 2 ); + expect( console ).toHaveWarned(); } ); - // Check for tabs without panels warning - expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( 'orphan-tab-1' ) - ); - expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( 'orphan-tab-2' ) + // Check for tabs without panels warning (both orphan tabs in one message) + expect( console ).toHaveWarnedWith( + 'Tabs: Found Tab(s) without matching Panel(s). Each Tab should have a corresponding Panel with the same `value` prop. Tab value(s) without panels: orphan-tab-1, orphan-tab-2' ); // Check for panels without tabs warning - expect( consoleWarnSpy ).toHaveBeenCalledWith( - expect.stringContaining( 'orphan-panel' ) + expect( console ).toHaveWarnedWith( + 'Tabs: Found Panel(s) without matching Tab(s). Each Panel should have a corresponding Tab with the same `value` prop. Panel value(s) without tabs: orphan-panel' ); - - consoleWarnSpy.mockRestore(); } ); } ); } ); From 0fdfa9d75baf8d0099f3e4c8d7ec27cf9233573d Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 11:22:46 +0100 Subject: [PATCH 09/15] Add a test for validating dynamic value changes --- packages/ui/src/tabs/test/index.test.tsx | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index e61452f429f1b7..a1029851fcb775 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2360,6 +2360,52 @@ describe( 'Tabs', () => { ); } ); + it( 'should handle dynamic value changes correctly', async () => { + const { rerender } = render( + + + One + Two + + First panel + Second panel + + ); + + await waitForComponentToBeInitializedWithSelectedTab( 'One' ); + + // Wait for validation + await new Promise( ( resolve ) => setTimeout( resolve, 50 ) ); + + // No warnings since all values match + expect( console ).not.toHaveWarned(); + + // Change a tab's value to create a mismatch + rerender( + + + One + Two + + First panel + Second panel + + ); + + // Wait for validation to run after the value change + await waitFor( () => { + expect( console ).toHaveWarned(); + } ); + + // Should warn about "changed" tab without panel AND "two" panel without tab + expect( console ).toHaveWarnedWith( + 'Tabs: Found Tab(s) without matching Panel(s). Each Tab should have a corresponding Panel with the same `value` prop. Tab value(s) without panels: changed' + ); + expect( console ).toHaveWarnedWith( + 'Tabs: Found Panel(s) without matching Tab(s). Each Panel should have a corresponding Tab with the same `value` prop. Panel value(s) without tabs: two' + ); + } ); + it( 'should not warn when all Tabs and Panels match', async () => { render( From f3b4b49220630a7898e15631523b201c24424740 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 3 Feb 2026 15:27:25 +0100 Subject: [PATCH 10/15] Use @wordpress/warning package --- package-lock.json | 1 + packages/ui/package.json | 1 + packages/ui/src/tabs/context.tsx | 7 ++--- packages/ui/tsconfig.json | 48 ++++++++++++++++++++++++-------- 4 files changed, 42 insertions(+), 15 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6dac45df17178d..ac62042ef98524 100644 --- a/package-lock.json +++ b/package-lock.json @@ -62675,6 +62675,7 @@ "@wordpress/primitives": "file:../primitives", "@wordpress/private-apis": "file:../private-apis", "@wordpress/theme": "file:../theme", + "@wordpress/warning": "file:../warning", "clsx": "^2.1.1" }, "devDependencies": { diff --git a/packages/ui/package.json b/packages/ui/package.json index 40ab191ddd7473..3a5a2f24bb5365 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -53,6 +53,7 @@ "@wordpress/primitives": "file:../primitives", "@wordpress/private-apis": "file:../private-apis", "@wordpress/theme": "file:../theme", + "@wordpress/warning": "file:../warning", "clsx": "^2.1.1" }, "devDependencies": { diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index 1d6dc86b29070a..a28637c1fe6996 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -6,6 +6,7 @@ import { useRef, useEffect, } from '@wordpress/element'; +import warning from '@wordpress/warning'; import type { TabProps } from './types'; @@ -128,8 +129,7 @@ function TabsValidationProviderDev( { // Warn about mismatches if ( tabsWithoutPanels.length > 0 ) { - // eslint-disable-next-line no-console - console.warn( + warning( `Tabs: Found Tab(s) without matching Panel(s). ` + `Each Tab should have a corresponding Panel with the same \`value\` prop. ` + `Tab value(s) without panels: ${ tabsWithoutPanels @@ -139,8 +139,7 @@ function TabsValidationProviderDev( { } if ( panelsWithoutTabs.length > 0 ) { - // eslint-disable-next-line no-console - console.warn( + warning( `Tabs: Found Panel(s) without matching Tab(s). ` + `Each Panel should have a corresponding Tab with the same \`value\` prop. ` + `Panel value(s) without tabs: ${ panelsWithoutTabs diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json index 81f7e58d2d1619..30c04ad70658f5 100644 --- a/packages/ui/tsconfig.json +++ b/packages/ui/tsconfig.json @@ -2,19 +2,45 @@ "$schema": "https://json.schemastore.org/tsconfig.json", "extends": "../../tsconfig.base.json", "compilerOptions": { - "types": [ "node", "jest" ] + "types": [ + "node", + "jest" + ] }, "references": [ - { "path": "../a11y" }, - { "path": "../compose" }, - { "path": "../element" }, - { "path": "../i18n" }, - { "path": "../icons" }, - { "path": "../keycodes" }, - { "path": "../primitives" }, - { "path": "../private-apis" }, - { "path": "../theme" } + { + "path": "../a11y" + }, + { + "path": "../compose" + }, + { + "path": "../element" + }, + { + "path": "../i18n" + }, + { + "path": "../icons" + }, + { + "path": "../keycodes" + }, + { + "path": "../primitives" + }, + { + "path": "../private-apis" + }, + { + "path": "../theme" + }, + { + "path": "../warning" + } + ], + "files": [ + "global.d.ts" ], - "files": [ "global.d.ts" ], "exclude": [] } From 2e61396e661ccad24f909efb46df7663ba370592 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Wed, 4 Feb 2026 15:15:25 +0100 Subject: [PATCH 11/15] Fix validation tracking with Map instead of Set Address PR feedback: Use Map instead of Set to correctly track counts of tabs/panels with the same value. This prevents false mismatch warnings when one duplicate unmounts while another is still mounted. Also adds warnings for duplicate Tab/Panel values to help developers catch configuration issues early. Co-authored-by: Cursor --- packages/ui/src/tabs/context.tsx | 75 ++++++++++++++++++++---- packages/ui/src/tabs/test/index.test.tsx | 31 ++++++++++ 2 files changed, 94 insertions(+), 12 deletions(-) diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index a28637c1fe6996..d837e6e8948824 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -94,8 +94,10 @@ function TabsValidationProviderDev( { }: { children: React.ReactNode; } ) { - const tabsRef = useRef< Set< TabValue > >( new Set() ); - const panelsRef = useRef< Set< TabValue > >( new Set() ); + // Use Map to track counts of each value. + // This correctly handles multiple instances with the same value. + const tabsRef = useRef< Map< TabValue, number > >( new Map() ); + const panelsRef = useRef< Map< TabValue, number > >( new Map() ); const validationScheduledRef = useRef< ReturnType< typeof setTimeout > | null >( null ); @@ -108,25 +110,41 @@ function TabsValidationProviderDev( { // Schedule validation for the next tick to allow all registrations to complete validationScheduledRef.current = setTimeout( () => { - const tabValues = tabsRef.current; - const panelValues = panelsRef.current; + const tabCounts = tabsRef.current; + const panelCounts = panelsRef.current; // Find tabs without matching panels const tabsWithoutPanels: TabValue[] = []; - tabValues.forEach( ( value ) => { - if ( ! panelValues.has( value ) ) { + tabCounts.forEach( ( _count, value ) => { + if ( ! panelCounts.has( value ) ) { tabsWithoutPanels.push( value ); } } ); // Find panels without matching tabs const panelsWithoutTabs: TabValue[] = []; - panelValues.forEach( ( value ) => { - if ( ! tabValues.has( value ) ) { + panelCounts.forEach( ( _count, value ) => { + if ( ! tabCounts.has( value ) ) { panelsWithoutTabs.push( value ); } } ); + // Find duplicate tabs (count > 1) + const duplicateTabs: TabValue[] = []; + tabCounts.forEach( ( count, value ) => { + if ( count > 1 ) { + duplicateTabs.push( value ); + } + } ); + + // Find duplicate panels (count > 1) + const duplicatePanels: TabValue[] = []; + panelCounts.forEach( ( count, value ) => { + if ( count > 1 ) { + duplicatePanels.push( value ); + } + } ); + // Warn about mismatches if ( tabsWithoutPanels.length > 0 ) { warning( @@ -148,18 +166,45 @@ function TabsValidationProviderDev( { ); } + // Warn about duplicates + if ( duplicateTabs.length > 0 ) { + warning( + `Tabs: Found duplicate Tab value(s). ` + + `Each Tab should have a unique \`value\` prop. ` + + `Duplicate value(s): ${ duplicateTabs + .map( String ) + .join( ', ' ) }` + ); + } + + if ( duplicatePanels.length > 0 ) { + warning( + `Tabs: Found duplicate Panel value(s). ` + + `Each Panel should have a unique \`value\` prop. ` + + `Duplicate value(s): ${ duplicatePanels + .map( String ) + .join( ', ' ) }` + ); + } + validationScheduledRef.current = null; }, 0 ); }, [] ); const registerTab = useCallback( ( value: TabValue ) => { - tabsRef.current.add( value ); + const currentCount = tabsRef.current.get( value ) ?? 0; + tabsRef.current.set( value, currentCount + 1 ); scheduleValidation(); // Return unregister function return () => { - tabsRef.current.delete( value ); + const count = tabsRef.current.get( value ) ?? 0; + if ( count <= 1 ) { + tabsRef.current.delete( value ); + } else { + tabsRef.current.set( value, count - 1 ); + } scheduleValidation(); }; }, @@ -168,12 +213,18 @@ function TabsValidationProviderDev( { const registerPanel = useCallback( ( value: TabValue ) => { - panelsRef.current.add( value ); + const currentCount = panelsRef.current.get( value ) ?? 0; + panelsRef.current.set( value, currentCount + 1 ); scheduleValidation(); // Return unregister function return () => { - panelsRef.current.delete( value ); + const count = panelsRef.current.get( value ) ?? 0; + if ( count <= 1 ) { + panelsRef.current.delete( value ); + } else { + panelsRef.current.set( value, count - 1 ); + } scheduleValidation(); }; }, diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index a1029851fcb775..f2de652c35bd1b 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2456,6 +2456,37 @@ describe( 'Tabs', () => { 'Tabs: Found Panel(s) without matching Tab(s). Each Panel should have a corresponding Tab with the same `value` prop. Panel value(s) without tabs: orphan-panel' ); } ); + + // Note: We cannot test duplicate Tab values directly because Base UI's + // internal state management breaks with "Maximum update depth exceeded" + // when duplicate tab values are present. The validation warning for + // duplicate tabs would help developers catch this before the error. + + it( 'should warn when duplicate Panel values are detected', async () => { + render( + + + One + Two + + First panel + Second panel + Second panel duplicate + + ); + + await waitForComponentToBeInitializedWithSelectedTab( 'One' ); + + // Wait for the validation to run + await waitFor( () => { + expect( console ).toHaveWarned(); + } ); + + // Verify the warning mentions the duplicate panel value + expect( console ).toHaveWarnedWith( + 'Tabs: Found duplicate Panel value(s). Each Panel should have a unique `value` prop. Duplicate value(s): two' + ); + } ); } ); } ); /* eslint-enable jest/no-conditional-expect */ From 393fbe6e4ba7575b44673856c5c20b789140d4e6 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 17 Mar 2026 19:46:02 +0100 Subject: [PATCH 12/15] Tabs: simplify validation to count-based Tab/Panel matching Replace the value-level Map-based tracking with simple counters that compare Tab count vs Panel count. This catches the primary abuse vector (using Tabs as a faux router without panels) with significantly less complexity. Drop duplicate detection and value-level mismatch warnings since those misconfigurations already manifest as visibly broken UI. Made-with: Cursor --- packages/ui/CHANGELOG.md | 2 +- packages/ui/src/tabs/context.tsx | 226 ++++++----------------- packages/ui/src/tabs/list.tsx | 2 - packages/ui/src/tabs/panel.tsx | 18 +- packages/ui/src/tabs/tab.tsx | 18 +- packages/ui/src/tabs/test/index.test.tsx | 145 +++------------ 6 files changed, 89 insertions(+), 322 deletions(-) diff --git a/packages/ui/CHANGELOG.md b/packages/ui/CHANGELOG.md index 3016b2eac857e5..1882a1615fccf1 100644 --- a/packages/ui/CHANGELOG.md +++ b/packages/ui/CHANGELOG.md @@ -4,7 +4,7 @@ ### Internal -- `Tabs`: Add development-mode validation for Tab/Panel value matching and Root wrapper requirement ([#75170](https://github.com/WordPress/gutenberg/pull/75170)). +- `Tabs`: Add development-mode validation for Tab/Panel count matching ([#75170](https://github.com/WordPress/gutenberg/pull/75170)). ## 0.9.0 (2026-03-18) diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index d837e6e8948824..5a56ba3da64fe3 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -8,16 +8,9 @@ import { } from '@wordpress/element'; import warning from '@wordpress/warning'; -import type { TabProps } from './types'; - -/** - * The type for tab/panel value props, derived from the actual TabProps. - */ -type TabValue = TabProps[ 'value' ]; - type TabsValidationContextType = { - registerTab: ( value: TabValue ) => () => void; - registerPanel: ( value: TabValue ) => () => void; + registerTab: () => () => void; + registerPanel: () => () => void; }; /** @@ -26,164 +19,84 @@ type TabsValidationContextType = { */ const VALIDATION_ENABLED = process.env.NODE_ENV !== 'production'; -// Context is only created in development mode. -// When VALIDATION_ENABLED is true, this is guaranteed to be a valid Context. const TabsValidationContext = VALIDATION_ENABLED ? createContext< TabsValidationContextType | null >( null ) : ( null as unknown as React.Context< TabsValidationContextType | null > ); -/** - * Development-only hook to access the tabs validation context. - */ -function useTabsValidationContextDev() { - return useContext( TabsValidationContext ); +function useRegisterTabDev() { + const context = useContext( TabsValidationContext ); + + useEffect( () => { + if ( context ) { + return context.registerTab(); + } + return undefined; + }, [ context ] ); } -/** - * Production no-op hook. - */ -function useTabsValidationContextProd() { - return null; +function useRegisterTabProd() { + // No-op in production. } /** - * Hook to access the tabs validation context. - * Returns null in production or if not within a Tabs.Root. + * Hook that registers a Tab for count validation in development mode. */ -export const useTabsValidationContext = VALIDATION_ENABLED - ? useTabsValidationContextDev - : useTabsValidationContextProd; +export const useRegisterTab = VALIDATION_ENABLED + ? useRegisterTabDev + : useRegisterTabProd; -/** - * Development-only hook that throws if not within Tabs.Root. - */ -function useRequireTabsRootDev( componentName: string ) { - const context = useTabsValidationContextDev(); +function useRegisterPanelDev() { + const context = useContext( TabsValidationContext ); - if ( context === null ) { - throw new Error( - `\`${ componentName }\` must be used within a \`Tabs.Root\` component.` - ); - } + useEffect( () => { + if ( context ) { + return context.registerPanel(); + } + return undefined; + }, [ context ] ); } -/** - * Production no-op hook. - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function useRequireTabsRootProd( componentName: string ) { - // No-op in production +function useRegisterPanelProd() { + // No-op in production. } /** - * Hook that throws an error in development if the component - * is not wrapped in a Tabs.Root. - * - * @param componentName The name of the component (for the error message). + * Hook that registers a Panel for count validation in development mode. */ -export const useRequireTabsRoot = VALIDATION_ENABLED - ? useRequireTabsRootDev - : useRequireTabsRootProd; +export const useRegisterPanel = VALIDATION_ENABLED + ? useRegisterPanelDev + : useRegisterPanelProd; /** - * Development-only provider that tracks registered tabs and panels, - * and validates that they match. + * Development-only provider that tracks the number of registered tabs and + * panels, and warns when the counts don't match. */ function TabsValidationProviderDev( { children, }: { children: React.ReactNode; } ) { - // Use Map to track counts of each value. - // This correctly handles multiple instances with the same value. - const tabsRef = useRef< Map< TabValue, number > >( new Map() ); - const panelsRef = useRef< Map< TabValue, number > >( new Map() ); + const tabCountRef = useRef( 0 ); + const panelCountRef = useRef( 0 ); const validationScheduledRef = useRef< ReturnType< typeof setTimeout > | null >( null ); const scheduleValidation = useCallback( () => { - // Clear any existing scheduled validation if ( validationScheduledRef.current ) { clearTimeout( validationScheduledRef.current ); } - // Schedule validation for the next tick to allow all registrations to complete + // Schedule validation for the next tick to allow all + // registrations/unregistrations to complete. validationScheduledRef.current = setTimeout( () => { - const tabCounts = tabsRef.current; - const panelCounts = panelsRef.current; - - // Find tabs without matching panels - const tabsWithoutPanels: TabValue[] = []; - tabCounts.forEach( ( _count, value ) => { - if ( ! panelCounts.has( value ) ) { - tabsWithoutPanels.push( value ); - } - } ); - - // Find panels without matching tabs - const panelsWithoutTabs: TabValue[] = []; - panelCounts.forEach( ( _count, value ) => { - if ( ! tabCounts.has( value ) ) { - panelsWithoutTabs.push( value ); - } - } ); - - // Find duplicate tabs (count > 1) - const duplicateTabs: TabValue[] = []; - tabCounts.forEach( ( count, value ) => { - if ( count > 1 ) { - duplicateTabs.push( value ); - } - } ); + const tabCount = tabCountRef.current; + const panelCount = panelCountRef.current; - // Find duplicate panels (count > 1) - const duplicatePanels: TabValue[] = []; - panelCounts.forEach( ( count, value ) => { - if ( count > 1 ) { - duplicatePanels.push( value ); - } - } ); - - // Warn about mismatches - if ( tabsWithoutPanels.length > 0 ) { - warning( - `Tabs: Found Tab(s) without matching Panel(s). ` + - `Each Tab should have a corresponding Panel with the same \`value\` prop. ` + - `Tab value(s) without panels: ${ tabsWithoutPanels - .map( String ) - .join( ', ' ) }` - ); - } - - if ( panelsWithoutTabs.length > 0 ) { + if ( tabCount !== panelCount ) { warning( - `Tabs: Found Panel(s) without matching Tab(s). ` + - `Each Panel should have a corresponding Tab with the same \`value\` prop. ` + - `Panel value(s) without tabs: ${ panelsWithoutTabs - .map( String ) - .join( ', ' ) }` - ); - } - - // Warn about duplicates - if ( duplicateTabs.length > 0 ) { - warning( - `Tabs: Found duplicate Tab value(s). ` + - `Each Tab should have a unique \`value\` prop. ` + - `Duplicate value(s): ${ duplicateTabs - .map( String ) - .join( ', ' ) }` - ); - } - - if ( duplicatePanels.length > 0 ) { - warning( - `Tabs: Found duplicate Panel value(s). ` + - `Each Panel should have a unique \`value\` prop. ` + - `Duplicate value(s): ${ duplicatePanels - .map( String ) - .join( ', ' ) }` + `Tabs: Tab/Panel count mismatch. Found ${ tabCount } Tab(s) and ${ panelCount } Panel(s). ` + + `Each Tab should have a corresponding Panel.` ); } @@ -191,47 +104,26 @@ function TabsValidationProviderDev( { }, 0 ); }, [] ); - const registerTab = useCallback( - ( value: TabValue ) => { - const currentCount = tabsRef.current.get( value ) ?? 0; - tabsRef.current.set( value, currentCount + 1 ); + const registerTab = useCallback( () => { + tabCountRef.current += 1; + scheduleValidation(); + + return () => { + tabCountRef.current -= 1; scheduleValidation(); + }; + }, [ scheduleValidation ] ); - // Return unregister function - return () => { - const count = tabsRef.current.get( value ) ?? 0; - if ( count <= 1 ) { - tabsRef.current.delete( value ); - } else { - tabsRef.current.set( value, count - 1 ); - } - scheduleValidation(); - }; - }, - [ scheduleValidation ] - ); + const registerPanel = useCallback( () => { + panelCountRef.current += 1; + scheduleValidation(); - const registerPanel = useCallback( - ( value: TabValue ) => { - const currentCount = panelsRef.current.get( value ) ?? 0; - panelsRef.current.set( value, currentCount + 1 ); + return () => { + panelCountRef.current -= 1; scheduleValidation(); + }; + }, [ scheduleValidation ] ); - // Return unregister function - return () => { - const count = panelsRef.current.get( value ) ?? 0; - if ( count <= 1 ) { - panelsRef.current.delete( value ); - } else { - panelsRef.current.set( value, count - 1 ); - } - scheduleValidation(); - }; - }, - [ scheduleValidation ] - ); - - // Cleanup scheduled validation on unmount useEffect( () => { return () => { if ( validationScheduledRef.current ) { @@ -267,8 +159,8 @@ function TabsValidationProviderProd( { } /** - * Provider component that tracks registered tabs and panels, - * and validates that they match in development mode. + * Provider component that validates the number of tabs matches the number + * of panels in development mode. * * In production, this component is a no-op and just renders children. */ diff --git a/packages/ui/src/tabs/list.tsx b/packages/ui/src/tabs/list.tsx index ac00a5603f779f..f90a3676d76d32 100644 --- a/packages/ui/src/tabs/list.tsx +++ b/packages/ui/src/tabs/list.tsx @@ -2,7 +2,6 @@ import { forwardRef, useEffect, useState } from '@wordpress/element'; import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; import { useMergeRefs } from '@wordpress/compose'; -import { useRequireTabsRoot } from './context'; import styles from './style.module.css'; import type { TabListProps } from './types'; @@ -27,7 +26,6 @@ export const List = forwardRef< HTMLDivElement, TabListProps >( }, forwardedRef ) { - useRequireTabsRoot( 'Tabs.List' ); const [ listEl, setListEl ] = useState< HTMLDivElement | null >( null ); const [ overflow, setOverflow ] = useState< { first: boolean; diff --git a/packages/ui/src/tabs/panel.tsx b/packages/ui/src/tabs/panel.tsx index f8f2744352918b..2396e7586e292b 100644 --- a/packages/ui/src/tabs/panel.tsx +++ b/packages/ui/src/tabs/panel.tsx @@ -1,7 +1,7 @@ -import { forwardRef, useEffect } from '@wordpress/element'; +import { forwardRef } from '@wordpress/element'; import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; -import { useTabsValidationContext, useRequireTabsRoot } from './context'; +import { useRegisterPanel } from './context'; import styles from './style.module.css'; import type { TabPanelProps } from './types'; @@ -12,23 +12,13 @@ import type { TabPanelProps } from './types'; * an [ARIA-compliant tabs pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/). */ export const Panel = forwardRef< HTMLDivElement, TabPanelProps >( - function TabPanel( { className, value, ...otherProps }, forwardedRef ) { - useRequireTabsRoot( 'Tabs.Panel' ); - const validationContext = useTabsValidationContext(); - - // Register this panel's value for validation - useEffect( () => { - if ( validationContext && value !== undefined ) { - return validationContext.registerPanel( value ); - } - return undefined; - }, [ validationContext, value ] ); + function TabPanel( { className, ...otherProps }, forwardedRef ) { + useRegisterPanel(); return ( <_Tabs.Panel ref={ forwardedRef } className={ clsx( styles.tabpanel, className ) } - value={ value } { ...otherProps } /> ); diff --git a/packages/ui/src/tabs/tab.tsx b/packages/ui/src/tabs/tab.tsx index f3589d16d9c2d1..d94fc3240c4dbc 100644 --- a/packages/ui/src/tabs/tab.tsx +++ b/packages/ui/src/tabs/tab.tsx @@ -1,9 +1,9 @@ -import { forwardRef, useEffect } from '@wordpress/element'; +import { forwardRef } from '@wordpress/element'; import clsx from 'clsx'; import { Tabs as _Tabs } from '@base-ui/react/tabs'; import { chevronRight } from '@wordpress/icons'; import { Icon } from '../icon'; -import { useTabsValidationContext, useRequireTabsRoot } from './context'; +import { useRegisterTab } from './context'; import styles from './style.module.css'; import type { TabProps } from './types'; @@ -14,25 +14,15 @@ import type { TabProps } from './types'; * an [ARIA-compliant tabs pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/). */ export const Tab = forwardRef< HTMLButtonElement, TabProps >( function Tab( - { className, children, value, ...otherProps }, + { className, children, ...otherProps }, forwardedRef ) { - useRequireTabsRoot( 'Tabs.Tab' ); - const validationContext = useTabsValidationContext(); - - // Register this tab's value for validation - useEffect( () => { - if ( validationContext && value !== undefined ) { - return validationContext.registerTab( value ); - } - return undefined; - }, [ validationContext, value ] ); + useRegisterTab(); return ( <_Tabs.Tab ref={ forwardedRef } className={ clsx( styles.tab, className ) } - value={ value } { ...otherProps } > { children } diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index f2de652c35bd1b..ae578b622f1b51 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2258,56 +2258,7 @@ describe( 'Tabs', () => { } ); describe( 'Development mode validation', () => { - describe( 'components used outside of Root', () => { - // Suppress React's error boundary logging for these tests. - // We use manual mocking because @wordpress/jest-console's toHaveErrored() - // has issues when running in the full test suite context. - let originalConsoleError: typeof console.error; - - beforeEach( () => { - // eslint-disable-next-line no-console - originalConsoleError = console.error; - // eslint-disable-next-line no-console - console.error = jest.fn(); - } ); - - afterEach( () => { - // eslint-disable-next-line no-console - console.error = originalConsoleError; - } ); - - it( 'should throw when Tabs.Tab is used outside of Tabs.Root', () => { - expect( () => { - render( Orphan Tab ); - } ).toThrow( - '`Tabs.Tab` must be used within a `Tabs.Root` component.' - ); - } ); - - it( 'should throw when Tabs.Panel is used outside of Tabs.Root', () => { - expect( () => { - render( - Orphan Panel - ); - } ).toThrow( - '`Tabs.Panel` must be used within a `Tabs.Root` component.' - ); - } ); - - it( 'should throw when Tabs.List is used outside of Tabs.Root', () => { - expect( () => { - render( - - One - - ); - } ).toThrow( - '`Tabs.List` must be used within a `Tabs.Root` component.' - ); - } ); - } ); - - it( 'should warn when a Tab has no matching Panel', async () => { + it( 'should warn when there are more Tabs than Panels', async () => { render( @@ -2317,24 +2268,21 @@ describe( 'Tabs', () => { First panel Second panel - { /* Missing panel for "three" */ } ); await waitForComponentToBeInitializedWithSelectedTab( 'One' ); - // Wait for the validation to run (it's scheduled with setTimeout) await waitFor( () => { expect( console ).toHaveWarned(); } ); - // Verify the warning mentions the orphan tab value expect( console ).toHaveWarnedWith( - 'Tabs: Found Tab(s) without matching Panel(s). Each Tab should have a corresponding Panel with the same `value` prop. Tab value(s) without panels: three' + 'Tabs: Tab/Panel count mismatch. Found 3 Tab(s) and 2 Panel(s). Each Tab should have a corresponding Panel.' ); } ); - it( 'should warn when a Panel has no matching Tab', async () => { + it( 'should warn when there are more Panels than Tabs', async () => { render( @@ -2343,25 +2291,23 @@ describe( 'Tabs', () => { First panel Second panel - Orphan panel + Third panel ); await waitForComponentToBeInitializedWithSelectedTab( 'One' ); - // Wait for the validation to run (it's scheduled with setTimeout) await waitFor( () => { expect( console ).toHaveWarned(); } ); - // Verify the warning mentions the orphan panel value expect( console ).toHaveWarnedWith( - 'Tabs: Found Panel(s) without matching Tab(s). Each Panel should have a corresponding Tab with the same `value` prop. Panel value(s) without tabs: orphan' + 'Tabs: Tab/Panel count mismatch. Found 2 Tab(s) and 3 Panel(s). Each Tab should have a corresponding Panel.' ); } ); - it( 'should handle dynamic value changes correctly', async () => { - const { rerender } = render( + it( 'should not warn when Tab and Panel counts match', async () => { + render( One @@ -2374,40 +2320,33 @@ describe( 'Tabs', () => { await waitForComponentToBeInitializedWithSelectedTab( 'One' ); - // Wait for validation + // Wait a bit to ensure validation has run await new Promise( ( resolve ) => setTimeout( resolve, 50 ) ); - // No warnings since all values match expect( console ).not.toHaveWarned(); + } ); - // Change a tab's value to create a mismatch - rerender( - + it( 'should warn when tabs are used without any panels', async () => { + render( + One - Two + Two - First panel - Second panel ); - // Wait for validation to run after the value change await waitFor( () => { expect( console ).toHaveWarned(); } ); - // Should warn about "changed" tab without panel AND "two" panel without tab - expect( console ).toHaveWarnedWith( - 'Tabs: Found Tab(s) without matching Panel(s). Each Tab should have a corresponding Panel with the same `value` prop. Tab value(s) without panels: changed' - ); expect( console ).toHaveWarnedWith( - 'Tabs: Found Panel(s) without matching Tab(s). Each Panel should have a corresponding Tab with the same `value` prop. Panel value(s) without tabs: two' + 'Tabs: Tab/Panel count mismatch. Found 2 Tab(s) and 0 Panel(s). Each Tab should have a corresponding Panel.' ); } ); - it( 'should not warn when all Tabs and Panels match', async () => { - render( + it( 'should detect count mismatch after dynamic changes', async () => { + const { rerender } = render( One @@ -2420,71 +2359,29 @@ describe( 'Tabs', () => { await waitForComponentToBeInitializedWithSelectedTab( 'One' ); - // Wait a bit to ensure validation has run + // Wait for validation await new Promise( ( resolve ) => setTimeout( resolve, 50 ) ); + // No warnings since counts match expect( console ).not.toHaveWarned(); - } ); - it( 'should warn about multiple mismatches', async () => { - render( - - - One - Orphan Tab 1 - Orphan Tab 2 - - First panel - Orphan panel - - ); - - await waitForComponentToBeInitializedWithSelectedTab( 'One' ); - - // Wait for the validation to run - await waitFor( () => { - expect( console ).toHaveWarned(); - } ); - - // Check for tabs without panels warning (both orphan tabs in one message) - expect( console ).toHaveWarnedWith( - 'Tabs: Found Tab(s) without matching Panel(s). Each Tab should have a corresponding Panel with the same `value` prop. Tab value(s) without panels: orphan-tab-1, orphan-tab-2' - ); - - // Check for panels without tabs warning - expect( console ).toHaveWarnedWith( - 'Tabs: Found Panel(s) without matching Tab(s). Each Panel should have a corresponding Tab with the same `value` prop. Panel value(s) without tabs: orphan-panel' - ); - } ); - - // Note: We cannot test duplicate Tab values directly because Base UI's - // internal state management breaks with "Maximum update depth exceeded" - // when duplicate tab values are present. The validation warning for - // duplicate tabs would help developers catch this before the error. - - it( 'should warn when duplicate Panel values are detected', async () => { - render( + // Remove a panel to create a mismatch + rerender( One Two First panel - Second panel - Second panel duplicate ); - await waitForComponentToBeInitializedWithSelectedTab( 'One' ); - - // Wait for the validation to run await waitFor( () => { expect( console ).toHaveWarned(); } ); - // Verify the warning mentions the duplicate panel value expect( console ).toHaveWarnedWith( - 'Tabs: Found duplicate Panel value(s). Each Panel should have a unique `value` prop. Duplicate value(s): two' + 'Tabs: Tab/Panel count mismatch. Found 2 Tab(s) and 1 Panel(s). Each Tab should have a corresponding Panel.' ); } ); } ); From 9c5f8e074a8cec2750f194f4d5f3906e720b8778 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Wed, 18 Mar 2026 12:25:28 +0100 Subject: [PATCH 13/15] Format tsconfig --- packages/ui/tsconfig.json | 49 ++++++++++----------------------------- 1 file changed, 12 insertions(+), 37 deletions(-) diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json index 30c04ad70658f5..693ec5775cfc49 100644 --- a/packages/ui/tsconfig.json +++ b/packages/ui/tsconfig.json @@ -2,45 +2,20 @@ "$schema": "https://json.schemastore.org/tsconfig.json", "extends": "../../tsconfig.base.json", "compilerOptions": { - "types": [ - "node", - "jest" - ] + "types": [ "node", "jest" ] }, "references": [ - { - "path": "../a11y" - }, - { - "path": "../compose" - }, - { - "path": "../element" - }, - { - "path": "../i18n" - }, - { - "path": "../icons" - }, - { - "path": "../keycodes" - }, - { - "path": "../primitives" - }, - { - "path": "../private-apis" - }, - { - "path": "../theme" - }, - { - "path": "../warning" - } - ], - "files": [ - "global.d.ts" + { "path": "../a11y" }, + { "path": "../compose" }, + { "path": "../element" }, + { "path": "../i18n" }, + { "path": "../icons" }, + { "path": "../keycodes" }, + { "path": "../primitives" }, + { "path": "../private-apis" }, + { "path": "../theme" }, + { "path": "../warning" } ], + "files": [ "global.d.ts" ], "exclude": [] } From f58032db3299f22723827dcaac436b445c88b64d Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Thu, 19 Mar 2026 10:28:28 +0100 Subject: [PATCH 14/15] Warning => throw, update error message --- packages/ui/global.d.ts | 1 - packages/ui/package.json | 2 - packages/ui/src/tabs/context.tsx | 9 +-- packages/ui/src/tabs/test/index.test.tsx | 71 +++++++++++++++++------- 4 files changed, 57 insertions(+), 26 deletions(-) diff --git a/packages/ui/global.d.ts b/packages/ui/global.d.ts index 707804b8732422..07d96c55dc3554 100644 --- a/packages/ui/global.d.ts +++ b/packages/ui/global.d.ts @@ -3,4 +3,3 @@ // To ensure that global types are included, we need to // explicitly reference them here. import '@testing-library/jest-dom'; -import '@wordpress/jest-console'; diff --git a/packages/ui/package.json b/packages/ui/package.json index 3a5a2f24bb5365..92164b9690f824 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -53,7 +53,6 @@ "@wordpress/primitives": "file:../primitives", "@wordpress/private-apis": "file:../private-apis", "@wordpress/theme": "file:../theme", - "@wordpress/warning": "file:../warning", "clsx": "^2.1.1" }, "devDependencies": { @@ -62,7 +61,6 @@ "@testing-library/jest-dom": "^6.9.1", "@types/jest": "^29.5.14", "@types/node": "^20.17.10", - "@wordpress/jest-console": "file:../jest-console", "storybook": "^10.2.8" }, "peerDependencies": { diff --git a/packages/ui/src/tabs/context.tsx b/packages/ui/src/tabs/context.tsx index 5a56ba3da64fe3..99b6e201b37ca6 100644 --- a/packages/ui/src/tabs/context.tsx +++ b/packages/ui/src/tabs/context.tsx @@ -6,7 +6,6 @@ import { useRef, useEffect, } from '@wordpress/element'; -import warning from '@wordpress/warning'; type TabsValidationContextType = { registerTab: () => () => void; @@ -94,9 +93,11 @@ function TabsValidationProviderDev( { const panelCount = panelCountRef.current; if ( tabCount !== panelCount ) { - warning( - `Tabs: Tab/Panel count mismatch. Found ${ tabCount } Tab(s) and ${ panelCount } Panel(s). ` + - `Each Tab should have a corresponding Panel.` + throw new Error( + `Tabs: Tab/Panel count mismatch (${ tabCount } Tabs, ${ panelCount } Panels). ` + + `Each Tab must be associated with exactly one Panel. ` + + `Mismatched or missing associations can break screen reader navigation ` + + `and violate WAI-ARIA Tabs pattern requirements.` ); } diff --git a/packages/ui/src/tabs/test/index.test.tsx b/packages/ui/src/tabs/test/index.test.tsx index ae578b622f1b51..0281f3ac14b7eb 100644 --- a/packages/ui/src/tabs/test/index.test.tsx +++ b/packages/ui/src/tabs/test/index.test.tsx @@ -2258,7 +2258,22 @@ describe( 'Tabs', () => { } ); describe( 'Development mode validation', () => { - it( 'should warn when there are more Tabs than Panels', async () => { + function collectUncaughtErrors() { + const errors: Error[] = []; + const handler = ( event: ErrorEvent ) => { + event.preventDefault(); + errors.push( event.error ); + }; + window.addEventListener( 'error', handler ); + return { + errors, + cleanup: () => window.removeEventListener( 'error', handler ), + }; + } + + it( 'should throw when there are more Tabs than Panels', async () => { + const { errors, cleanup } = collectUncaughtErrors(); + render( @@ -2274,15 +2289,19 @@ describe( 'Tabs', () => { await waitForComponentToBeInitializedWithSelectedTab( 'One' ); await waitFor( () => { - expect( console ).toHaveWarned(); + expect( errors.length ).toBeGreaterThan( 0 ); } ); - expect( console ).toHaveWarnedWith( - 'Tabs: Tab/Panel count mismatch. Found 3 Tab(s) and 2 Panel(s). Each Tab should have a corresponding Panel.' + expect( errors[ 0 ].message ).toBe( + 'Tabs: Tab/Panel count mismatch (3 Tabs, 2 Panels). Each Tab must be associated with exactly one Panel. Mismatched or missing associations can break screen reader navigation and violate WAI-ARIA Tabs pattern requirements.' ); + + cleanup(); } ); - it( 'should warn when there are more Panels than Tabs', async () => { + it( 'should throw when there are more Panels than Tabs', async () => { + const { errors, cleanup } = collectUncaughtErrors(); + render( @@ -2298,15 +2317,19 @@ describe( 'Tabs', () => { await waitForComponentToBeInitializedWithSelectedTab( 'One' ); await waitFor( () => { - expect( console ).toHaveWarned(); + expect( errors.length ).toBeGreaterThan( 0 ); } ); - expect( console ).toHaveWarnedWith( - 'Tabs: Tab/Panel count mismatch. Found 2 Tab(s) and 3 Panel(s). Each Tab should have a corresponding Panel.' + expect( errors[ 0 ].message ).toBe( + 'Tabs: Tab/Panel count mismatch (2 Tabs, 3 Panels). Each Tab must be associated with exactly one Panel. Mismatched or missing associations can break screen reader navigation and violate WAI-ARIA Tabs pattern requirements.' ); + + cleanup(); } ); - it( 'should not warn when Tab and Panel counts match', async () => { + it( 'should not throw when Tab and Panel counts match', async () => { + const { errors, cleanup } = collectUncaughtErrors(); + render( @@ -2323,10 +2346,14 @@ describe( 'Tabs', () => { // Wait a bit to ensure validation has run await new Promise( ( resolve ) => setTimeout( resolve, 50 ) ); - expect( console ).not.toHaveWarned(); + expect( errors ).toHaveLength( 0 ); + + cleanup(); } ); - it( 'should warn when tabs are used without any panels', async () => { + it( 'should throw when tabs are used without any panels', async () => { + const { errors, cleanup } = collectUncaughtErrors(); + render( @@ -2337,15 +2364,19 @@ describe( 'Tabs', () => { ); await waitFor( () => { - expect( console ).toHaveWarned(); + expect( errors.length ).toBeGreaterThan( 0 ); } ); - expect( console ).toHaveWarnedWith( - 'Tabs: Tab/Panel count mismatch. Found 2 Tab(s) and 0 Panel(s). Each Tab should have a corresponding Panel.' + expect( errors[ 0 ].message ).toBe( + 'Tabs: Tab/Panel count mismatch (2 Tabs, 0 Panels). Each Tab must be associated with exactly one Panel. Mismatched or missing associations can break screen reader navigation and violate WAI-ARIA Tabs pattern requirements.' ); + + cleanup(); } ); it( 'should detect count mismatch after dynamic changes', async () => { + const { errors, cleanup } = collectUncaughtErrors(); + const { rerender } = render( @@ -2362,8 +2393,8 @@ describe( 'Tabs', () => { // Wait for validation await new Promise( ( resolve ) => setTimeout( resolve, 50 ) ); - // No warnings since counts match - expect( console ).not.toHaveWarned(); + // No errors since counts match + expect( errors ).toHaveLength( 0 ); // Remove a panel to create a mismatch rerender( @@ -2377,12 +2408,14 @@ describe( 'Tabs', () => { ); await waitFor( () => { - expect( console ).toHaveWarned(); + expect( errors.length ).toBeGreaterThan( 0 ); } ); - expect( console ).toHaveWarnedWith( - 'Tabs: Tab/Panel count mismatch. Found 2 Tab(s) and 1 Panel(s). Each Tab should have a corresponding Panel.' + expect( errors[ 0 ].message ).toBe( + 'Tabs: Tab/Panel count mismatch (2 Tabs, 1 Panels). Each Tab must be associated with exactly one Panel. Mismatched or missing associations can break screen reader navigation and violate WAI-ARIA Tabs pattern requirements.' ); + + cleanup(); } ); } ); } ); From fc7b1ba42e8d11c2b3c351ae573f215ad12373e2 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Thu, 19 Mar 2026 10:33:36 +0100 Subject: [PATCH 15/15] Undo changes to package-lock and tsconfig --- package-lock.json | 2 -- packages/ui/tsconfig.json | 3 +-- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index ac62042ef98524..adc99623078299 100644 --- a/package-lock.json +++ b/package-lock.json @@ -62675,7 +62675,6 @@ "@wordpress/primitives": "file:../primitives", "@wordpress/private-apis": "file:../private-apis", "@wordpress/theme": "file:../theme", - "@wordpress/warning": "file:../warning", "clsx": "^2.1.1" }, "devDependencies": { @@ -62684,7 +62683,6 @@ "@testing-library/jest-dom": "^6.9.1", "@types/jest": "^29.5.14", "@types/node": "^20.17.10", - "@wordpress/jest-console": "file:../jest-console", "storybook": "^10.2.8" }, "engines": { diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json index 693ec5775cfc49..81f7e58d2d1619 100644 --- a/packages/ui/tsconfig.json +++ b/packages/ui/tsconfig.json @@ -13,8 +13,7 @@ { "path": "../keycodes" }, { "path": "../primitives" }, { "path": "../private-apis" }, - { "path": "../theme" }, - { "path": "../warning" } + { "path": "../theme" } ], "files": [ "global.d.ts" ], "exclude": []