File size: 4,698 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import * as Ariakit from '@ariakit/react';
import { useMergeRefs } from '@wordpress/compose';
import warning from '@wordpress/warning';
import clsx from 'clsx';
import { forwardRef, useLayoutEffect, useState } from 'react';
import { useTrackElementOffsetRect } from '../utils/element-rect';
import { useAnimatedOffsetRect } from '../utils/hooks/use-animated-offset-rect';
import { useTabsContext } from './context';
import styles from './style.module.scss';
import { useTrackOverflow } from './use-track-overflow';
import type { TabListProps } from './types';
import type { ElementOffsetRect } from '../utils/element-rect';

const DEFAULT_SCROLL_MARGIN = 24;

/**
 * Scrolls a given parent element so that a given rect is visible.
 *
 * The scroll is updated initially and whenever the rect changes.
 */
function useScrollRectIntoView(
	parent: HTMLElement | undefined,
	rect: ElementOffsetRect,
	{ margin = DEFAULT_SCROLL_MARGIN } = {}
) {
	useLayoutEffect( () => {
		if ( ! parent || ! rect ) {
			return;
		}

		const { scrollLeft: parentScroll } = parent;
		const parentWidth = parent.getBoundingClientRect().width;
		const { left: childLeft, width: childWidth } = rect;

		const parentRightEdge = parentScroll + parentWidth;
		const childRightEdge = childLeft + childWidth;
		const rightOverflow = childRightEdge + margin - parentRightEdge;
		const leftOverflow = parentScroll - ( childLeft - margin );

		let scrollLeft = null;
		if ( leftOverflow > 0 ) {
			scrollLeft = parentScroll - leftOverflow;
		} else if ( rightOverflow > 0 ) {
			scrollLeft = parentScroll + rightOverflow;
		}

		if ( scrollLeft !== null ) {
			/**
			 * The optional chaining is used here to avoid unit test failures.
			 * It can be removed when JSDOM supports `Element` scroll methods.
			 * See: https://github.com/WordPress/gutenberg/pull/66498#issuecomment-2441146096
			 */
			parent.scroll?.( { left: scrollLeft } );
		}
	}, [ margin, parent, rect ] );
}

export const TabList = forwardRef<
	HTMLDivElement,
	React.ComponentPropsWithoutRef< 'div' > & TabListProps
>( function TabList( { children, density = 'default', ...otherProps }, ref ) {
	const { store } = useTabsContext() ?? {};

	const selectedId = Ariakit.useStoreState( store, 'selectedId' );
	const activeId = Ariakit.useStoreState( store, 'activeId' );
	const selectOnMove = Ariakit.useStoreState( store, 'selectOnMove' );
	const items = Ariakit.useStoreState( store, 'items' );
	const [ parent, setParent ] = useState< HTMLElement >();
	const refs = useMergeRefs( [ ref, setParent ] );

	const selectedItem = store?.item( selectedId );
	const renderedItems = Ariakit.useStoreState( store, 'renderedItems' );

	const selectedItemIndex =
		renderedItems && selectedItem ? renderedItems.indexOf( selectedItem ) : -1;
	// Use selectedItemIndex as a dependency to force recalculation when the
	// selected item index changes (elements are swapped / added / removed).
	const selectedRect = useTrackElementOffsetRect( selectedItem?.element, [ selectedItemIndex ] );

	// Track overflow to show scroll hints.
	const overflow = useTrackOverflow( parent, {
		first: items?.at( 0 )?.element,
		last: items?.at( -1 )?.element,
	} );

	// Size, position, and animate the indicator.
	useAnimatedOffsetRect( parent, selectedRect, {
		prefix: 'selected',
		dataAttribute: 'indicator-animated',
		transitionEndFilter: ( event ) => event.pseudoElement === '::before',
		roundRect: true,
	} );

	// Make sure selected tab is scrolled into view.
	useScrollRectIntoView( parent, selectedRect );

	const onBlur = () => {
		if ( ! selectOnMove ) {
			return;
		}

		// When automatic tab selection is on, make sure that the active tab is up
		// to date with the selected tab when leaving the tablist. This makes sure
		// that the selected tab will receive keyboard focus when tabbing back into
		// the tablist.
		if ( selectedId !== activeId ) {
			store?.setActiveId( selectedId );
		}
	};

	if ( ! store ) {
		warning( '`Tabs.TabList` must be wrapped in a `Tabs` component.' );
		return null;
	}

	return (
		<Ariakit.TabList
			ref={ refs }
			store={ store }
			render={ ( props ) => (
				<div
					{ ...props }
					// Fallback to -1 to prevent browsers from making the tablist
					// tabbable when it is a scrolling container.
					tabIndex={ props.tabIndex ?? -1 }
				/>
			) }
			onBlur={ onBlur }
			data-select-on-move={ selectOnMove ? 'true' : 'false' }
			{ ...otherProps }
			className={ clsx(
				styles.tablist,
				overflow.first && styles[ 'is-overflowing-first' ],
				overflow.last && styles[ 'is-overflowing-last' ],
				styles[ `has-${ density }-density` ],
				otherProps.className
			) }
		>
			{ children }
		</Ariakit.TabList>
	);
} );