Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(lab): a TabBar tab can be disabled (#10539)

Christopher Chedeau6c5e2e6652dc
diff --git a/apps/storybook/stories/TabBar.stories.tsx b/apps/storybook/stories/TabBar.stories.tsx
index b9ee247e57..8c631685bd 100644
--- a/apps/storybook/stories/TabBar.stories.tsx
+++ b/apps/storybook/stories/TabBar.stories.tsx
@@ -109,6 +109,7 @@ function Bar({
initial = 'home',
badges = {library: 3},
keeps = [],
+ disabled = [],
onChange,
}: {
sections?: Section[];
@@ -116,6 +117,8 @@ function Bar({
badges?: Record<string, string | number>;
/** Tabs the app declines to switch to (it keeps the selection). */
keeps?: string[];
+ /** Tabs the app has disabled. */
+ disabled?: string[];
/** Also told of every choice. */
onChange?: (value: string) => void;
}) {
@@ -144,6 +147,7 @@ function Bar({
icon={<Icon icon={section.icon} size="lg" />}
selectedIcon={<Icon icon={section.selectedIcon} size="lg" />}
badge={badges[section.value]}
+ aria-disabled={disabled.includes(section.value) || undefined}
/>
))}
</TabBar>
@@ -281,6 +285,16 @@ export const FiveTabs: Story = {
),
};
+/** Browse is disabled: dimmed, skipped by the arrow keys, and never chosen. */
+export const DisabledTab: Story = {
+ render: () => <Bar disabled={['browse']} />,
+};
+
+/** No tab selected, Browse disabled: a held finger paints only enabled tabs. */
+export const DisabledTabNoSelection: Story = {
+ render: () => <Bar initial="none" disabled={['browse']} />,
+};
+
/** Three tabs: the capsule narrows to its natural width and centres. */
export const ThreeTabs: Story = {
render: () => <Bar sections={SECTIONS.slice(0, 3)} />,
diff --git a/packages/lab/src/TabBar/TabBar.doc.mjs b/packages/lab/src/TabBar/TabBar.doc.mjs
index 4d62a7129b..33178ed4af 100644
--- a/packages/lab/src/TabBar/TabBar.doc.mjs
+++ b/packages/lab/src/TabBar/TabBar.doc.mjs
@@ -110,6 +110,12 @@ export const docs = {
description:
"Id of the panel this tab controls, wired up as aria-controls. Put the same id on the section's panel element.",
},
+ {
+ name: 'aria-disabled',
+ type: "boolean | 'true' | 'false'",
+ description:
+ "Disables the tab, as on Core's Tab: it stays focusable but dimmed and is never chosen. A tap, a click or a key on it, or a lift over it, selects nothing, and the arrow keys skip it. A finger that lands on it lifts no lens until it drags or reaches an enabled tab, which the lift then chooses. This differs from iOS on purpose. iOS ignores a touch that starts on a disabled tab, but TabBar follows the action-group rule: the tab you lift on acts.",
+ },
],
},
],
@@ -132,6 +138,11 @@ export const docs = {
description:
"Give each tab a panelId naming its section's panel, so assistive technology can associate the two.",
},
+ {
+ guidance: true,
+ description:
+ 'Disable a tab only while its section cannot open, and keep it in place, so the other tabs do not move.',
+ },
{
guidance: false,
description:
diff --git a/packages/lab/src/TabBar/TabBar.test.tsx b/packages/lab/src/TabBar/TabBar.test.tsx
index 9beaf3fbc6..b622d25331 100644
--- a/packages/lab/src/TabBar/TabBar.test.tsx
+++ b/packages/lab/src/TabBar/TabBar.test.tsx
@@ -338,3 +338,56 @@ describe('TabBar', () => {
expect(screen.queryByText('stray')).toBeNull();
});
});
+
+describe('TabBar disabled tab', () => {
+ function Disabled({onChange}: {onChange?: (value: string) => void}) {
+ const [value, setValue] = useState('home');
+ return (
+ <TabBar
+ value={value}
+ onChange={next => {
+ setValue(next);
+ onChange?.(next);
+ }}
+ label="Sections">
+ <TabBarItem value="home" label="Home" icon={<Glyph name="home" />} />
+ <TabBarItem
+ value="browse"
+ label="Browse"
+ icon={<Glyph name="browse" />}
+ aria-disabled
+ />
+ <TabBarItem
+ value="profile"
+ label="Profile"
+ icon={<Glyph name="profile" />}
+ />
+ </TabBar>
+ );
+ }
+
+ it('is marked disabled and ignores a click', () => {
+ const onChange = vi.fn();
+ render(<Disabled onChange={onChange} />);
+ const browse = screen.getByRole('tab', {name: 'Browse'});
+ expect(browse).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(browse);
+ expect(onChange).not.toHaveBeenCalled();
+ expect(browse).toHaveAttribute('aria-selected', 'false');
+ });
+
+ it('is skipped by the arrow keys', () => {
+ render(<Disabled />);
+ const home = screen.getByRole('tab', {name: 'Home'});
+ home.focus();
+ fireEvent.keyDown(home, {key: 'ArrowRight'});
+ expect(screen.getByRole('tab', {name: 'Profile'})).toHaveFocus();
+ });
+
+ it('keeps the other tabs choosable', () => {
+ const onChange = vi.fn();
+ render(<Disabled onChange={onChange} />);
+ fireEvent.click(screen.getByRole('tab', {name: 'Profile'}));
+ expect(onChange).toHaveBeenCalledWith('profile');
+ });
+});
diff --git a/packages/lab/src/TabBar/TabBar.tsx b/packages/lab/src/TabBar/TabBar.tsx
index 7cf176c50b..59214c9900 100644
--- a/packages/lab/src/TabBar/TabBar.tsx
+++ b/packages/lab/src/TabBar/TabBar.tsx
@@ -73,6 +73,12 @@ export interface TabBarItemProps {
* same id on the panel element.
*/
panelId?: string;
+ /**
+ * Disables the tab, as on Core's Tab: it stays focusable, dimmed, and is
+ * never chosen. A tap, a click or a key on it, or a lift over it, selects
+ * nothing, and the arrow keys skip it.
+ */
+ 'aria-disabled'?: boolean | 'true' | 'false';
}
export interface TabBarProps extends Omit<
@@ -120,6 +126,11 @@ function readItems(children: ReactNode): TabBarItemProps[] {
);
}
+function isDisabledItem(item: TabBarItemProps | undefined): boolean {
+ const disabled = item?.['aria-disabled'];
+ return disabled === true || disabled === 'true';
+}
+
function hasBadge(badge: string | number | undefined): boolean {
return badge != null && badge !== '';
}
@@ -398,6 +409,9 @@ const styles = stylex.create({
itemSelectedLook: {
color: colorVars['--color-accent'],
},
+ itemDisabled: {
+ color: colorVars['--color-text-disabled'],
+ },
badges: {
position: 'absolute',
inset: 0,
@@ -544,6 +558,9 @@ export function TabBar({
});
const choose = useCallback(
(item: TabBarItemProps) => {
+ if (isDisabledItem(item)) {
+ return;
+ }
if (item.value === value) {
onReselect?.(item.value);
} else {
@@ -558,6 +575,7 @@ export function TabBar({
selectedIndex,
isTouch,
onLift: index => choose(items[index]),
+ isDisabled: index => isDisabledItem(items[index]),
});
const mergedCapsuleRef = useMergedRefs(capsuleRef, listRef, lens.capsule);
@@ -593,6 +611,7 @@ export function TabBar({
)}>
{items.map((item, index) => {
const isSelected = index === selectedIndex;
+ const isDisabled = isDisabledItem(item);
const {start, width, itemStart} = column(index, count);
return (
<button
@@ -601,6 +620,7 @@ export function TabBar({
role="tab"
id={`${baseId}-tab-${index}`}
aria-selected={isSelected}
+ aria-disabled={isDisabled || undefined}
aria-controls={item.panelId}
tabIndex={
isSelected || (selectedIndex < 0 && index === 0) ? 0 : -1
@@ -632,11 +652,14 @@ export function TabBar({
// At rest the tab draws its selected look; while the lens
// slides, the copy inside it does.
isSelected && !lens.isCopyShown && styles.itemSelectedLook,
+ isDisabled && styles.itemDisabled,
styles.box(itemStart, ITEM_TOP, itemSize, ITEM_HEIGHT),
)}>
<ItemFace
item={item}
- isSelectedLook={isSelected && !lens.isCopyShown}
+ isSelectedLook={
+ isSelected && !isDisabled && !lens.isCopyShown
+ }
/>
</span>
</button>
@@ -687,8 +710,13 @@ export function TabBar({
itemSize,
ITEM_HEIGHT,
),
+ isDisabledItem(item) && styles.itemDisabled,
)}>
- <ItemFace item={item} isSelectedLook isCopy />
+ <ItemFace
+ item={item}
+ isSelectedLook={!isDisabledItem(item)}
+ isCopy
+ />
</span>
))}
</div>
diff --git a/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts b/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts
index 777672633b..4862bd44ae 100644
--- a/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts
+++ b/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts
@@ -1607,6 +1607,261 @@ test('at rest the selected tab draws its own look; the copy of the items rides i
expect(await labelWeight(page, 'Home')).not.toBe('600');
});
+test('a disabled tab is announced disabled on the tab itself, with its name, in the accessibility tree (spec:AST-085 FR5)', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(browserName !== 'chromium', 'reads Chromium’s accessibility tree');
+ await openBar(page, 'disabled-tab');
+ const cdp = await page.context().newCDPSession(page);
+ const {nodes} = await cdp.send('Accessibility.getFullAXTree');
+ const tabs = nodes
+ .filter(node => node.ignored !== true && node.role?.value === 'tab')
+ .map(node => ({
+ name: node.name?.value,
+ disabled:
+ node.properties?.some(
+ property =>
+ property.name === 'disabled' && property.value.value === true,
+ ) ?? false,
+ }));
+ expect(tabs).toContainEqual({name: 'Browse', disabled: true});
+ expect(tabs.filter(entry => entry.disabled)).toHaveLength(1);
+});
+
+test('a finger landing on a disabled tab moves and lifts nothing (UIKit ignores the tap)', async ({
+ page,
+}) => {
+ const {driver} = await openFreezableBar(page, 'disabled-tab');
+ const home = await itemCenter(page, 'Home');
+ const browse = await itemCenter(page, 'Browse');
+ const capsule = page.getByRole('tablist');
+ let held: {
+ lens: number;
+ lift: {x: number; y: number};
+ flex: {x: number; y: number};
+ } | null = null;
+ // The scene freezes as the finger lands, then runs 120 ms by its own
+ // clock. A lift would be well under way by then.
+ await freezePageOn(page, 'touchstart');
+ await driver.play(tapScript(browse, {holdMs: 200}), {
+ onEvent: async (_step, index) => {
+ if (index !== 0) {
+ return;
+ }
+ await advanceFrozenPage(page, 120);
+ held = {
+ lens: await lensCenterX(page),
+ lift: await scaleOf(lensBody(page)),
+ flex: await scaleOf(capsule),
+ };
+ await thawPage(page);
+ },
+ });
+ const atHold = held as {
+ lens: number;
+ lift: {x: number; y: number};
+ flex: {x: number; y: number};
+ } | null;
+ expect(atHold).not.toBeNull();
+ expect(atHold?.lift).toEqual({x: 1, y: 1});
+ expect(atHold?.flex).toEqual({x: 1, y: 1});
+ expect(Math.abs((atHold?.lens ?? Infinity) - home.x)).toBeLessThan(0.5);
+ await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true');
+});
+
+test('a lift over a disabled tab leaves the selection, and the lens settles back', async ({
+ page,
+}) => {
+ const {driver} = await openBar(page, 'disabled-tab');
+ const home = await itemCenter(page, 'Home');
+ const browse = await itemCenter(page, 'Browse');
+ await driver.play(drag(home, browse, {durationMs: 400, restMs: 200}));
+ await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true');
+ await expect(tab(page, 'Browse')).toHaveAttribute('aria-disabled', 'true');
+ await expect
+ .poll(async () => Math.abs((await lensCenterX(page)) - home.x), {
+ timeout: 3000,
+ })
+ .toBeLessThan(0.5);
+});
+
+test('a drag from a disabled tab lifts the lens once it drags, and the lift chooses the tab under the finger', async ({
+ page,
+}) => {
+ const {driver} = await openBar(page, 'disabled-tab');
+ const browse = await itemCenter(page, 'Browse');
+ const profile = await itemCenter(page, 'Profile');
+ let lifted: {x: number; y: number} | null = null;
+ const script = drag(browse, profile, {durationMs: 500, restMs: 300});
+ await driver.play(script, {
+ onEvent: async (_step, index) => {
+ // The finger rests over Profile before it lifts.
+ if (index === script.length - 2) {
+ lifted = await scaleOf(lensBody(page));
+ }
+ },
+ });
+ const atRest = lifted as {x: number; y: number} | null;
+ expect(atRest?.x ?? 1).toBeGreaterThan(1);
+ await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'true');
+});
+
+test('a finger that lands on a disabled tab and lifts within the slop over a neighbour chooses the neighbour, painted while held (family:action-groups FR1)', async ({
+ page,
+}) => {
+ const {driver} = await openBar(page, 'disabled-tab-no-selection');
+ const browse = await itemCenter(page, 'Browse');
+ const box = await tab(page, 'Browse').boundingBox();
+ if (box == null) {
+ throw new Error('no Browse tab');
+ }
+ // 3 px inside Browse on Library's side, then 7 px onto Library: under the
+ // 10 px slop.
+ const from = {x: box.x + 3, y: browse.y};
+ const to = {x: from.x - 7, y: browse.y};
+ let painted: string[] | null = null;
+ const script = drag(from, to, {durationMs: 200, restMs: 200});
+ await driver.play(script, {
+ onEvent: async (_step, index) => {
+ if (index === script.length - 2) {
+ painted = await page
+ .locator('[data-tab-bar-pressed]')
+ .evaluateAll(tabs => tabs.map(tab => tab.textContent ?? ''));
+ }
+ },
+ });
+ expect(painted).toEqual(['Library']);
+ await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true');
+});
+
+test('a finger that lands on a disabled tab and lifts within the slop over a neighbour chooses the neighbour, the lens lifted over it while held (family:action-groups FR1, FR2)', async ({
+ page,
+}) => {
+ const {driver} = await openBar(page, 'disabled-tab');
+ const browse = await itemCenter(page, 'Browse');
+ const library = await itemCenter(page, 'Library');
+ const box = await tab(page, 'Browse').boundingBox();
+ if (box == null) {
+ throw new Error('no Browse tab');
+ }
+ const home = await itemCenter(page, 'Home');
+ const from = {x: box.x + 3, y: browse.y};
+ const to = {x: from.x - 7, y: browse.y};
+ // While the finger rests on Library, the lens is lifted and has left Home.
+ let held: {lift: {x: number; y: number}; lens: number} | null = null;
+ const script = drag(from, to, {durationMs: 200, restMs: 200});
+ await driver.play(script, {
+ onEvent: async (_step, index) => {
+ if (index === script.length - 2) {
+ held = {
+ lift: await scaleOf(lensBody(page)),
+ lens: await lensCenterX(page),
+ };
+ }
+ },
+ });
+ const atRest = held as {lift: {x: number; y: number}; lens: number} | null;
+ expect(atRest?.lift.x ?? 1).toBeGreaterThan(1);
+ expect(atRest?.lens ?? home.x).toBeGreaterThan(home.x + 30);
+ await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true');
+ await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'false');
+ await expect
+ .poll(async () => Math.abs((await lensCenterX(page)) - library.x), {
+ timeout: 3000,
+ })
+ .toBeLessThan(0.5);
+});
+
+test('a drag over a disabled tab returns the lens to the selected tab, since the lift there chooses nothing; the disabled tab keeps its paint (spec:AST-085 FR6)', async ({
+ page,
+}) => {
+ const {driver, bar} = await openBar(page, 'disabled-tab');
+ const home = await itemCenter(page, 'Home');
+ const browse = await itemCenter(page, 'Browse');
+ const box = await bar.boundingBox();
+ if (box == null) {
+ throw new Error('no bar');
+ }
+ // Where an item sits under the press's flex (about the capsule's centre).
+ const center = box.x + box.width / 2;
+ const flexed = (x: number) => center + (x - center) * FLEX_SCALE;
+ // Just short of Browse's centre: over Browse, a disabled tab.
+ const over = {x: browse.x - 5, y: browse.y};
+ // The lens's farthest point on the way, as it chases the finger.
+ let farthest = -Infinity;
+ let held: {
+ lens: number;
+ color: string;
+ weight: string;
+ accent: string;
+ } | null = null;
+ const script = drag(home, over, {durationMs: 500, restMs: 600});
+ await driver.play(script, {
+ onEvent: async (_step, index) => {
+ farthest = Math.max(farthest, await lensCenterX(page));
+ if (index !== script.length - 2) {
+ return;
+ }
+ // The finger holds over Browse until the lens comes to rest.
+ await waitForRest(lensBody(page));
+ const paint = await page.evaluate(() => {
+ const item = document.querySelector(
+ '[data-tab-bar-copy-item="browse"]',
+ );
+ const label = item?.querySelector(':scope > span:last-child');
+ const enabled = document.querySelector(
+ '[data-tab-bar-copy-item="home"]',
+ );
+ return {
+ color: item == null ? '' : getComputedStyle(item).color,
+ weight: label == null ? '' : getComputedStyle(label).fontWeight,
+ accent: enabled == null ? '' : getComputedStyle(enabled).color,
+ };
+ });
+ held = {lens: await lensCenterX(page), ...paint};
+ },
+ });
+ const atHold = held as {
+ lens: number;
+ color: string;
+ weight: string;
+ accent: string;
+ } | null;
+ expect(atHold).not.toBeNull();
+ // On the way the lens chased the finger away from Home.
+ expect(farthest).toBeGreaterThan(flexed(home.x) + 30);
+ // Over Browse it waits on Home, the selected tab: nothing is highlighted
+ // over a disabled tab.
+ expect(Math.abs((atHold?.lens ?? Infinity) - flexed(home.x))).toBeLessThan(
+ 0.5,
+ );
+ // Browse keeps its disabled paint in the lens's copy, not the selected look.
+ expect(atHold?.color).not.toBe('');
+ expect(atHold?.color).not.toBe(atHold?.accent);
+ expect(atHold?.weight).not.toBe('600');
+ // The lift over a disabled tab chooses nothing.
+ await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true');
+});
+
+test('with Reduce Motion the settle back from a disabled tab cross-fades', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {driver} = await openBar(page, 'disabled-tab');
+ const home = await itemCenter(page, 'Home');
+ const browse = await itemCenter(page, 'Browse');
+ await driver.play(drag(home, browse, {durationMs: 400, restMs: 300}));
+ // Since the page's own lift, not a read the test makes after it.
+ const released = await liftedAt(page);
+ expect(released, 'no lift reached the page').toBeGreaterThan(0);
+ // The fade starts with the input; what it changes follows a few frames
+ // later.
+ await expectCrossFade(page, released);
+ await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true');
+ assertOpacityOnly(await runningAnimations(page, released));
+});
+
test.describe('with Reduce Motion (design:reduced-motion)', () => {
test('on a touch screen a tap cross-fades the lens: opacity only, within 200 ms', async ({
page,
@@ -2218,3 +2473,22 @@ test(
expect(Math.max(...frames.map(f => f.flex))).toBeGreaterThan(1.03);
},
);
+
+test.describe('a disabled tab under a mouse', () => {
+ test.use({hasTouch: false, isMobile: false});
+
+ test('a click on a disabled tab chooses nothing, and the arrow keys skip it', async ({
+ page,
+ }) => {
+ await expectFinePointer(page);
+ await openBar(page, 'disabled-tab');
+ const browse = await itemCenter(page, 'Browse');
+ await page.mouse.click(browse.x, browse.y);
+ await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true');
+ await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'false');
+ // From Library the next key stop is Profile.
+ await tab(page, 'Library').focus();
+ await page.keyboard.press('ArrowRight');
+ await expect(tab(page, 'Profile')).toBeFocused();
+ });
+});
diff --git a/packages/lab/src/TabBar/tabBarModel.test.ts b/packages/lab/src/TabBar/tabBarModel.test.ts
index ea577c58af..9e53bfaa14 100644
--- a/packages/lab/src/TabBar/tabBarModel.test.ts
+++ b/packages/lab/src/TabBar/tabBarModel.test.ts
@@ -20,6 +20,7 @@ import {
lensTarget,
liftScale,
naturalWidth,
+ nearestIndex,
} from './tabBarModel';
/**
@@ -111,6 +112,23 @@ describe('itemWidth and itemCenters', () => {
});
});
+describe('nearestIndex: the item nearest a finger', () => {
+ const centers = itemCenters(290, 4);
+
+ it('picks the nearest centre', () => {
+ expect(nearestIndex(centers[2] + 20, centers)).toBe(2);
+ expect(nearestIndex(centers[1] - 30, centers)).toBe(1);
+ });
+
+ it('gives a tie to the leading (earlier) item', () => {
+ const midpoint = (centers[1] + centers[2]) / 2;
+ expect(nearestIndex(midpoint, centers)).toBe(1);
+ // In a right-to-left capsule the earlier item is on the right.
+ const rtl = itemCenters(290, 4, true);
+ expect(nearestIndex((rtl[1] + rtl[2]) / 2, rtl)).toBe(1);
+ });
+});
+
describe('lensTarget', () => {
const centers = itemCenters(290, 4);
diff --git a/packages/lab/src/TabBar/tabBarModel.ts b/packages/lab/src/TabBar/tabBarModel.ts
index 42ceee51ce..a9558e540c 100644
--- a/packages/lab/src/TabBar/tabBarModel.ts
+++ b/packages/lab/src/TabBar/tabBarModel.ts
@@ -3,8 +3,8 @@
/**
* @file tabBarModel.ts
* @input TabBar's UIKit values (uikitTabBar.ts)
- * @output TabBar's pure geometry: the items' widths and centres, and the
- * lens's target and scale.
+ * @output TabBar's pure geometry: the items' widths and centres, the item
+ * nearest a finger, and the lens's target and scale.
* @position Math of the lab TabBar; no DOM, no React. Coordinates are the
* capsule's own, in px, before its flex scale. x runs from its left edge,
* and items go in logical order.
@@ -70,6 +70,29 @@ export function itemCenters(
return isRtl ? centers.map(center => width - center) : centers;
}
+/**
+ * The item nearest a finger at `x`: the one whose centre is nearest, the
+ * earlier one on a tie. TabBar asks it whether a finger landed on a disabled
+ * tab.
+ */
+export function nearestIndex(
+ x: number,
+ centers: ReadonlyArray<number>,
+): number {
+ let best = 0;
+ let bestDistance = Infinity;
+ centers.forEach((center, index) => {
+ const distance = Math.abs(x - center);
+ // Float centres can differ by rounding. A difference under 1e-9 px counts
+ // as a tie.
+ if (distance < bestDistance - 1e-9) {
+ best = index;
+ bestDistance = distance;
+ }
+ });
+ return best;
+}
+
/**
* Where the lens heads for a finger at `x`: the finger itself between the
* first and last centres, rubber-banded past them.
diff --git a/packages/lab/src/TabBar/useTabBarLens.ts b/packages/lab/src/TabBar/useTabBarLens.ts
index 7954425ef0..9272e23a9d 100644
--- a/packages/lab/src/TabBar/useTabBarLens.ts
+++ b/packages/lab/src/TabBar/useTabBarLens.ts
@@ -37,6 +37,7 @@ import {
itemWidth,
lensTarget,
liftScale,
+ nearestIndex,
} from './tabBarModel';
import {useMotionEngine} from '../internal/useMotionEngine';
import {tabBar} from './uikitTabBar';
@@ -62,6 +63,8 @@ interface Press {
isDragging: boolean;
/** A tab was selected when the finger landed: the lens follows it. */
hasLens: boolean;
+ /** It landed on a disabled tab: nothing moves until the finger drags. */
+ isIgnored: boolean;
readonly count: number;
/** No tab was selected when it landed, so no lens shows it: it paints. */
readonly paints: boolean;
@@ -93,6 +96,11 @@ export interface UseTabBarLensOptions {
readonly isTouch: boolean;
/** A press lifted over the item at `index`. */
readonly onLift: (index: number) => void;
+ /**
+ * Whether the item at `index` is disabled. A finger that lands on it moves
+ * nothing until it drags, as UIKit ignores a tap on a disabled tab.
+ */
+ readonly isDisabled?: (index: number) => boolean;
}
export interface TabBarLensRefs {
@@ -159,6 +167,9 @@ function useAnimatorList(count: number) {
* cancelled touch settles back onto the selected item.
* - off the bar: the lens shows the selected item again, and a lift there
* chooses nothing. Sliding off cancels.
+ * - over a disabled tab: the tracker skips it, so the lens shows the selected
+ * item, as off the bar. A finger that lands on one moves nothing until it
+ * drags.
* The choice reaches the app (`onLift`) from the lift itself, right after the
* settle has started in the same task. The settle's first frame waits for the
* browser's commit, so the app rendering the new tab delays its start rather
@@ -187,6 +198,7 @@ export function useTabBarLens({
selectedIndex,
isTouch,
onLift,
+ isDisabled,
}: UseTabBarLensOptions): TabBarLensRefs {
const capsule = useMotionEngine();
const body = useMotionEngine();
@@ -218,6 +230,8 @@ export function useTabBarLens({
selectedRef.current = selectedIndex;
const onLiftRef = useRef(onLift);
onLiftRef.current = onLift;
+ const isDisabledRef = useRef(isDisabled);
+ isDisabledRef.current = isDisabled;
const tabsOf = (capsule: HTMLElement) =>
[...capsule.children].filter(
(child): child is HTMLElement => child.getAttribute('role') === 'tab',
@@ -353,6 +367,10 @@ export function useTabBarLens({
const centers = itemCenters(element.offsetWidth, count, isRtl);
const size = itemWidth(element.offsetWidth, count);
const x = clientX - left;
+ // UIKit ignores a tap on a disabled tab. So a finger that lands on one
+ // moves nothing unless it then drags.
+ const isIgnored =
+ isDisabledRef.current?.(nearestIndex(x, centers)) === true;
pressRef.current = {
centers,
size,
@@ -361,6 +379,7 @@ export function useTabBarLens({
lastX: x,
isDragging: false,
hasLens: selected >= 0,
+ isIgnored,
count,
paints: selected < 0,
painted: null,
@@ -369,7 +388,7 @@ export function useTabBarLens({
paintTab(pressRef.current, tab);
// No tab selected: there is no lens to move; the lift chooses the tab
// nearest the finger.
- if (selected < 0) {
+ if (selected < 0 || isIgnored) {
return;
}
// The lifted lens magnifies the selected look: its copy mounts now, in
@@ -404,6 +423,21 @@ export function useTabBarLens({
const x = clientX - press.left;
press.lastX = x;
press.isDragging ||= Math.abs(x - press.startX) > DRAG_SLOP;
+ if (press.isIgnored) {
+ // The ignore ends once the finger drags or rests on an enabled tab:
+ // the tab under a held finger shows, and the lift chooses it.
+ if (!press.isDragging && tab == null) {
+ return;
+ }
+ press.isIgnored = false;
+ if (press.hasLens && selected >= 0) {
+ motionRef.current += 1;
+ if (body.animator.reducedMotion({}) === 'off') {
+ flushSync(() => setIsCopyShown(true));
+ }
+ lift(true, performance.now(), press.size);
+ }
+ }
if (!press.hasLens || selected < 0) {
return;
}
@@ -442,7 +476,9 @@ export function useTabBarLens({
// The app's answer to this lift, as rendered now: the tab the finger
// chose is the one under it at the lift, whatever renders after.
const deliver = onLiftRef.current;
- if (!press.hasLens || selected < 0) {
+ // A press that landed on a disabled tab moved no lens. The tab it lifts
+ // on, if any, still acts, as for any press.
+ if (press.isIgnored || !press.hasLens || selected < 0) {
// No lens moved: the tab the tracker took runs at once.
if (chosen >= 0) {
liftRef.current = () => flushSync(() => deliver(chosen));