pre-installations and preparations
This commit is contained in:
1 parent
3e5a0329cb
commit
201d621ac3
6977 files changed
+742826
No files matched your search
+8
@@ -0,0 +1,8 @@
|
||||
import * as React from 'react';
|
||||
import { ListAction } from './listActions.types';
|
||||
import { ListItemState } from './useList.types';
|
||||
export interface ListContextValue<ItemValue> {
|
||||
dispatch: (action: ListAction<ItemValue>) => void;
|
||||
getItemState: (item: ItemValue) => ListItemState;
|
||||
}
|
||||
export declare const ListContext: React.Context<ListContextValue<any> | null>;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import * as React from 'react';
|
||||
export const ListContext = /*#__PURE__*/React.createContext(null);
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
ListContext.displayName = 'ListContext';
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
export { useList } from './useList';
|
||||
export * from './useList.types';
|
||||
export { useListItem } from './useListItem';
|
||||
export * from './useListItem.types';
|
||||
export * from './listReducer';
|
||||
export * from './listActions.types';
|
||||
export * from './ListContext';
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
'use client';
|
||||
|
||||
export { useList } from './useList';
|
||||
export * from './useList.types';
|
||||
export { useListItem } from './useListItem';
|
||||
export * from './useListItem.types';
|
||||
export * from './listReducer';
|
||||
export * from './listActions.types';
|
||||
export * from './ListContext';
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/// <reference types="react" />
|
||||
export declare const ListActionTypes: {
|
||||
readonly blur: "list:blur";
|
||||
readonly focus: "list:focus";
|
||||
readonly itemClick: "list:itemClick";
|
||||
readonly itemHover: "list:itemHover";
|
||||
readonly itemsChange: "list:itemsChange";
|
||||
readonly keyDown: "list:keyDown";
|
||||
readonly resetHighlight: "list:resetHighlight";
|
||||
readonly highlightLast: "list:highlightLast";
|
||||
readonly textNavigation: "list:textNavigation";
|
||||
readonly clearSelection: "list:clearSelection";
|
||||
};
|
||||
interface ItemClickAction<ItemValue> {
|
||||
type: typeof ListActionTypes.itemClick;
|
||||
item: ItemValue;
|
||||
event: React.MouseEvent;
|
||||
}
|
||||
interface ItemHoverAction<ItemValue> {
|
||||
type: typeof ListActionTypes.itemHover;
|
||||
item: ItemValue;
|
||||
event: React.MouseEvent;
|
||||
}
|
||||
interface FocusAction {
|
||||
type: typeof ListActionTypes.focus;
|
||||
event: React.FocusEvent;
|
||||
}
|
||||
interface BlurAction {
|
||||
type: typeof ListActionTypes.blur;
|
||||
event: React.FocusEvent;
|
||||
}
|
||||
interface KeyDownAction {
|
||||
type: typeof ListActionTypes.keyDown;
|
||||
key: string;
|
||||
event: React.KeyboardEvent;
|
||||
}
|
||||
interface TextNavigationAction {
|
||||
type: typeof ListActionTypes.textNavigation;
|
||||
event: React.KeyboardEvent;
|
||||
searchString: string;
|
||||
}
|
||||
interface ItemsChangeAction<ItemValue> {
|
||||
type: typeof ListActionTypes.itemsChange;
|
||||
event: null;
|
||||
items: ItemValue[];
|
||||
previousItems: ItemValue[];
|
||||
}
|
||||
interface ResetHighlightAction {
|
||||
type: typeof ListActionTypes.resetHighlight;
|
||||
event: React.SyntheticEvent | null;
|
||||
}
|
||||
interface HighlightLastAction {
|
||||
type: typeof ListActionTypes.highlightLast;
|
||||
event: React.SyntheticEvent | null;
|
||||
}
|
||||
interface ClearSelectionAction {
|
||||
type: typeof ListActionTypes.clearSelection;
|
||||
}
|
||||
/**
|
||||
* A union of all standard actions that can be dispatched to the list reducer.
|
||||
*/
|
||||
export type ListAction<ItemValue> = BlurAction | FocusAction | ItemClickAction<ItemValue> | ItemHoverAction<ItemValue> | ItemsChangeAction<ItemValue> | KeyDownAction | ResetHighlightAction | HighlightLastAction | TextNavigationAction | ClearSelectionAction;
|
||||
export {};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
export const ListActionTypes = {
|
||||
blur: 'list:blur',
|
||||
focus: 'list:focus',
|
||||
itemClick: 'list:itemClick',
|
||||
itemHover: 'list:itemHover',
|
||||
itemsChange: 'list:itemsChange',
|
||||
keyDown: 'list:keyDown',
|
||||
resetHighlight: 'list:resetHighlight',
|
||||
highlightLast: 'list:highlightLast',
|
||||
textNavigation: 'list:textNavigation',
|
||||
clearSelection: 'list:clearSelection'
|
||||
};
|
||||
|
||||
/**
|
||||
* A union of all standard actions that can be dispatched to the list reducer.
|
||||
*/
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { ListState, ListReducerAction, ListActionContext, SelectionMode } from './useList.types';
|
||||
/**
|
||||
* Gets the next item to highlight based on the current highlighted item and the search direction.
|
||||
*
|
||||
* @param previouslyHighlightedValue The item from which to start the search for the next candidate.
|
||||
* @param offset The offset from the previously highlighted item to search for the next candidate or a special named value ('reset', 'start', 'end').
|
||||
* @param context The list action context.
|
||||
*
|
||||
* @returns The next item to highlight or null if no item is valid.
|
||||
*/
|
||||
export declare function moveHighlight<ItemValue>(previouslyHighlightedValue: ItemValue | null, offset: number | 'reset' | 'start' | 'end', context: ListActionContext<ItemValue>): NonNullable<ItemValue> | (ItemValue & undefined) | null;
|
||||
/**
|
||||
* Toggles the selection of an item.
|
||||
*
|
||||
* @param item Item to toggle.
|
||||
* @param selectedValues Already selected items.
|
||||
* @param selectionMode The number of items that can be simultanously selected.
|
||||
* @param itemComparer A custom item comparer function.
|
||||
*
|
||||
* @returns The new array of selected items.
|
||||
*/
|
||||
export declare function toggleSelection<ItemValue>(item: ItemValue, selectedValues: ItemValue[], selectionMode: SelectionMode, itemComparer: (item1: ItemValue, item2: ItemValue) => boolean): ItemValue[];
|
||||
/**
|
||||
* Handles item selection in a list.
|
||||
*
|
||||
* @param item - The item to be selected.
|
||||
* @param state - The current state of the list.
|
||||
* @param context - The context of the list action.
|
||||
* @returns The new state of the list after the item has been selected, or the original state if the item is disabled.
|
||||
*/
|
||||
export declare function handleItemSelection<ItemValue, State extends ListState<ItemValue>>(item: ItemValue, state: State, context: ListActionContext<ItemValue>): State;
|
||||
export declare function listReducer<ItemValue, State extends ListState<ItemValue>>(state: State, action: ListReducerAction<ItemValue> & {
|
||||
context: ListActionContext<ItemValue>;
|
||||
}): State;
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import { ListActionTypes } from './listActions.types';
|
||||
/**
|
||||
* Looks up the next valid item to highlight within the list.
|
||||
*
|
||||
* @param currentIndex The index of the start of the search.
|
||||
* @param lookupDirection Whether to look for the next or previous item.
|
||||
* @param items The array of items to search.
|
||||
* @param includeDisabledItems Whether to include disabled items in the search.
|
||||
* @param isItemDisabled A function that determines whether an item is disabled.
|
||||
* @param wrapAround Whether to wrap around the list when searching.
|
||||
* @returns The index of the next valid item to highlight or -1 if no valid item is found.
|
||||
*/
|
||||
function findValidItemToHighlight(currentIndex, lookupDirection, items, includeDisabledItems, isItemDisabled, wrapAround) {
|
||||
if (items.length === 0 || !includeDisabledItems && items.every((item, itemIndex) => isItemDisabled(item, itemIndex))) {
|
||||
return -1;
|
||||
}
|
||||
let nextFocus = currentIndex;
|
||||
for (;;) {
|
||||
// No valid items found
|
||||
if (!wrapAround && lookupDirection === 'next' && nextFocus === items.length || !wrapAround && lookupDirection === 'previous' && nextFocus === -1) {
|
||||
return -1;
|
||||
}
|
||||
const nextFocusDisabled = includeDisabledItems ? false : isItemDisabled(items[nextFocus], nextFocus);
|
||||
if (nextFocusDisabled) {
|
||||
nextFocus += lookupDirection === 'next' ? 1 : -1;
|
||||
if (wrapAround) {
|
||||
nextFocus = (nextFocus + items.length) % items.length;
|
||||
}
|
||||
} else {
|
||||
return nextFocus;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the next item to highlight based on the current highlighted item and the search direction.
|
||||
*
|
||||
* @param previouslyHighlightedValue The item from which to start the search for the next candidate.
|
||||
* @param offset The offset from the previously highlighted item to search for the next candidate or a special named value ('reset', 'start', 'end').
|
||||
* @param context The list action context.
|
||||
*
|
||||
* @returns The next item to highlight or null if no item is valid.
|
||||
*/
|
||||
export function moveHighlight(previouslyHighlightedValue, offset, context) {
|
||||
var _items$nextIndex;
|
||||
const {
|
||||
items,
|
||||
isItemDisabled,
|
||||
disableListWrap,
|
||||
disabledItemsFocusable,
|
||||
itemComparer,
|
||||
focusManagement
|
||||
} = context;
|
||||
|
||||
// TODO: make this configurable
|
||||
// The always should be an item highlighted when focus is managed by the DOM
|
||||
// so that it's accessible by the `tab` key.
|
||||
const defaultHighlightedIndex = focusManagement === 'DOM' ? 0 : -1;
|
||||
const maxIndex = items.length - 1;
|
||||
const previouslyHighlightedIndex = previouslyHighlightedValue == null ? -1 : items.findIndex(item => itemComparer(item, previouslyHighlightedValue));
|
||||
let nextIndexCandidate;
|
||||
let lookupDirection;
|
||||
let wrapAround = !disableListWrap;
|
||||
switch (offset) {
|
||||
case 'reset':
|
||||
if (defaultHighlightedIndex === -1) {
|
||||
return null;
|
||||
}
|
||||
nextIndexCandidate = 0;
|
||||
lookupDirection = 'next';
|
||||
wrapAround = false;
|
||||
break;
|
||||
case 'start':
|
||||
nextIndexCandidate = 0;
|
||||
lookupDirection = 'next';
|
||||
wrapAround = false;
|
||||
break;
|
||||
case 'end':
|
||||
nextIndexCandidate = maxIndex;
|
||||
lookupDirection = 'previous';
|
||||
wrapAround = false;
|
||||
break;
|
||||
default:
|
||||
{
|
||||
const newIndex = previouslyHighlightedIndex + offset;
|
||||
if (newIndex < 0) {
|
||||
if (!wrapAround && previouslyHighlightedIndex !== -1 || Math.abs(offset) > 1) {
|
||||
nextIndexCandidate = 0;
|
||||
lookupDirection = 'next';
|
||||
} else {
|
||||
nextIndexCandidate = maxIndex;
|
||||
lookupDirection = 'previous';
|
||||
}
|
||||
} else if (newIndex > maxIndex) {
|
||||
if (!wrapAround || Math.abs(offset) > 1) {
|
||||
nextIndexCandidate = maxIndex;
|
||||
lookupDirection = 'previous';
|
||||
} else {
|
||||
nextIndexCandidate = 0;
|
||||
lookupDirection = 'next';
|
||||
}
|
||||
} else {
|
||||
nextIndexCandidate = newIndex;
|
||||
lookupDirection = offset >= 0 ? 'next' : 'previous';
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextIndex = findValidItemToHighlight(nextIndexCandidate, lookupDirection, items, disabledItemsFocusable, isItemDisabled, wrapAround);
|
||||
|
||||
// If there are no valid items to highlight, return the previously highlighted item (if it's still valid).
|
||||
if (nextIndex === -1 && previouslyHighlightedValue !== null && !isItemDisabled(previouslyHighlightedValue, previouslyHighlightedIndex)) {
|
||||
return previouslyHighlightedValue;
|
||||
}
|
||||
return (_items$nextIndex = items[nextIndex]) != null ? _items$nextIndex : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles the selection of an item.
|
||||
*
|
||||
* @param item Item to toggle.
|
||||
* @param selectedValues Already selected items.
|
||||
* @param selectionMode The number of items that can be simultanously selected.
|
||||
* @param itemComparer A custom item comparer function.
|
||||
*
|
||||
* @returns The new array of selected items.
|
||||
*/
|
||||
export function toggleSelection(item, selectedValues, selectionMode, itemComparer) {
|
||||
if (selectionMode === 'none') {
|
||||
return [];
|
||||
}
|
||||
if (selectionMode === 'single') {
|
||||
// if the item to select has already been selected, return the original array
|
||||
if (itemComparer(selectedValues[0], item)) {
|
||||
return selectedValues;
|
||||
}
|
||||
return [item];
|
||||
}
|
||||
|
||||
// The toggled item is selected; remove it from the selection.
|
||||
if (selectedValues.some(sv => itemComparer(sv, item))) {
|
||||
return selectedValues.filter(sv => !itemComparer(sv, item));
|
||||
}
|
||||
|
||||
// The toggled item is not selected - add it to the selection.
|
||||
return [...selectedValues, item];
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles item selection in a list.
|
||||
*
|
||||
* @param item - The item to be selected.
|
||||
* @param state - The current state of the list.
|
||||
* @param context - The context of the list action.
|
||||
* @returns The new state of the list after the item has been selected, or the original state if the item is disabled.
|
||||
*/
|
||||
export function handleItemSelection(item, state, context) {
|
||||
const {
|
||||
itemComparer,
|
||||
isItemDisabled,
|
||||
selectionMode,
|
||||
items
|
||||
} = context;
|
||||
const {
|
||||
selectedValues
|
||||
} = state;
|
||||
const itemIndex = items.findIndex(i => itemComparer(item, i));
|
||||
if (isItemDisabled(item, itemIndex)) {
|
||||
return state;
|
||||
}
|
||||
|
||||
// if the item is already selected, remove it from the selection, otherwise add it
|
||||
const newSelectedValues = toggleSelection(item, selectedValues, selectionMode, itemComparer);
|
||||
return _extends({}, state, {
|
||||
selectedValues: newSelectedValues,
|
||||
highlightedValue: item
|
||||
});
|
||||
}
|
||||
function handleKeyDown(key, state, context) {
|
||||
const previouslySelectedValue = state.highlightedValue;
|
||||
const {
|
||||
orientation,
|
||||
pageSize
|
||||
} = context;
|
||||
switch (key) {
|
||||
case 'Home':
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, 'start', context)
|
||||
});
|
||||
case 'End':
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, 'end', context)
|
||||
});
|
||||
case 'PageUp':
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, -pageSize, context)
|
||||
});
|
||||
case 'PageDown':
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, pageSize, context)
|
||||
});
|
||||
case 'ArrowUp':
|
||||
if (orientation !== 'vertical') {
|
||||
break;
|
||||
}
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, -1, context)
|
||||
});
|
||||
case 'ArrowDown':
|
||||
if (orientation !== 'vertical') {
|
||||
break;
|
||||
}
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, 1, context)
|
||||
});
|
||||
case 'ArrowLeft':
|
||||
{
|
||||
if (orientation === 'vertical') {
|
||||
break;
|
||||
}
|
||||
const offset = orientation === 'horizontal-ltr' ? -1 : 1;
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, offset, context)
|
||||
});
|
||||
}
|
||||
case 'ArrowRight':
|
||||
{
|
||||
if (orientation === 'vertical') {
|
||||
break;
|
||||
}
|
||||
const offset = orientation === 'horizontal-ltr' ? 1 : -1;
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(previouslySelectedValue, offset, context)
|
||||
});
|
||||
}
|
||||
case 'Enter':
|
||||
case ' ':
|
||||
if (state.highlightedValue === null) {
|
||||
return state;
|
||||
}
|
||||
return handleItemSelection(state.highlightedValue, state, context);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
function handleBlur(state, context) {
|
||||
if (context.focusManagement === 'DOM') {
|
||||
return state;
|
||||
}
|
||||
return _extends({}, state, {
|
||||
highlightedValue: null
|
||||
});
|
||||
}
|
||||
function textCriteriaMatches(nextFocus, searchString, stringifyItem) {
|
||||
var _stringifyItem;
|
||||
const text = (_stringifyItem = stringifyItem(nextFocus)) == null ? void 0 : _stringifyItem.trim().toLowerCase();
|
||||
if (!text || text.length === 0) {
|
||||
// Make item not navigable if stringification fails or results in empty string.
|
||||
return false;
|
||||
}
|
||||
return text.indexOf(searchString) === 0;
|
||||
}
|
||||
function handleTextNavigation(state, searchString, context) {
|
||||
const {
|
||||
items,
|
||||
isItemDisabled,
|
||||
disabledItemsFocusable,
|
||||
getItemAsString
|
||||
} = context;
|
||||
const startWithCurrentItem = searchString.length > 1;
|
||||
let nextItem = startWithCurrentItem ? state.highlightedValue : moveHighlight(state.highlightedValue, 1, context);
|
||||
for (let index = 0; index < items.length; index += 1) {
|
||||
// Return un-mutated state if looped back to the currently highlighted value
|
||||
if (!nextItem || !startWithCurrentItem && state.highlightedValue === nextItem) {
|
||||
return state;
|
||||
}
|
||||
if (textCriteriaMatches(nextItem, searchString, getItemAsString) && (!isItemDisabled(nextItem, items.indexOf(nextItem)) || disabledItemsFocusable)) {
|
||||
// The nextItem is the element to be highlighted
|
||||
return _extends({}, state, {
|
||||
highlightedValue: nextItem
|
||||
});
|
||||
}
|
||||
// Move to the next element.
|
||||
nextItem = moveHighlight(nextItem, 1, context);
|
||||
}
|
||||
|
||||
// No item matches the text search criteria
|
||||
return state;
|
||||
}
|
||||
function handleItemsChange(items, previousItems, state, context) {
|
||||
var _state$selectedValues;
|
||||
const {
|
||||
itemComparer,
|
||||
focusManagement
|
||||
} = context;
|
||||
let newHighlightedValue = null;
|
||||
if (state.highlightedValue != null) {
|
||||
var _items$find;
|
||||
newHighlightedValue = (_items$find = items.find(item => itemComparer(item, state.highlightedValue))) != null ? _items$find : null;
|
||||
} else if (focusManagement === 'DOM' && previousItems.length === 0) {
|
||||
newHighlightedValue = moveHighlight(null, 'reset', context);
|
||||
}
|
||||
|
||||
// exclude selected values that are no longer in the items list
|
||||
const selectedValues = (_state$selectedValues = state.selectedValues) != null ? _state$selectedValues : [];
|
||||
const newSelectedValues = selectedValues.filter(selectedValue => items.some(item => itemComparer(item, selectedValue)));
|
||||
return _extends({}, state, {
|
||||
highlightedValue: newHighlightedValue,
|
||||
selectedValues: newSelectedValues
|
||||
});
|
||||
}
|
||||
function handleResetHighlight(state, context) {
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(null, 'reset', context)
|
||||
});
|
||||
}
|
||||
function handleHighlightLast(state, context) {
|
||||
return _extends({}, state, {
|
||||
highlightedValue: moveHighlight(null, 'end', context)
|
||||
});
|
||||
}
|
||||
function handleClearSelection(state, context) {
|
||||
return _extends({}, state, {
|
||||
selectedValues: [],
|
||||
highlightedValue: moveHighlight(null, 'reset', context)
|
||||
});
|
||||
}
|
||||
export function listReducer(state, action) {
|
||||
const {
|
||||
type,
|
||||
context
|
||||
} = action;
|
||||
switch (type) {
|
||||
case ListActionTypes.keyDown:
|
||||
return handleKeyDown(action.key, state, context);
|
||||
case ListActionTypes.itemClick:
|
||||
return handleItemSelection(action.item, state, context);
|
||||
case ListActionTypes.blur:
|
||||
return handleBlur(state, context);
|
||||
case ListActionTypes.textNavigation:
|
||||
return handleTextNavigation(state, action.searchString, context);
|
||||
case ListActionTypes.itemsChange:
|
||||
return handleItemsChange(action.items, action.previousItems, state, context);
|
||||
case ListActionTypes.resetHighlight:
|
||||
return handleResetHighlight(state, context);
|
||||
case ListActionTypes.highlightLast:
|
||||
return handleHighlightLast(state, context);
|
||||
case ListActionTypes.clearSelection:
|
||||
return handleClearSelection(state, context);
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sideEffects": false,
|
||||
"module": "./index.js",
|
||||
"main": "../node/useList/index.js",
|
||||
"types": "./index.d.ts"
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { UseListParameters, ListState, UseListReturnValue } from './useList.types';
|
||||
import { ControllableReducerAction } from '../utils/useControllableReducer.types';
|
||||
/**
|
||||
* The useList is a lower-level utility that is used to build list-like components.
|
||||
* It's used to manage the state of the list and its items.
|
||||
*
|
||||
* Supports highlighting a single item and selecting an arbitrary number of items.
|
||||
*
|
||||
* The state of the list is managed by a controllable reducer - that is a reducer that can have its state
|
||||
* controlled from outside.
|
||||
*
|
||||
* By default, the state consists of `selectedValues` and `highlightedValue` but can be extended by the caller of the hook.
|
||||
* Also the actions that can be dispatched and the reducer function can be defined externally.
|
||||
*
|
||||
* @template ItemValue The type of the item values.
|
||||
* @template State The type of the list state. This should be a subtype of `ListState<ItemValue>`.
|
||||
* @template CustomAction The type of the actions that can be dispatched (besides the standard ListAction).
|
||||
* @template CustomActionContext The shape of additional properties that will be added to actions when dispatched.
|
||||
*
|
||||
* @ignore - internal hook.
|
||||
*/
|
||||
declare function useList<ItemValue, State extends ListState<ItemValue> = ListState<ItemValue>, CustomAction extends ControllableReducerAction = never, CustomActionContext = {}>(params: UseListParameters<ItemValue, State, CustomAction, CustomActionContext>): UseListReturnValue<ItemValue, State, CustomAction>;
|
||||
export { useList };
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
'use client';
|
||||
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import * as React from 'react';
|
||||
import { unstable_useForkRef as useForkRef } from '@mui/utils';
|
||||
import { ListActionTypes } from './listActions.types';
|
||||
import { listReducer as defaultReducer } from './listReducer';
|
||||
import { useControllableReducer } from '../utils/useControllableReducer';
|
||||
import { areArraysEqual } from '../utils/areArraysEqual';
|
||||
import { useTextNavigation } from '../utils/useTextNavigation';
|
||||
import { extractEventHandlers } from '../utils/extractEventHandlers';
|
||||
const EMPTY_OBJECT = {};
|
||||
const NOOP = () => {};
|
||||
const defaultItemComparer = (optionA, optionB) => optionA === optionB;
|
||||
const defaultIsItemDisabled = () => false;
|
||||
const defaultItemStringifier = item => typeof item === 'string' ? item : String(item);
|
||||
const defaultGetInitialState = () => ({
|
||||
highlightedValue: null,
|
||||
selectedValues: []
|
||||
});
|
||||
|
||||
/**
|
||||
* The useList is a lower-level utility that is used to build list-like components.
|
||||
* It's used to manage the state of the list and its items.
|
||||
*
|
||||
* Supports highlighting a single item and selecting an arbitrary number of items.
|
||||
*
|
||||
* The state of the list is managed by a controllable reducer - that is a reducer that can have its state
|
||||
* controlled from outside.
|
||||
*
|
||||
* By default, the state consists of `selectedValues` and `highlightedValue` but can be extended by the caller of the hook.
|
||||
* Also the actions that can be dispatched and the reducer function can be defined externally.
|
||||
*
|
||||
* @template ItemValue The type of the item values.
|
||||
* @template State The type of the list state. This should be a subtype of `ListState<ItemValue>`.
|
||||
* @template CustomAction The type of the actions that can be dispatched (besides the standard ListAction).
|
||||
* @template CustomActionContext The shape of additional properties that will be added to actions when dispatched.
|
||||
*
|
||||
* @ignore - internal hook.
|
||||
*/
|
||||
function useList(params) {
|
||||
const {
|
||||
controlledProps = EMPTY_OBJECT,
|
||||
disabledItemsFocusable = false,
|
||||
disableListWrap = false,
|
||||
focusManagement = 'activeDescendant',
|
||||
getInitialState = defaultGetInitialState,
|
||||
getItemDomElement,
|
||||
getItemId,
|
||||
isItemDisabled = defaultIsItemDisabled,
|
||||
rootRef: externalListRef,
|
||||
onStateChange = NOOP,
|
||||
items,
|
||||
itemComparer = defaultItemComparer,
|
||||
getItemAsString = defaultItemStringifier,
|
||||
onChange,
|
||||
onHighlightChange,
|
||||
onItemsChange,
|
||||
orientation = 'vertical',
|
||||
pageSize = 5,
|
||||
reducerActionContext = EMPTY_OBJECT,
|
||||
selectionMode = 'single',
|
||||
stateReducer: externalReducer,
|
||||
componentName = 'useList'
|
||||
} = params;
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (focusManagement === 'DOM' && getItemDomElement == null) {
|
||||
throw new Error('useList: The `getItemDomElement` prop is required when using the `DOM` focus management.');
|
||||
}
|
||||
if (focusManagement === 'activeDescendant' && getItemId == null) {
|
||||
throw new Error('useList: The `getItemId` prop is required when using the `activeDescendant` focus management.');
|
||||
}
|
||||
}
|
||||
const listRef = React.useRef(null);
|
||||
const handleRef = useForkRef(externalListRef, listRef);
|
||||
const handleHighlightChange = React.useCallback((event, value, reason) => {
|
||||
onHighlightChange == null || onHighlightChange(event, value, reason);
|
||||
if (focusManagement === 'DOM' && value != null && (reason === ListActionTypes.itemClick || reason === ListActionTypes.keyDown || reason === ListActionTypes.textNavigation)) {
|
||||
var _getItemDomElement;
|
||||
getItemDomElement == null || (_getItemDomElement = getItemDomElement(value)) == null || _getItemDomElement.focus();
|
||||
}
|
||||
}, [getItemDomElement, onHighlightChange, focusManagement]);
|
||||
const stateComparers = React.useMemo(() => ({
|
||||
highlightedValue: itemComparer,
|
||||
selectedValues: (valuesArray1, valuesArray2) => areArraysEqual(valuesArray1, valuesArray2, itemComparer)
|
||||
}), [itemComparer]);
|
||||
|
||||
// This gets called whenever a reducer changes the state.
|
||||
const handleStateChange = React.useCallback((event, field, value, reason, state) => {
|
||||
onStateChange == null || onStateChange(event, field, value, reason, state);
|
||||
switch (field) {
|
||||
case 'highlightedValue':
|
||||
handleHighlightChange(event, value, reason);
|
||||
break;
|
||||
case 'selectedValues':
|
||||
onChange == null || onChange(event, value, reason);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}, [handleHighlightChange, onChange, onStateChange]);
|
||||
|
||||
// The following object is added to each action when it's dispatched.
|
||||
// It's accessible in the reducer via the `action.context` field.
|
||||
const listActionContext = React.useMemo(() => {
|
||||
return {
|
||||
disabledItemsFocusable,
|
||||
disableListWrap,
|
||||
focusManagement,
|
||||
isItemDisabled,
|
||||
itemComparer,
|
||||
items,
|
||||
getItemAsString,
|
||||
onHighlightChange: handleHighlightChange,
|
||||
orientation,
|
||||
pageSize,
|
||||
selectionMode,
|
||||
stateComparers
|
||||
};
|
||||
}, [disabledItemsFocusable, disableListWrap, focusManagement, isItemDisabled, itemComparer, items, getItemAsString, handleHighlightChange, orientation, pageSize, selectionMode, stateComparers]);
|
||||
const initialState = getInitialState();
|
||||
const reducer = externalReducer != null ? externalReducer : defaultReducer;
|
||||
const actionContext = React.useMemo(() => _extends({}, reducerActionContext, listActionContext), [reducerActionContext, listActionContext]);
|
||||
const [state, dispatch] = useControllableReducer({
|
||||
reducer,
|
||||
actionContext,
|
||||
initialState: initialState,
|
||||
controlledProps,
|
||||
stateComparers,
|
||||
onStateChange: handleStateChange,
|
||||
componentName
|
||||
});
|
||||
const {
|
||||
highlightedValue,
|
||||
selectedValues
|
||||
} = state;
|
||||
const handleTextNavigation = useTextNavigation((searchString, event) => dispatch({
|
||||
type: ListActionTypes.textNavigation,
|
||||
event,
|
||||
searchString
|
||||
}));
|
||||
const previousItems = React.useRef([]);
|
||||
React.useEffect(() => {
|
||||
// Whenever the `items` object changes, we need to determine if the actual items changed.
|
||||
// If they did, we need to dispatch an `itemsChange` action, so the selected/highlighted state is updated.
|
||||
if (areArraysEqual(previousItems.current, items, itemComparer)) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: ListActionTypes.itemsChange,
|
||||
event: null,
|
||||
items,
|
||||
previousItems: previousItems.current
|
||||
});
|
||||
previousItems.current = items;
|
||||
onItemsChange == null || onItemsChange(items);
|
||||
}, [items, itemComparer, dispatch, onItemsChange]);
|
||||
const createHandleKeyDown = externalHandlers => event => {
|
||||
var _externalHandlers$onK;
|
||||
(_externalHandlers$onK = externalHandlers.onKeyDown) == null || _externalHandlers$onK.call(externalHandlers, event);
|
||||
if (event.defaultMuiPrevented) {
|
||||
return;
|
||||
}
|
||||
const keysToPreventDefault = ['Home', 'End', 'PageUp', 'PageDown'];
|
||||
if (orientation === 'vertical') {
|
||||
keysToPreventDefault.push('ArrowUp', 'ArrowDown');
|
||||
} else {
|
||||
keysToPreventDefault.push('ArrowLeft', 'ArrowRight');
|
||||
}
|
||||
if (focusManagement === 'activeDescendant') {
|
||||
// When the child element is focused using the activeDescendant attribute,
|
||||
// the list handles keyboard events on its behalf.
|
||||
// We have to `preventDefault()` is this case to prevent the browser from
|
||||
// scrolling the view when space is pressed or submitting forms when enter is pressed.
|
||||
keysToPreventDefault.push(' ', 'Enter');
|
||||
}
|
||||
if (keysToPreventDefault.includes(event.key)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
dispatch({
|
||||
type: ListActionTypes.keyDown,
|
||||
key: event.key,
|
||||
event
|
||||
});
|
||||
handleTextNavigation(event);
|
||||
};
|
||||
const createHandleBlur = externalHandlers => event => {
|
||||
var _externalHandlers$onB, _listRef$current;
|
||||
(_externalHandlers$onB = externalHandlers.onBlur) == null || _externalHandlers$onB.call(externalHandlers, event);
|
||||
if (event.defaultMuiPrevented) {
|
||||
return;
|
||||
}
|
||||
if ((_listRef$current = listRef.current) != null && _listRef$current.contains(event.relatedTarget)) {
|
||||
// focus remains within the list
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: ListActionTypes.blur,
|
||||
event
|
||||
});
|
||||
};
|
||||
const getRootProps = (externalProps = {}) => {
|
||||
const externalEventHandlers = extractEventHandlers(externalProps);
|
||||
return _extends({}, externalProps, {
|
||||
'aria-activedescendant': focusManagement === 'activeDescendant' && highlightedValue != null ? getItemId(highlightedValue) : undefined,
|
||||
tabIndex: focusManagement === 'DOM' ? -1 : 0,
|
||||
ref: handleRef
|
||||
}, externalEventHandlers, {
|
||||
onBlur: createHandleBlur(externalEventHandlers),
|
||||
onKeyDown: createHandleKeyDown(externalEventHandlers)
|
||||
});
|
||||
};
|
||||
const getItemState = React.useCallback(item => {
|
||||
const selected = (selectedValues != null ? selectedValues : []).some(value => value != null && itemComparer(item, value));
|
||||
const highlighted = highlightedValue != null && itemComparer(item, highlightedValue);
|
||||
const focusable = focusManagement === 'DOM';
|
||||
return {
|
||||
focusable,
|
||||
highlighted,
|
||||
selected
|
||||
};
|
||||
}, [itemComparer, selectedValues, highlightedValue, focusManagement]);
|
||||
const contextValue = React.useMemo(() => ({
|
||||
dispatch,
|
||||
getItemState
|
||||
}), [dispatch, getItemState]);
|
||||
React.useDebugValue({
|
||||
state
|
||||
});
|
||||
return {
|
||||
contextValue,
|
||||
dispatch,
|
||||
getRootProps,
|
||||
rootRef: handleRef,
|
||||
state
|
||||
};
|
||||
}
|
||||
export { useList };
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
import * as React from 'react';
|
||||
import { Simplify } from '@mui/types';
|
||||
import { ListAction } from './listActions.types';
|
||||
import { ActionWithContext, ControllableReducerAction, StateChangeCallback } from '../utils/useControllableReducer.types';
|
||||
import type { ListContextValue } from './ListContext';
|
||||
import { MuiCancellableEventHandler } from '../utils/MuiCancellableEvent';
|
||||
type ListActionContextRequiredKeys = 'disabledItemsFocusable' | 'disableListWrap' | 'focusManagement' | 'getItemAsString' | 'isItemDisabled' | 'itemComparer' | 'items' | 'orientation' | 'pageSize' | 'selectionMode';
|
||||
/**
|
||||
* The subset of `UseListParameters` that is passed to the list reducer actions.
|
||||
*/
|
||||
export type ListActionContext<ItemValue> = Simplify<Required<Pick<UseListParameters<ItemValue, any, any>, ListActionContextRequiredKeys>>>;
|
||||
/**
|
||||
* The action object augmented with the action context ({@linkcode ListActionContext} instance).
|
||||
* Instances of this type are passed to the reducer.
|
||||
*
|
||||
* @template ItemValue The type of the item values.
|
||||
* @template CustomActionContext The shape of additional properties that will be added to actions when dispatched.
|
||||
*/
|
||||
export type ListReducerAction<ItemValue, CustomActionContext = {}> = ActionWithContext<ListAction<ItemValue>, ListActionContext<ItemValue> & CustomActionContext>;
|
||||
/**
|
||||
* The state of the list.
|
||||
* Modifications to this state should be done via the reducer.
|
||||
*/
|
||||
export interface ListState<ItemValue> {
|
||||
/**
|
||||
* The item that is currently highlighted.
|
||||
*/
|
||||
highlightedValue: ItemValue | null;
|
||||
/**
|
||||
* The item(s) that are currently selected.
|
||||
*/
|
||||
selectedValues: ItemValue[];
|
||||
}
|
||||
/**
|
||||
* Type of the reducer that operates on the list state.
|
||||
*
|
||||
* @template ItemValue The type of the item values.
|
||||
* @template State The type of the list state. This should be a subtype of ListState<ItemValue>.
|
||||
* @template CustomActionContext The shape of additional properties that will be added to actions when dispatched.
|
||||
*/
|
||||
export type ListReducer<ItemValue, State extends ListState<ItemValue>, CustomActionContext> = (state: State, action: ListReducerAction<ItemValue, CustomActionContext>) => State;
|
||||
export type FocusManagementType = 'DOM' | 'activeDescendant';
|
||||
export type SelectionMode = 'none' | 'single' | 'multiple';
|
||||
/**
|
||||
* Parameters of the useList hook.
|
||||
*
|
||||
* @template ItemValue The type of the item values.
|
||||
* @template State The type of the list state. This should be a subtype of `ListState<ItemValue>`.
|
||||
* @template CustomAction The type of the actions that can be dispatched (besides the standard ListAction).
|
||||
* @template CustomActionContext The shape of additional properties that will be added to actions when dispatched.
|
||||
*/
|
||||
export interface UseListParameters<ItemValue, State extends ListState<ItemValue> = ListState<ItemValue>, CustomAction extends ControllableReducerAction = never, CustomActionContext = {}> {
|
||||
/**
|
||||
* The externally controlled values (highlighted and selected item(s)) of the list.
|
||||
* If a custom state is used, this object can contain the added state fields as well.
|
||||
*
|
||||
* @default {}
|
||||
*/
|
||||
controlledProps?: Partial<State>;
|
||||
/**
|
||||
* If `true`, it will be possible to highlight disabled items.
|
||||
* @default false
|
||||
*/
|
||||
disabledItemsFocusable?: boolean;
|
||||
/**
|
||||
* If `true`, the highlight will not wrap around the list if arrow keys are used.
|
||||
* @default false
|
||||
*/
|
||||
disableListWrap?: boolean;
|
||||
/**
|
||||
* The focus management strategy used by the list.
|
||||
* Controls the attributes used to set focus on the list items.
|
||||
* @default 'activeDescendant'
|
||||
*/
|
||||
focusManagement?: FocusManagementType;
|
||||
/**
|
||||
* A function that returns the DOM element associated with an item.
|
||||
* This is required when using the `DOM` focus management.
|
||||
*
|
||||
* @param item List item to get the DOM element for.
|
||||
*/
|
||||
getItemDomElement?: (itemValue: ItemValue) => HTMLElement | null;
|
||||
/**
|
||||
* A function that returns the id of an item.
|
||||
* This is required when using the `activeDescendant` focus management.
|
||||
*
|
||||
* @param itemValue List item to get the id for.
|
||||
*/
|
||||
getItemId?: (itemValue: ItemValue) => string | undefined;
|
||||
/**
|
||||
* A function that intializes the state of the list.
|
||||
* It is required when using a custom state with mandatory fields.
|
||||
* If not provided, the state will be initialized with the default values (nothing highlighted or selected).
|
||||
*
|
||||
* @returns The initial state of the list.
|
||||
*/
|
||||
getInitialState?: () => State;
|
||||
/**
|
||||
* A function that determines if a particular item is disabled.
|
||||
* @default () => false
|
||||
*/
|
||||
isItemDisabled?: (itemValue: ItemValue, index: number) => boolean;
|
||||
/**
|
||||
* Ref to the list root DOM element.
|
||||
*/
|
||||
rootRef?: React.Ref<Element>;
|
||||
/**
|
||||
* Callback fired when the selected value changes.
|
||||
* This is a strongly typed convenience event that can be used instead of `onStateChange`.
|
||||
*/
|
||||
onChange?: (event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null, value: ItemValue[], reason: string) => void;
|
||||
/**
|
||||
* Callback fired when the highlighted option changes.
|
||||
* This is a strongly typed convenience event that can be used instead of `onStateChange`.
|
||||
*/
|
||||
onHighlightChange?: (event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null, option: ItemValue | null, reason: string) => void;
|
||||
/**
|
||||
* Callback fired when the items change.
|
||||
*
|
||||
* @param items The new items collection
|
||||
*/
|
||||
onItemsChange?: (items: ItemValue[]) => void;
|
||||
/**
|
||||
* Callback fired when the any of the state items change.
|
||||
* Note that in case of `selectedValues` and `highlightedValue` the strongly typed
|
||||
* `onChange` and `onHighlightChange` callbacks are also fired.
|
||||
*/
|
||||
onStateChange?: StateChangeCallback<State>;
|
||||
/**
|
||||
* The number of items skip when using the page up and page down keys.
|
||||
*
|
||||
* @default 5
|
||||
*/
|
||||
pageSize?: number;
|
||||
/**
|
||||
* A function that tests equality between two items' values.
|
||||
* @default (a, b) => a === b
|
||||
*/
|
||||
itemComparer?: (itemValue1: ItemValue, itemValue2: ItemValue) => boolean;
|
||||
/**
|
||||
* A function that converts an object to its string representation
|
||||
* @default (o) => o
|
||||
*/
|
||||
getItemAsString?: (option: ItemValue) => string | undefined;
|
||||
/**
|
||||
* Array of list items.
|
||||
*/
|
||||
items: ItemValue[];
|
||||
/**
|
||||
* Additional data to be passed to all the reducer actions.
|
||||
* It will be available in the `context` property of the action when dispatched.
|
||||
*/
|
||||
reducerActionContext?: CustomActionContext;
|
||||
/**
|
||||
* Orientation of the items in the list.
|
||||
* Determines the actions that are performed when arrow keys are pressed.
|
||||
*/
|
||||
orientation?: 'horizontal-ltr' | 'horizontal-rtl' | 'vertical';
|
||||
/**
|
||||
* Controls how many items can be selected at once: none (the selection functionality is disabled in this case), one, or indefinitely many.
|
||||
* @default 'single'
|
||||
*/
|
||||
selectionMode?: SelectionMode;
|
||||
/**
|
||||
* Custom state reducer function. It calculates the new state (highlighted and selected items + optional custom state)
|
||||
* based on the previous one and the performed action.
|
||||
*/
|
||||
stateReducer?: (state: State, action: ActionWithContext<ListAction<ItemValue> | CustomAction, ListActionContext<ItemValue> & CustomActionContext>) => State;
|
||||
/**
|
||||
* The name of the component using useList.
|
||||
* For debugging purposes.
|
||||
* @default 'useList'
|
||||
*/
|
||||
componentName?: string;
|
||||
}
|
||||
export interface ListItemState {
|
||||
/**
|
||||
* Determines if the item is focusable (its focus is managed by the DOM).
|
||||
*/
|
||||
focusable: boolean;
|
||||
/**
|
||||
* If `true` the item is highlighted.
|
||||
*/
|
||||
highlighted: boolean;
|
||||
/**
|
||||
* If `true` the item is selected.
|
||||
*/
|
||||
selected: boolean;
|
||||
}
|
||||
interface UseListRootSlotOwnProps {
|
||||
'aria-activedescendant'?: React.AriaAttributes['aria-activedescendant'];
|
||||
onBlur: MuiCancellableEventHandler<React.FocusEvent<HTMLElement>>;
|
||||
onKeyDown: MuiCancellableEventHandler<React.KeyboardEvent<HTMLElement>>;
|
||||
tabIndex: number;
|
||||
ref: React.RefCallback<Element> | null;
|
||||
}
|
||||
export type UseListRootSlotProps<ExternalProps = {}> = ExternalProps & UseListRootSlotOwnProps;
|
||||
export interface UseListReturnValue<ItemValue, State extends ListState<ItemValue>, CustomAction extends ControllableReducerAction> {
|
||||
contextValue: ListContextValue<ItemValue>;
|
||||
dispatch: (action: CustomAction | ListAction<ItemValue>) => void;
|
||||
/**
|
||||
* Resolver for the root slot's props.
|
||||
* @param externalProps additional props for the root slot
|
||||
* @returns props that should be spread on the root slot
|
||||
*/
|
||||
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseListRootSlotProps<ExternalProps>;
|
||||
rootRef: React.RefCallback<Element> | null;
|
||||
state: State;
|
||||
}
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { UseListItemParameters, UseListItemReturnValue } from './useListItem.types';
|
||||
/**
|
||||
* Contains the logic for an item of a list-like component (for example Select, Menu, etc.).
|
||||
* It handles the item's mouse events and tab index.
|
||||
*
|
||||
* @template ItemValue The type of the item's value. This should be consistent with the type of useList's `items` parameter.
|
||||
* @ignore - internal hook.
|
||||
*/
|
||||
export declare function useListItem<ItemValue>(parameters: UseListItemParameters<ItemValue>): UseListItemReturnValue;
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
'use client';
|
||||
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import * as React from 'react';
|
||||
import { extractEventHandlers } from '../utils/extractEventHandlers';
|
||||
import { ListActionTypes } from './listActions.types';
|
||||
import { ListContext } from './ListContext';
|
||||
|
||||
/**
|
||||
* Contains the logic for an item of a list-like component (for example Select, Menu, etc.).
|
||||
* It handles the item's mouse events and tab index.
|
||||
*
|
||||
* @template ItemValue The type of the item's value. This should be consistent with the type of useList's `items` parameter.
|
||||
* @ignore - internal hook.
|
||||
*/
|
||||
export function useListItem(parameters) {
|
||||
const {
|
||||
handlePointerOverEvents = false,
|
||||
item
|
||||
} = parameters;
|
||||
const listContext = React.useContext(ListContext);
|
||||
if (!listContext) {
|
||||
throw new Error('useListItem must be used within a ListProvider');
|
||||
}
|
||||
const {
|
||||
dispatch,
|
||||
getItemState
|
||||
} = listContext;
|
||||
const {
|
||||
highlighted,
|
||||
selected,
|
||||
focusable
|
||||
} = getItemState(item);
|
||||
const createHandleClick = React.useCallback(externalHandlers => event => {
|
||||
var _externalHandlers$onC;
|
||||
(_externalHandlers$onC = externalHandlers.onClick) == null || _externalHandlers$onC.call(externalHandlers, event);
|
||||
if (event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (item === undefined) {
|
||||
throw new Error(['MUI: The `item` provided to useListItem() is undefined.', 'This should happen only during server-side rendering under React 17.'].join('\n'));
|
||||
}
|
||||
}
|
||||
dispatch({
|
||||
type: ListActionTypes.itemClick,
|
||||
item: item,
|
||||
event
|
||||
});
|
||||
}, [dispatch, item]);
|
||||
const createHandlePointerOver = React.useCallback(externalHandlers => event => {
|
||||
var _externalHandlers$onM;
|
||||
(_externalHandlers$onM = externalHandlers.onMouseOver) == null || _externalHandlers$onM.call(externalHandlers, event);
|
||||
if (event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (item === undefined) {
|
||||
throw new Error(['MUI: The `item` provided to useListItem() is undefined.', 'This should happen only during server-side rendering under React 17.'].join('\n'));
|
||||
}
|
||||
}
|
||||
dispatch({
|
||||
type: ListActionTypes.itemHover,
|
||||
item: item,
|
||||
event
|
||||
});
|
||||
}, [dispatch, item]);
|
||||
let tabIndex;
|
||||
if (focusable) {
|
||||
tabIndex = highlighted ? 0 : -1;
|
||||
}
|
||||
const getRootProps = (externalProps = {}) => {
|
||||
const externalEventHandlers = extractEventHandlers(externalProps);
|
||||
return _extends({}, externalProps, {
|
||||
onClick: createHandleClick(externalEventHandlers),
|
||||
onPointerOver: handlePointerOverEvents ? createHandlePointerOver(externalEventHandlers) : undefined,
|
||||
tabIndex
|
||||
});
|
||||
};
|
||||
return {
|
||||
getRootProps,
|
||||
highlighted,
|
||||
selected
|
||||
};
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/// <reference types="react" />
|
||||
export interface UseListItemParameters<ItemValue> {
|
||||
/**
|
||||
* If `true`, the list item will dispatch the `itemHover` action on pointer over.
|
||||
* Since the use cases for it are rare, it's disabled by default.
|
||||
* It could be used to mimic the native `select` behavior, which highlights the hovered item.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
handlePointerOverEvents?: boolean;
|
||||
/**
|
||||
* The list item.
|
||||
*/
|
||||
item: ItemValue;
|
||||
}
|
||||
interface UseListItemRootSlotOwnProps {
|
||||
onClick: React.MouseEventHandler;
|
||||
onPointerOver: React.PointerEventHandler | undefined;
|
||||
tabIndex?: number;
|
||||
}
|
||||
export type UseListItemRootSlotProps<ExternalProps = {}> = ExternalProps & UseListItemRootSlotOwnProps;
|
||||
export interface UseListItemReturnValue {
|
||||
/**
|
||||
* Resolver for the root slot's props.
|
||||
* @param externalProps additional props to be forwarded to the root slot
|
||||
* @returns props that should be spread on the root slot
|
||||
*/
|
||||
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseListItemRootSlotProps<ExternalProps>;
|
||||
/**
|
||||
* If `true`, the current item is highlighted.
|
||||
*/
|
||||
highlighted: boolean;
|
||||
/**
|
||||
* If `true`, the current item is selected.
|
||||
*/
|
||||
selected: boolean;
|
||||
}
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
Reference in new issue
Block a user