Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ interface UseCompositeListItemReturnValue {
index: number;
}

export enum IndexGuessBehavior {
None,
GuessFromOrder,
}
const GUESS_FROM_ORDER = 1;

export const IndexGuessBehavior = {
None: 0,
GuessFromOrder: GUESS_FROM_ORDER,
} as const;
export type IndexGuessBehavior = (typeof IndexGuessBehavior)[keyof typeof IndexGuessBehavior];

/**
* Used to register a list item and its index (DOM position) in the `CompositeList`.
Expand All @@ -38,7 +41,7 @@ export function useCompositeListItem<Metadata>(
const indexRef = React.useRef(-1);
const [index, setIndex] = React.useState<number>(
externalIndex ??
(indexGuessBehavior === IndexGuessBehavior.GuessFromOrder
(indexGuessBehavior === GUESS_FROM_ORDER
? () => {
if (indexRef.current === -1) {
const newIndex = nextIndexRef.current;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export function useCompositeRoot(params: UseCompositeRootParameters) {
onHighlightedIndexChange: externalSetHighlightedIndex,
rootRef: externalRef,
enableHomeAndEndKeys = false,
stopEventPropagation = false,
stopEventPropagation,
disabledIndices,
modifierKeys = EMPTY_ARRAY,
} = params;
Expand Down Expand Up @@ -215,7 +215,7 @@ export function useCompositeRoot(params: UseCompositeRootParameters) {
if (target != null && isNativeInput(target) && !isElementDisabled(target)) {
const selectionStart = target.selectionStart;
const selectionEnd = target.selectionEnd;
const textContent = target.value ?? '';
const textContent = target.value;
// return to native textbox behavior when
// 1 - Shift is held to make a text selection, or if there already is a text selection
if (selectionStart == null || event.shiftKey || selectionStart !== selectionEnd) {
Expand Down Expand Up @@ -326,7 +326,7 @@ export function useCompositeRoot(params: UseCompositeRootParameters) {
if (!element || target == null || !isNativeInput(target)) {
return;
}
target.setSelectionRange(0, target.value.length ?? 0);
target.setSelectionRange(0, target.value.length);
},
onKeyDown,
};
Expand All @@ -336,14 +336,13 @@ export function useCompositeRoot(params: UseCompositeRootParameters) {
highlightedIndex,
onHighlightedIndexChange,
elementsRef,
disabledIndices,
onMapChange,
relayKeyboardEvent: onKeyDown,
};
}

function isModifierKeySet(event: React.KeyboardEvent, ignoredModifierKeys: ModifierKey[]) {
for (const key of MODIFIER_KEYS.values()) {
for (const key of MODIFIER_KEYS) {
if (ignoredModifierKeys.includes(key)) {
continue;
}
Expand Down
62 changes: 62 additions & 0 deletions packages/react/src/tabs/enumSync.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import * as React from 'react';
import { expect } from 'vitest';
import { Tabs } from '@base-ui/react/tabs';
import { screen } from '@mui/internal-test-utils';
import { createRenderer } from '#test-utils';
import { tabsStateAttributesMapping } from './root/stateAttributesMapping';
import { TabsRootDataAttributes } from './root/TabsRootDataAttributes';
import { TabsPanelDataAttributes } from './panel/TabsPanelDataAttributes';
import { TabsIndicatorCssVars } from './indicator/TabsIndicatorCssVars';

// The parts inline these enums' values instead of referencing the members, so
// nothing links the docs enums to runtime behavior. These tests re-link every
// inlined member so a rename to only one side fails CI. Test-only imports ship no
// production bytes.
describe('Tabs enum sync', () => {
const { render } = createRenderer();

it('names the activation-direction attribute per TabsRootDataAttributes', () => {
const emitted = tabsStateAttributesMapping.tabActivationDirection!('none');
expect(Object.keys(emitted!)[0]).toBe(TabsRootDataAttributes.activationDirection);
});

it('names the panel index attribute per TabsPanelDataAttributes', async () => {
await render(
<Tabs.Root defaultValue={0}>
<Tabs.List>
<Tabs.Tab value={0} />
</Tabs.List>
<Tabs.Panel value={0} data-testid="panel" />
</Tabs.Root>,
);

expect(screen.getByTestId('panel')).toHaveAttribute(TabsPanelDataAttributes.index);
});

it('names the indicator CSS variables per TabsIndicatorCssVars', async () => {
await render(
<Tabs.Root defaultValue={0}>
<Tabs.List>
<Tabs.Tab value={0} />
<Tabs.Indicator data-testid="indicator" />
</Tabs.List>
</Tabs.Root>,
);

// The indicator writes every variable through the `style` prop whenever a tab
// is selected, so the inline style carries them even without layout measurement.
const indicator = screen.getByTestId('indicator');
const vars = [
TabsIndicatorCssVars.activeTabLeft,
TabsIndicatorCssVars.activeTabRight,
TabsIndicatorCssVars.activeTabTop,
TabsIndicatorCssVars.activeTabBottom,
TabsIndicatorCssVars.activeTabWidth,
TabsIndicatorCssVars.activeTabHeight,
] as const;

for (const cssVar of vars) {
expect(indicator.style.getPropertyValue(cssVar)).not.toBe('');
}
});
});
16 changes: 7 additions & 9 deletions packages/react/src/tabs/indicator/TabsIndicator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { useTabsRootContext } from '../root/TabsRootContext';
import { tabsStateAttributesMapping } from '../root/stateAttributesMapping';
import { useTabsListContext } from '../list/TabsListContext';
import type { TabsTab } from '../tab/TabsTab';
import { TabsIndicatorCssVars } from './TabsIndicatorCssVars';

const stateAttributesMapping = {
...tabsStateAttributesMapping,
Expand Down Expand Up @@ -69,8 +68,7 @@ export const TabsIndicator = React.forwardRef(function TabsIndicator(
const tabsListRect = tabsListElement.getBoundingClientRect();
const scaleX = tabListWidth > 0 ? tabsListRect.width / tabListWidth : 1;
const scaleY = tabListHeight > 0 ? tabsListRect.height / tabListHeight : 1;
const hasNonZeroScale =
Math.abs(scaleX) > Number.EPSILON && Math.abs(scaleY) > Number.EPSILON;
const hasNonZeroScale = scaleX > Number.EPSILON && scaleY > Number.EPSILON;

if (hasNonZeroScale) {
const tabLeftDelta = tabRect.left - tabsListRect.left;
Expand All @@ -96,12 +94,12 @@ export const TabsIndicator = React.forwardRef(function TabsIndicator(

const style: React.CSSProperties | undefined = isTabSelected
? ({
[TabsIndicatorCssVars.activeTabLeft]: `${left}px`,
[TabsIndicatorCssVars.activeTabRight]: `${right}px`,
[TabsIndicatorCssVars.activeTabTop]: `${top}px`,
[TabsIndicatorCssVars.activeTabBottom]: `${bottom}px`,
[TabsIndicatorCssVars.activeTabWidth]: `${width}px`,
[TabsIndicatorCssVars.activeTabHeight]: `${height}px`,
'--active-tab-left': `${left}px`,
'--active-tab-right': `${right}px`,
'--active-tab-top': `${top}px`,
'--active-tab-bottom': `${bottom}px`,
'--active-tab-width': `${width}px`,
'--active-tab-height': `${height}px`,
} as React.CSSProperties)
: undefined;

Expand Down
20 changes: 2 additions & 18 deletions packages/react/src/tabs/list/TabsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import { useStableCallback } from '@base-ui/utils/useStableCallback';
import { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';
import { EMPTY_ARRAY } from '@base-ui/utils/empty';
import { BaseUIComponentProps, HTMLProps } from '../../internals/types';
import type { TabsRoot, TabsRootState } from '../root/TabsRoot';
import type { TabsRootState } from '../root/TabsRoot';
import { CompositeRoot } from '../../internals/composite/root/CompositeRoot';
import { tabsStateAttributesMapping } from '../root/stateAttributesMapping';
import { useTabsRootContext } from '../root/TabsRootContext';
import type { TabsTab } from '../tab/TabsTab';
import { TabsListContext } from './TabsListContext';

/**
Expand All @@ -30,8 +29,7 @@ export const TabsList = React.forwardRef(function TabsList(
...elementProps
} = componentProps;

const { onValueChange, orientation, value, setTabMap, tabActivationDirection } =
useTabsRootContext();
const { orientation, setTabMap, tabActivationDirection } = useTabsRootContext();

const [highlightedTabIndex, setHighlightedTabIndex] = React.useState(0);
const [tabsListElement, setTabsListElement] = React.useState<HTMLElement | null>(null);
Expand Down Expand Up @@ -83,14 +81,6 @@ export const TabsList = React.forwardRef(function TabsList(
};
});

const onTabActivation = useStableCallback(
(newValue: TabsTab.Value, eventDetails: TabsRoot.ChangeEventDetails) => {
if (newValue !== value) {
onValueChange(newValue, eventDetails);
}
},
);

const state: TabsListState = {
orientation,
tabActivationDirection,
Expand All @@ -104,20 +94,14 @@ export const TabsList = React.forwardRef(function TabsList(
const tabsListContextValue: TabsListContext = React.useMemo(
() => ({
activateOnFocus,
highlightedTabIndex,
registerIndicatorUpdateListener,
registerTabResizeObserverElement,
onTabActivation,
setHighlightedTabIndex,
tabsListElement,
}),
[
activateOnFocus,
highlightedTabIndex,
registerIndicatorUpdateListener,
registerTabResizeObserverElement,
onTabActivation,
setHighlightedTabIndex,
tabsListElement,
],
);
Expand Down
5 changes: 0 additions & 5 deletions packages/react/src/tabs/list/TabsListContext.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
'use client';
import * as React from 'react';
import type { TabsRoot } from '../root/TabsRoot';
import type { TabsTab } from '../tab/TabsTab';

export interface TabsListContext {
activateOnFocus: boolean;
highlightedTabIndex: number;
registerIndicatorUpdateListener: (listener: () => void) => () => void;
registerTabResizeObserverElement: (element: HTMLElement) => () => void;
onTabActivation: (newValue: TabsTab.Value, eventDetails: TabsRoot.ChangeEventDetails) => void;
setHighlightedTabIndex: (index: number) => void;
tabsListElement: HTMLElement | null;
}

Expand Down
24 changes: 5 additions & 19 deletions packages/react/src/tabs/panel/TabsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { tabsStateAttributesMapping } from '../root/stateAttributesMapping';
import { useTabsRootContext } from '../root/TabsRootContext';
import type { TabsRootState } from '../root/TabsRoot';
import type { TabsTab } from '../tab/TabsTab';
import { TabsPanelDataAttributes } from './TabsPanelDataAttributes';

const stateAttributesMapping: StateAttributesMapping<TabsPanelState> = {
...tabsStateAttributesMapping,
Expand All @@ -39,22 +38,11 @@ export const TabsPanel = React.forwardRef(function TabsPanel(
orientation,
tabActivationDirection,
registerMountedTabPanel,
unregisterMountedTabPanel,
} = useTabsRootContext();

const id = useBaseUiId();

const metadata = React.useMemo(
() => ({
id,
value,
}),
[id, value],
);

const { ref: listItemRef, index } = useCompositeListItem<TabsPanel.Metadata>({
metadata,
});
const { ref: listItemRef, index } = useCompositeListItem();

const open = value === selectedValue;
const { mounted, transitionStatus, setMounted } = useTransitionStatus(open);
Expand Down Expand Up @@ -82,7 +70,8 @@ export const TabsPanel = React.forwardRef(function TabsPanel(
role: 'tabpanel',
tabIndex: open ? 0 : -1,
inert: inertValue(!open),
[TabsPanelDataAttributes.index as string]: index,
// Computed key: a plain literal key fails the DOM-props excess property check.
['data-index' as string]: index,
},
elementProps,
],
Expand All @@ -108,11 +97,8 @@ export const TabsPanel = React.forwardRef(function TabsPanel(
return undefined;
}

registerMountedTabPanel(value, id);
return () => {
unregisterMountedTabPanel(value, id);
};
}, [hidden, keepMounted, value, id, registerMountedTabPanel, unregisterMountedTabPanel]);
return registerMountedTabPanel(value, id);
}, [hidden, keepMounted, value, id, registerMountedTabPanel]);

const shouldRender = keepMounted || mounted;
if (!shouldRender) {
Expand Down
Loading
Loading