(props: TabListStateOptions<T>)
| 54 | * which tab is currently selected and displays the content associated with that Tab in a TabPanel. |
| 55 | */ |
| 56 | export function useTabListState<T extends object>(props: TabListStateOptions<T>): TabListState<T> { |
| 57 | let state = useSingleSelectListState<T>({ |
| 58 | ...props, |
| 59 | onSelectionChange: props.onSelectionChange |
| 60 | ? key => { |
| 61 | if (key != null) { |
| 62 | props.onSelectionChange?.(key); |
| 63 | } |
| 64 | } |
| 65 | : undefined, |
| 66 | suppressTextValueWarning: true, |
| 67 | defaultSelectedKey: |
| 68 | props.defaultSelectedKey ?? |
| 69 | findDefaultSelectedKey( |
| 70 | props.collection, |
| 71 | props.disabledKeys ? new Set(props.disabledKeys) : new Set() |
| 72 | ) ?? |
| 73 | undefined |
| 74 | }); |
| 75 | |
| 76 | let {selectionManager, collection, selectedKey: currentSelectedKey} = state; |
| 77 | |
| 78 | let lastSelectedKey = useRef(currentSelectedKey); |
| 79 | useEffect(() => { |
| 80 | // Ensure a tab is always selected (in case no selected key was specified or if selected item was deleted from collection) |
| 81 | let selectedKey = currentSelectedKey; |
| 82 | if ( |
| 83 | props.selectedKey == null && |
| 84 | (selectionManager.isEmpty || selectedKey == null || !collection.getItem(selectedKey)) |
| 85 | ) { |
| 86 | selectedKey = findDefaultSelectedKey(collection, state.disabledKeys); |
| 87 | if (selectedKey != null) { |
| 88 | // directly set selection because replace/toggle selection won't consider disabled keys |
| 89 | selectionManager.setSelectedKeys([selectedKey]); |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // If the tablist doesn't have focus and the selected key changes or if there isn't a focused key yet, change focused key to the selected key if it exists. |
| 94 | if ( |
| 95 | (selectedKey != null && selectionManager.focusedKey == null) || |
| 96 | (!selectionManager.isFocused && selectedKey !== lastSelectedKey.current) |
| 97 | ) { |
| 98 | selectionManager.setFocusedKey(selectedKey); |
| 99 | } |
| 100 | lastSelectedKey.current = selectedKey; |
| 101 | }); |
| 102 | |
| 103 | return { |
| 104 | ...state, |
| 105 | isDisabled: props.isDisabled || false |
| 106 | }; |
| 107 | } |
| 108 | |
| 109 | function findDefaultSelectedKey<T>( |
| 110 | collection: Collection<Node<T>> | undefined, |
no test coverage detected