UNPKG

2.82 kBJavaScriptView Raw
1'use client';
2
3import _extends from "@babel/runtime/helpers/esm/extends";
4import * as React from 'react';
5import { extractEventHandlers } from '../utils/extractEventHandlers';
6import { ListActionTypes } from './listActions.types';
7import { ListContext } from './ListContext';
8
9/**
10 * Contains the logic for an item of a list-like component (for example Select, Menu, etc.).
11 * It handles the item's mouse events and tab index.
12 *
13 * @template ItemValue The type of the item's value. This should be consistent with the type of useList's `items` parameter.
14 * @ignore - internal hook.
15 */
16export function useListItem(parameters) {
17 const {
18 handlePointerOverEvents = false,
19 item
20 } = parameters;
21 const listContext = React.useContext(ListContext);
22 if (!listContext) {
23 throw new Error('useListItem must be used within a ListProvider');
24 }
25 const {
26 dispatch,
27 getItemState
28 } = listContext;
29 const {
30 highlighted,
31 selected,
32 focusable
33 } = getItemState(item);
34 const createHandleClick = React.useCallback(externalHandlers => event => {
35 var _externalHandlers$onC;
36 (_externalHandlers$onC = externalHandlers.onClick) == null || _externalHandlers$onC.call(externalHandlers, event);
37 if (event.defaultPrevented) {
38 return;
39 }
40 if (process.env.NODE_ENV !== 'production') {
41 if (item === undefined) {
42 throw new Error(['MUI: The `item` provided to useListItem() is undefined.', 'This should happen only during server-side rendering under React 17.'].join('\n'));
43 }
44 }
45 dispatch({
46 type: ListActionTypes.itemClick,
47 item: item,
48 event
49 });
50 }, [dispatch, item]);
51 const createHandlePointerOver = React.useCallback(externalHandlers => event => {
52 var _externalHandlers$onM;
53 (_externalHandlers$onM = externalHandlers.onMouseOver) == null || _externalHandlers$onM.call(externalHandlers, event);
54 if (event.defaultPrevented) {
55 return;
56 }
57 if (process.env.NODE_ENV !== 'production') {
58 if (item === undefined) {
59 throw new Error(['MUI: The `item` provided to useListItem() is undefined.', 'This should happen only during server-side rendering under React 17.'].join('\n'));
60 }
61 }
62 dispatch({
63 type: ListActionTypes.itemHover,
64 item: item,
65 event
66 });
67 }, [dispatch, item]);
68 let tabIndex;
69 if (focusable) {
70 tabIndex = highlighted ? 0 : -1;
71 }
72 const getRootProps = (externalProps = {}) => {
73 const externalEventHandlers = extractEventHandlers(externalProps);
74 return _extends({}, externalProps, {
75 onClick: createHandleClick(externalEventHandlers),
76 onPointerOver: handlePointerOverEvents ? createHandlePointerOver(externalEventHandlers) : undefined,
77 tabIndex
78 });
79 };
80 return {
81 getRootProps,
82 highlighted,
83 selected
84 };
85}
\No newline at end of file