index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
|---|---|---|---|---|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useCompound/useCompoundItem.ts
|
'use client';
import * as React from 'react';
import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';
import {
CompoundComponentContext,
CompoundComponentContextValue,
KeyGenerator,
} from './useCompoundParent';
export interface UseCompoundItemReturnValue<Key> {
/**
* The unique key for the child component.
* If the id was provided to `useCompoundItem`, this will be the same value.
* Otherwise, this will be a value generated by the `missingKeyGenerator`.
*/
id: Key | undefined;
/**
* The 0-based index of the child component in the parent component's list of registered children.
*/
index: number;
/**
* The total number of child components registered with the parent component.
* This value will be correct after the effect phase of the component (as children are registered with the parent during the effect phase).
*/
totalItemCount: number;
}
/**
* Registers a child component with the parent component.
*
* @param id A unique key for the child component. If the `id` is `undefined`, the registration logic will not run (this can sometimes be the case during SSR).
* This can be either a value, or a function that generates a value based on already registered siblings' ids.
* @param itemMetadata Arbitrary metadata to pass to the parent component. This should be a stable reference (e.g. a memoized object), to avoid unnecessary re-registrations.
* @param missingKeyGenerator A function that generates a unique id for the item.
* It is called with the set of the ids of all the items that have already been registered.
* Return `existingKeys.size` if you want to use the index of the new item as the id.
*
* @ignore - internal hook.
*/
export function useCompoundItem<Key, Subitem>(
id: Key | KeyGenerator<Key>,
itemMetadata: Subitem,
): UseCompoundItemReturnValue<Key> {
const context = React.useContext(CompoundComponentContext) as CompoundComponentContextValue<
Key,
Subitem
>;
if (context === null) {
throw new Error('useCompoundItem must be used within a useCompoundParent');
}
const { registerItem } = context;
const [registeredId, setRegisteredId] = React.useState(typeof id === 'function' ? undefined : id);
useEnhancedEffect(() => {
const { id: returnedId, deregister } = registerItem(id, itemMetadata);
setRegisteredId(returnedId);
return deregister;
}, [registerItem, itemMetadata, id]);
return {
id: registeredId,
index: registeredId !== undefined ? context.getItemIndex(registeredId) : -1,
totalItemCount: context.totalSubitemCount,
};
}
| 6,300
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useCompound/useCompoundParent.ts
|
'use client';
import * as React from 'react';
interface RegisterItemReturnValue<Key> {
/**
* The id of the item.
* If the `id` was `undefined`, an id from the `missingKeyGenerator` will be used.
*/
id: Key;
/**
* A function that deregisters the item.
*/
deregister: () => void;
}
export type KeyGenerator<Key> = (existingKeys: Set<Key>) => Key;
export type CompoundComponentContextValue<Key, Subitem> = {
/**
* Registers an item with the parent.
* This should be called during the effect phase of the child component.
* The `itemMetadata` should be a stable reference (e.g. a memoized object), to avoid unnecessary re-registrations.
*
* @param id Id of the item or A function that generates a unique id for the item.
* It is called with the set of the ids of all the items that have already been registered.
* Return `existingKeys.size` if you want to use the index of the new item as the id..
* @param itemMetadata Arbitrary metadata to pass to the parent component.
*/
registerItem: (id: Key | KeyGenerator<Key>, item: Subitem) => RegisterItemReturnValue<Key>;
/**
* Returns the 0-based index of the item in the parent component's list of registered items.
*
* @param id id of the item.
*/
getItemIndex: (id: Key) => number;
/**
* The total number of items registered with the parent.
*/
totalSubitemCount: number;
};
export const CompoundComponentContext = React.createContext<CompoundComponentContextValue<
any,
any
> | null>(null);
CompoundComponentContext.displayName = 'CompoundComponentContext';
export interface UseCompoundParentReturnValue<Key, Subitem extends { ref: React.RefObject<Node> }> {
/**
* The value for the CompoundComponentContext provider.
*/
contextValue: CompoundComponentContextValue<Key, Subitem>;
/**
* The subitems registered with the parent.
* The key is the id of the subitem, and the value is the metadata passed to the `useCompoundItem` hook.
* The order of the items is the same as the order in which they were registered.
*/
subitems: Map<Key, Subitem>;
}
/**
* Sorts the subitems by their position in the DOM.
*/
function sortSubitems<Key, Subitem extends { ref: React.RefObject<Node> }>(
subitems: Map<Key, Subitem>,
) {
const subitemsArray = Array.from(subitems.keys()).map((key) => {
const subitem = subitems.get(key)!;
return { key, subitem };
});
subitemsArray.sort((a, b) => {
const aNode = a.subitem.ref.current;
const bNode = b.subitem.ref.current;
if (aNode === null || bNode === null || aNode === bNode) {
return 0;
}
// eslint-disable-next-line no-bitwise
return aNode.compareDocumentPosition(bNode) & Node.DOCUMENT_POSITION_PRECEDING ? 1 : -1;
});
return new Map(subitemsArray.map((item) => [item.key, item.subitem]));
}
/**
* Provides a way for a component to know about its children.
*
* Child components register themselves with the `useCompoundItem` hook, passing in arbitrary metadata to the parent.
*
* This is a more powerful altervantive to `children` traversal, as child components don't have to be placed
* directly inside the parent component. They can be anywhere in the tree (and even rendered by other components).
*
* The downside is that this doesn't work with SSR as it relies on the useEffect hook.
*
* @ignore - internal hook.
*/
export function useCompoundParent<
Key,
Subitem extends { ref: React.RefObject<Node> },
>(): UseCompoundParentReturnValue<Key, Subitem> {
const [subitems, setSubitems] = React.useState(new Map<Key, Subitem>());
const subitemKeys = React.useRef(new Set<Key>());
const deregisterItem = React.useCallback(function deregisterItem(id: Key) {
subitemKeys.current.delete(id);
setSubitems((previousState) => {
const newState = new Map(previousState);
newState.delete(id);
return newState;
});
}, []);
const registerItem = React.useCallback(
function registerItem(id: Key | KeyGenerator<Key>, item: Subitem) {
let providedOrGeneratedId: Key;
if (typeof id === 'function') {
providedOrGeneratedId = (id as KeyGenerator<Key>)(subitemKeys.current);
} else {
providedOrGeneratedId = id;
}
subitemKeys.current.add(providedOrGeneratedId);
setSubitems((previousState) => {
const newState = new Map(previousState);
newState.set(providedOrGeneratedId, item);
return newState;
});
return {
id: providedOrGeneratedId,
deregister: () => deregisterItem(providedOrGeneratedId),
};
},
[deregisterItem],
);
const sortedSubitems = React.useMemo(() => sortSubitems(subitems), [subitems]);
const getItemIndex = React.useCallback(
function getItemIndex(id: Key) {
return Array.from(sortedSubitems.keys()).indexOf(id);
},
[sortedSubitems],
);
const contextValue = React.useMemo(
() => ({
getItemIndex,
registerItem,
totalSubitemCount: subitems.size,
}),
[getItemIndex, registerItem, subitems.size],
);
return {
contextValue,
subitems: sortedSubitems,
};
}
| 6,301
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useDropdown/DropdownContext.ts
|
import * as React from 'react';
import { DropdownAction, DropdownState } from './useDropdown.types';
export interface DropdownContextValue {
dispatch: React.Dispatch<DropdownAction>;
popupId: string;
registerPopup: (popupId: string) => void;
registerTrigger: (element: HTMLElement | null) => void;
state: DropdownState;
triggerElement: HTMLElement | null;
}
const DropdownContext = React.createContext<DropdownContextValue | null>(null);
export { DropdownContext };
| 6,302
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useDropdown/dropdownReducer.ts
|
import { DropdownAction, DropdownActionTypes, DropdownState } from './useDropdown.types';
export function dropdownReducer(state: DropdownState, action: DropdownAction): DropdownState {
switch (action.type) {
case DropdownActionTypes.blur:
return { open: false };
case DropdownActionTypes.escapeKeyDown:
return { open: false };
case DropdownActionTypes.toggle:
return { open: !state.open };
case DropdownActionTypes.open:
return { open: true };
case DropdownActionTypes.close:
return { open: false };
default:
throw new Error(`Unhandled action`);
}
}
| 6,303
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useDropdown/index.ts
|
'use client';
export * from './useDropdown';
export * from './useDropdown.types';
export * from './DropdownContext';
| 6,304
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useDropdown/useDropdown.ts
|
'use client';
import * as React from 'react';
import type { DropdownContextValue } from './DropdownContext';
import { useControllableReducer } from '../utils/useControllableReducer';
import { StateChangeCallback } from '../utils/useControllableReducer.types';
import { DropdownActionTypes, DropdownState, UseDropdownParameters } from './useDropdown.types';
import { dropdownReducer } from './dropdownReducer';
/**
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/#hooks)
*
* API:
*
* - [useDropdown API](https://mui.com/base-ui/react-menu/hooks-api/#use-dropdown)
*/
export function useDropdown(parameters: UseDropdownParameters = {}) {
const { defaultOpen, onOpenChange, open: openProp } = parameters;
const [popupId, setPopupId] = React.useState<string>('');
const [triggerElement, setTriggerElement] = React.useState<HTMLElement | null>(null);
const lastActionType = React.useRef<string | null>(null);
const handleStateChange: StateChangeCallback<DropdownState> = React.useCallback(
(event, field, value, reason) => {
if (field === 'open') {
onOpenChange?.(event as React.MouseEvent | React.KeyboardEvent | React.FocusEvent, value);
}
lastActionType.current = reason;
},
[onOpenChange],
);
const controlledProps = React.useMemo(
() => (openProp !== undefined ? { open: openProp } : {}),
[openProp],
);
const [state, dispatch] = useControllableReducer({
controlledProps,
initialState: defaultOpen ? { open: true } : { open: false },
onStateChange: handleStateChange,
reducer: dropdownReducer,
});
React.useEffect(() => {
if (
!state.open &&
lastActionType.current !== null &&
lastActionType.current !== DropdownActionTypes.blur
) {
triggerElement?.focus();
}
}, [state.open, triggerElement]);
const contextValue: DropdownContextValue = {
state,
dispatch,
popupId,
registerPopup: setPopupId,
registerTrigger: setTriggerElement,
triggerElement,
};
return {
contextValue,
open: state.open,
};
}
| 6,305
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useDropdown/useDropdown.types.ts
|
import type { DropdownContextValue } from './DropdownContext';
export interface UseDropdownParameters {
/**
* If `true`, the dropdown is initially open.
*/
defaultOpen?: boolean;
/**
* Callback fired when the component requests to be opened or closed.
*/
onOpenChange?: (
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null,
open: boolean,
) => void;
/**
* Allows to control whether the dropdown is open.
* This is a controlled counterpart of `defaultOpen`.
*/
open?: boolean;
}
export interface UseDropdownReturnValue {
/**
* The value to be passed into the DropdownContext provider.
*/
contextValue: DropdownContextValue;
/**
* If `true`, the dropdown is open.
*/
open: boolean;
}
export const DropdownActionTypes = {
blur: 'dropdown:blur',
escapeKeyDown: 'dropdown:escapeKeyDown',
toggle: 'dropdown:toggle',
open: 'dropdown:open',
close: 'dropdown:close',
} as const;
interface DropdownBlurAction {
type: typeof DropdownActionTypes.blur;
event: React.FocusEvent;
}
interface DropdownEscapeKeyDownAction {
type: typeof DropdownActionTypes.escapeKeyDown;
event: React.KeyboardEvent;
}
interface DropdownToggleAction {
type: typeof DropdownActionTypes.toggle;
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null;
}
interface DropdownOpenAction {
type: typeof DropdownActionTypes.open;
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null;
}
interface DropdownCloseAction {
type: typeof DropdownActionTypes.close;
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null;
}
export type DropdownAction =
| DropdownBlurAction
| DropdownEscapeKeyDownAction
| DropdownToggleAction
| DropdownOpenAction
| DropdownCloseAction;
export type DropdownState = { open: boolean };
| 6,306
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useInput/index.ts
|
'use client';
export { useInput } from './useInput';
export * from './useInput.types';
| 6,307
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useInput/useInput.test.tsx
|
import * as React from 'react';
import { act, createRenderer } from '@mui-internal/test-utils';
import { expect } from 'chai';
import { spy } from 'sinon';
import { useInput } from './useInput';
import { UseInputParameters } from './useInput.types';
describe('useInput', () => {
const { render } = createRenderer();
describe('params: inputRef', () => {
it('should be able to attach input ref passed through params', () => {
const inputRef = React.createRef<HTMLInputElement>();
function Input() {
const { getInputProps } = useInput({
inputRef,
});
return <input {...getInputProps()} />;
}
const { getByRole } = render(<Input />);
expect(inputRef.current).to.deep.equal(getByRole('textbox'));
});
});
describe('prop: disabled', () => {
it('should render a disabled <input />', () => {
function Input(props: { disabled: boolean }) {
const { getInputProps } = useInput({
disabled: props.disabled,
});
return <input {...getInputProps()} />;
}
const { getByRole } = render(<Input disabled />);
const input = getByRole('textbox');
expect(input).to.have.attribute('disabled');
});
it('should reset the focused state if getting disabled', () => {
const handleBlur = spy();
const handleFocus = spy();
function Input(props: UseInputParameters) {
const { getInputProps } = useInput(props);
return <input {...getInputProps()} />;
}
const { getByRole, setProps } = render(<Input onBlur={handleBlur} onFocus={handleFocus} />);
act(() => {
getByRole('textbox').focus();
});
expect(handleFocus.callCount).to.equal(1);
setProps({ disabled: true });
expect(handleBlur.callCount).to.equal(1);
// check if focus not initiated again
expect(handleFocus.callCount).to.equal(1);
});
});
describe('external props', () => {
it('prop getter functions should forward arbitrary props to the corresponding slot', () => {
const rootRef = React.createRef<HTMLDivElement>();
function Input() {
const { getRootProps, getInputProps } = useInput();
return (
<div {...getRootProps({ 'data-testid': 'test-root-slot', ref: rootRef })}>
<input {...getInputProps({ 'data-testid': 'test-input-slot' })} />
</div>
);
}
const { getByRole } = render(<Input />);
expect(rootRef.current).to.have.attribute('data-testid', 'test-root-slot');
expect(getByRole('textbox')).to.have.attribute('data-testid', 'test-input-slot');
});
});
});
| 6,308
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useInput/useInput.ts
|
'use client';
import * as React from 'react';
import MuiError from '@mui/utils/macros/MuiError.macro';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import { FormControlState, useFormControlContext } from '../FormControl';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import {
UseInputInputSlotProps,
UseInputParameters,
UseInputRootSlotProps,
UseInputReturnValue,
} from './useInput.types';
/**
*
* Demos:
*
* - [Input](https://mui.com/base-ui/react-input/#hook)
*
* API:
*
* - [useInput API](https://mui.com/base-ui/react-input/hooks-api/#use-input)
*/
export function useInput(parameters: UseInputParameters = {}): UseInputReturnValue {
const {
defaultValue: defaultValueProp,
disabled: disabledProp = false,
error: errorProp = false,
onBlur,
onChange,
onFocus,
required: requiredProp = false,
value: valueProp,
inputRef: inputRefProp,
} = parameters;
const formControlContext: FormControlState | undefined = useFormControlContext();
let defaultValue: unknown;
let disabled: boolean;
let error: boolean;
let required: boolean;
let value: unknown;
if (formControlContext) {
defaultValue = undefined;
disabled = formControlContext.disabled ?? false;
error = formControlContext.error ?? false;
required = formControlContext.required ?? false;
value = formControlContext.value;
if (process.env.NODE_ENV !== 'production') {
const definedLocalProps = (
['defaultValue', 'disabled', 'error', 'required', 'value'] as const
).filter((prop) => parameters[prop] !== undefined);
if (definedLocalProps.length > 0) {
console.warn(
[
'MUI: You have set props on an input that is inside a FormControl.',
'Set these props on a FormControl instead. Otherwise they will be ignored.',
`Ignored props: ${definedLocalProps.join(', ')}`,
].join('\n'),
);
}
}
} else {
defaultValue = defaultValueProp;
disabled = disabledProp;
error = errorProp;
required = requiredProp;
value = valueProp;
}
const { current: isControlled } = React.useRef(value != null);
const handleInputRefWarning = React.useCallback((instance: HTMLElement) => {
if (process.env.NODE_ENV !== 'production') {
if (instance && instance.nodeName !== 'INPUT' && !instance.focus) {
console.error(
[
'MUI: You have provided a `slots.input` to the input component',
'that does not correctly handle the `ref` prop.',
'Make sure the `ref` prop is called with a HTMLInputElement.',
].join('\n'),
);
}
}
}, []);
const inputRef = React.useRef<HTMLInputElement>(null);
const handleInputRef = useForkRef(inputRef, inputRefProp, handleInputRefWarning);
const [focused, setFocused] = React.useState(false);
// The blur won't fire when the disabled state is set on a focused input.
// We need to book keep the focused state manually.
React.useEffect(() => {
if (!formControlContext && disabled && focused) {
setFocused(false);
// @ts-ignore
onBlur?.();
}
}, [formControlContext, disabled, focused, onBlur]);
const handleFocus =
(otherHandlers: Record<string, React.EventHandler<any> | undefined>) =>
(event: React.FocusEvent<HTMLInputElement>) => {
// Fix a bug with IE11 where the focus/blur events are triggered
// while the component is disabled.
if (formControlContext?.disabled) {
event.stopPropagation();
return;
}
otherHandlers.onFocus?.(event);
if (formControlContext && formControlContext.onFocus) {
formControlContext?.onFocus?.();
} else {
setFocused(true);
}
};
const handleBlur =
(otherHandlers: Record<string, React.EventHandler<any> | undefined>) =>
(event: React.FocusEvent<HTMLInputElement>) => {
otherHandlers.onBlur?.(event);
if (formControlContext && formControlContext.onBlur) {
formControlContext.onBlur();
} else {
setFocused(false);
}
};
const handleChange =
(otherHandlers: Record<string, React.EventHandler<any> | undefined>) =>
(event: React.ChangeEvent<HTMLInputElement>, ...args: unknown[]) => {
if (!isControlled) {
const element = event.target || inputRef.current;
if (element == null) {
throw new MuiError(
'MUI: Expected valid input target. ' +
'Did you use a custom `slots.input` and forget to forward refs? ' +
'See https://mui.com/r/input-component-ref-interface for more info.',
);
}
}
formControlContext?.onChange?.(event);
// @ts-ignore
otherHandlers.onChange?.(event, ...args);
};
const handleClick =
(otherHandlers: Record<string, React.EventHandler<any>>) =>
(event: React.MouseEvent<HTMLInputElement>) => {
if (inputRef.current && event.currentTarget === event.target) {
inputRef.current.focus();
}
otherHandlers.onClick?.(event);
};
const getRootProps = <ExternalProps extends Record<string, any> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseInputRootSlotProps<ExternalProps> => {
// onBlur, onChange and onFocus are forwarded to the input slot.
const propsEventHandlers = extractEventHandlers(parameters, ['onBlur', 'onChange', 'onFocus']);
const externalEventHandlers = { ...propsEventHandlers, ...extractEventHandlers(externalProps) };
return {
...externalProps,
...externalEventHandlers,
onClick: handleClick(externalEventHandlers),
};
};
const getInputProps = <ExternalProps extends Record<string, any> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseInputInputSlotProps<ExternalProps> => {
const propsEventHandlers: Record<string, React.EventHandler<any> | undefined> = {
onBlur,
onChange,
onFocus,
};
const externalEventHandlers = { ...propsEventHandlers, ...extractEventHandlers(externalProps) };
const mergedEventHandlers = {
...externalEventHandlers,
onBlur: handleBlur(externalEventHandlers),
onChange: handleChange(externalEventHandlers),
onFocus: handleFocus(externalEventHandlers),
};
return {
...mergedEventHandlers,
'aria-invalid': error || undefined,
defaultValue: defaultValue as string | number | readonly string[] | undefined,
value: value as string | number | readonly string[] | undefined,
required,
disabled,
...externalProps,
ref: handleInputRef,
...mergedEventHandlers,
};
};
return {
disabled,
error,
focused,
formControlContext,
getInputProps,
getRootProps,
inputRef: handleInputRef,
required,
value,
};
}
| 6,309
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useInput/useInput.types.ts
|
import * as React from 'react';
import { FormControlState } from '../FormControl';
export interface UseInputParameters {
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: unknown;
/**
* If `true`, the component is disabled.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
disabled?: boolean;
/**
* If `true`, the `input` will indicate an error by setting the `aria-invalid` attribute.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
error?: boolean;
onBlur?: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;
onClick?: React.MouseEventHandler;
onChange?: React.ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>;
onFocus?: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;
inputRef?: React.Ref<HTMLInputElement | HTMLTextAreaElement>;
/**
* If `true`, the `input` element is required.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
required?: boolean;
value?: unknown;
}
export interface UseInputRootSlotOwnProps {
onClick: React.MouseEventHandler | undefined;
}
export type UseInputRootSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseInputRootSlotOwnProps | 'onBlur' | 'onChange' | 'onFocus'
> &
UseInputRootSlotOwnProps;
export interface UseInputInputSlotOwnProps {
'aria-invalid': React.AriaAttributes['aria-invalid'];
defaultValue: string | number | readonly string[] | undefined;
ref: React.RefCallback<HTMLInputElement | HTMLTextAreaElement> | null;
value: string | number | readonly string[] | undefined;
onBlur: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;
onChange: React.ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>;
onFocus: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;
required: boolean;
disabled: boolean;
}
export type UseInputInputSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseInputInputSlotOwnProps
> &
UseInputInputSlotOwnProps;
export interface UseInputReturnValue {
/**
* If `true`, the component will be disabled.
*/
disabled: boolean;
/**
* If `true`, the `input` will indicate an error by setting the `aria-invalid` attribute.
*/
error: boolean;
/**
* If `true`, the `input` will be focused.
*/
focused: boolean;
/**
* Return value from the `useFormControlContext` hook.
*/
formControlContext: FormControlState | undefined;
/**
* Resolver for the input slot's props.
* @param externalProps props for the input slot
* @returns props that should be spread on the input slot
*/
getInputProps: <ExternalProps extends Record<string, any> = {}>(
externalProps?: ExternalProps,
) => UseInputInputSlotProps<ExternalProps>;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, any> = {}>(
externalProps?: ExternalProps,
) => UseInputRootSlotProps<ExternalProps>;
inputRef: React.RefCallback<HTMLInputElement | HTMLTextAreaElement> | null;
/**
* If `true`, the `input` will indicate that it's required.
*/
required: boolean;
/**
* The `value` of the `input` element.
*/
value: unknown;
}
| 6,310
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/ListContext.ts
|
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 const ListContext = React.createContext<ListContextValue<any> | null>(null);
if (process.env.NODE_ENV !== 'production') {
ListContext.displayName = 'ListContext';
}
| 6,311
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/index.ts
|
'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';
| 6,312
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/listActions.types.ts
|
export const ListActionTypes = {
blur: 'list:blur',
focus: 'list:focus',
itemClick: 'list:itemClick',
itemHover: 'list:itemHover',
itemsChange: 'list:itemsChange',
keyDown: 'list:keyDown',
resetHighlight: 'list:resetHighlight',
textNavigation: 'list:textNavigation',
clearSelection: 'list:clearSelection',
} as const;
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 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
| TextNavigationAction
| ClearSelectionAction;
| 6,313
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/listReducer.test.ts
|
import * as React from 'react';
import { expect } from 'chai';
import { listReducer } from './listReducer';
import { ListReducerAction, ListState } from './useList.types';
import { ListActionTypes } from './listActions.types';
describe('listReducer', () => {
describe('action: blur', () => {
it('resets the highlightedValue', () => {
const state: ListState<string> = {
highlightedValue: 'a',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.blur,
event: {} as any, // not relevant
context: {
items: [],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal(null);
});
});
describe('action: itemClick', () => {
it('sets the selectedValues to the clicked value', () => {
const state: ListState<string> = {
highlightedValue: 'a',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemClick,
event: {} as any, // not relevant
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
item: 'two',
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['two']);
});
it('does not select a disabled item', () => {
const state: ListState<string> = {
highlightedValue: null,
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemClick,
event: {} as any, // not relevant
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: (item) => item === 'two',
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
item: 'two',
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal(null);
expect(result.selectedValues).to.deep.equal([]);
});
it('replaces the selectedValues with the clicked value if selectionMode = "single"', () => {
const state: ListState<string> = {
highlightedValue: 'a',
selectedValues: ['one'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemClick,
event: {} as any, // not relevant
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
item: 'two',
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['two']);
});
it('add the clicked value to the selection if selectionMode = "multiple"', () => {
const state: ListState<string> = {
highlightedValue: 'one',
selectedValues: ['one'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemClick,
event: {} as any, // not relevant
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'multiple',
},
item: 'two',
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['one', 'two']);
});
it('remove the clicked value from the selection if selectionMode = "multiple" and it was selected already', () => {
const state: ListState<string> = {
highlightedValue: 'three',
selectedValues: ['one', 'two'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemClick,
event: {} as any, // not relevant
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'multiple',
},
item: 'two',
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['one']);
});
it('does not select the clicked value to the selection if selectionMode = "none"', () => {
const state: ListState<string> = {
highlightedValue: 'one',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemClick,
event: {} as any, // not relevant
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'none',
},
item: 'two',
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal([]);
});
});
describe('action: keyDown', () => {
interface KeydownTestCase {
description: string;
key: string;
initialHighlightedItem: string | null;
disabledItemFocusable: boolean;
disabledItems: string[];
disableListWrap: boolean;
expected: string | null;
}
const testCases: KeydownTestCase[] = [
{
description: 'happy path',
key: 'Home',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '1',
},
{
description: 'highlights the first enabled item',
key: 'Home',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['1'],
disableListWrap: false,
expected: '2',
},
{
description: 'highlights the first enabled item',
key: 'Home',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['1', '2'],
disableListWrap: false,
expected: '3',
},
{
description: 'highlights the first item even if it is disabled',
key: 'Home',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['1'],
disableListWrap: false,
expected: '1',
},
{
description: 'all disabled',
key: 'Home',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: null,
},
{
description: 'all disabled but focusable',
key: 'Home',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: '1',
},
{
description: 'happy path',
key: 'End',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '5',
},
{
description: 'highlights the last enabled item',
key: 'End',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['5'],
disableListWrap: false,
expected: '4',
},
{
description: 'highlights the last enabled item',
key: 'End',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['4', '5'],
disableListWrap: false,
expected: '3',
},
{
description: 'highlights the last item even if it is disabled',
key: 'End',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['5'],
disableListWrap: false,
expected: '5',
},
{
description: 'all disabled',
key: 'End',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: null,
},
{
description: 'all disabled but focusable',
key: 'End',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: '5',
},
{
description: 'happy path',
key: 'ArrowDown',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '1',
},
{
description: 'happy path',
key: 'ArrowDown',
initialHighlightedItem: '1',
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '2',
},
{
description: 'skips the disabled item',
key: 'ArrowDown',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['1'],
disableListWrap: false,
expected: '2',
},
{
description: 'skips multiple disabled items',
key: 'ArrowDown',
initialHighlightedItem: '1',
disabledItemFocusable: false,
disabledItems: ['2', '3'],
disableListWrap: false,
expected: '4',
},
{
description: 'skips the disabled items and wraps around',
key: 'ArrowDown',
initialHighlightedItem: '3',
disabledItemFocusable: false,
disabledItems: ['1', '4', '5'],
disableListWrap: false,
expected: '2',
},
{
description: 'focuses the disabled item',
key: 'ArrowDown',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['1'],
disableListWrap: false,
expected: '1',
},
{
description: 'does not wrap around',
key: 'ArrowDown',
initialHighlightedItem: '5',
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: true,
expected: '5',
},
{
description: 'remains on the same item when all the next are disabled',
key: 'ArrowDown',
initialHighlightedItem: '3',
disabledItemFocusable: false,
disabledItems: ['4', '5'],
disableListWrap: true,
expected: '3',
},
{
description: 'all disabled',
key: 'ArrowDown',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: null,
},
{
description: 'all disabled but focusable',
key: 'ArrowDown',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: '1',
},
{
description: 'happy path',
key: 'ArrowUp',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '5',
},
{
description: 'happy path',
key: 'ArrowUp',
initialHighlightedItem: '2',
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '1',
},
{
description: 'skips the disabled item',
key: 'ArrowUp',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['5'],
disableListWrap: false,
expected: '4',
},
{
description: 'skips multiple disabled items',
key: 'ArrowUp',
initialHighlightedItem: '1',
disabledItemFocusable: false,
disabledItems: ['4', '5'],
disableListWrap: false,
expected: '3',
},
{
description: 'skips the disabled items and wraps around',
key: 'ArrowUp',
initialHighlightedItem: '2',
disabledItemFocusable: false,
disabledItems: ['1', '4', '5'],
disableListWrap: false,
expected: '3',
},
{
description: 'focuses the disabled item',
key: 'ArrowUp',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['5'],
disableListWrap: false,
expected: '5',
},
{
description: 'does not wrap around',
key: 'ArrowUp',
initialHighlightedItem: '1',
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: true,
expected: '1',
},
{
description: 'remains on the same item when all the previous are disabled',
key: 'ArrowUp',
initialHighlightedItem: '3',
disabledItemFocusable: false,
disabledItems: ['1', '2'],
disableListWrap: true,
expected: '3',
},
{
description: 'all disabled',
key: 'ArrowUp',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: null,
},
{
description: 'all disabled but focusable',
key: 'ArrowUp',
initialHighlightedItem: null,
disabledItemFocusable: true,
disabledItems: ['1', '2', '3', '4', '5'],
disableListWrap: false,
expected: '5',
},
{
description: 'happy path',
key: 'PageDown',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '3',
},
{
description: 'skips the disabled item',
key: 'PageDown',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: ['3'],
disableListWrap: false,
expected: '4',
},
{
description: 'does not wrap around, no matter the setting',
key: 'PageDown',
initialHighlightedItem: '4',
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '5',
},
{
description: 'does not wrap around, no matter the setting, and skips the disabled item',
key: 'PageDown',
initialHighlightedItem: '3',
disabledItemFocusable: false,
disabledItems: ['5'],
disableListWrap: false,
expected: '4',
},
{
description: 'happy path',
key: 'PageUp',
initialHighlightedItem: null,
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '1',
},
{
description: 'skips the disabled item',
key: 'PageUp',
initialHighlightedItem: '5',
disabledItemFocusable: false,
disabledItems: ['2'],
disableListWrap: false,
expected: '1',
},
{
description: 'does not wrap around, no matter the setting',
key: 'PageUp',
initialHighlightedItem: '2',
disabledItemFocusable: false,
disabledItems: [],
disableListWrap: false,
expected: '1',
},
{
description: 'does not wrap around, no matter the setting, and skips the disabled item',
key: 'PageUp',
initialHighlightedItem: '3',
disabledItemFocusable: false,
disabledItems: ['1'],
disableListWrap: false,
expected: '2',
},
];
testCases.forEach((spec: KeydownTestCase) => {
describe(`given initialHighlightedItem: '${
spec.initialHighlightedItem
}', disabledItemsFocusable: ${spec.disabledItemFocusable}, disableListWrap: ${
spec.disableListWrap
}, disabledItems: [${spec.disabledItems.join()}]`, () => {
it(`${spec.description}: should highlight the '${spec.expected}' item after the ${spec.key} is pressed`, () => {
const state: ListState<string> = {
highlightedValue: spec.initialHighlightedItem,
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.keyDown,
key: spec.key,
event: null as any, // not relevant
context: {
items: ['1', '2', '3', '4', '5'],
disableListWrap: spec.disableListWrap,
disabledItemsFocusable: spec.disabledItemFocusable,
focusManagement: 'activeDescendant',
isItemDisabled: (item) => spec.disabledItems.includes(item),
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 3,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal(spec.expected);
});
});
});
describe('Enter key is pressed', () => {
it('selects the highlighted option', () => {
const state: ListState<string> = {
highlightedValue: 'two',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.keyDown,
key: 'Enter',
event: {} as any,
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['two']);
});
it('replaces the selectedValues with the highlighted value if selectionMode = "single"', () => {
const state: ListState<string> = {
highlightedValue: 'two',
selectedValues: ['one'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.keyDown,
key: 'Enter',
event: {} as any,
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['two']);
});
it('add the highlighted value to the selection if selectionMode = "multiple"', () => {
const state: ListState<string> = {
highlightedValue: 'two',
selectedValues: ['one'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.keyDown,
key: 'Enter',
event: {} as any,
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'multiple',
},
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['one', 'two']);
});
});
});
describe('action: textNavigation', () => {
it('should navigate to next match', () => {
const state: ListState<string> = {
highlightedValue: 'two',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.textNavigation,
searchString: 'th',
event: {} as React.KeyboardEvent,
context: {
items: ['one', 'two', 'three', 'four', 'five'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('three');
});
it('should not move the highlight when there are no matched items', () => {
const state: ListState<string> = {
highlightedValue: 'one',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.textNavigation,
searchString: 'z',
event: {} as React.KeyboardEvent,
context: {
items: ['one', 'two', 'three', 'four', 'five'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('one');
});
it('should highlight first match that is not disabled', () => {
const state: ListState<string> = {
highlightedValue: 'one',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.textNavigation,
searchString: 't',
event: {} as React.KeyboardEvent,
context: {
items: ['one', 'two', 'three', 'four', 'five'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: (_, i) => i === 1,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('three');
});
it('should move highlight to disabled items if disabledItemsFocusable=true', () => {
const state: ListState<string> = {
highlightedValue: 'one',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.textNavigation,
searchString: 't',
event: {} as React.KeyboardEvent,
context: {
items: ['one', 'two', 'three', 'four', 'five'],
disableListWrap: false,
disabledItemsFocusable: true,
focusManagement: 'activeDescendant',
isItemDisabled: (_, i) => i === 1,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('two');
});
it('should not move highlight when disabled wrap and match is before highlighted option', () => {
const state: ListState<string> = {
highlightedValue: 'three',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.textNavigation,
searchString: 'one',
event: {} as React.KeyboardEvent,
context: {
items: ['one', 'two', 'three', 'four', 'five'],
disableListWrap: true,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'single',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('three');
});
});
describe('action: itemsChange', () => {
const irrelevantConfig = {
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant' as const,
isItemDisabled: () => false,
getItemAsString: (option: any) => option,
orientation: 'vertical' as const,
pageSize: 5,
selectionMode: 'single' as const,
};
describe('using default item comparer', () => {
it('keeps the highlighted value if it is present among the new items', () => {
const state: ListState<string> = {
highlightedValue: '1',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemsChange,
event: null,
items: ['1', '2'],
previousItems: ['0', '1', '2'],
context: {
items: ['1', '2'],
itemComparer: (o, v) => o === v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('1');
});
it('resets the highlighted value if it is not present among the new items', () => {
const state: ListState<string> = {
highlightedValue: '0',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemsChange,
event: null,
items: ['1', '2'],
previousItems: ['0', '1', '2'],
context: {
items: ['1', '2'],
itemComparer: (o, v) => o === v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal(null);
});
it('keeps the selected values if they are present among the new items', () => {
const state: ListState<string> = {
highlightedValue: '1',
selectedValues: ['1', '2'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemsChange,
event: null,
items: ['1', '2'],
previousItems: ['0', '1', '2'],
context: {
items: ['1', '2'],
itemComparer: (o, v) => o === v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['1', '2']);
});
it('removes the values from the selection if they are no longer present among the new items', () => {
const state: ListState<string> = {
highlightedValue: '1',
selectedValues: ['0', '2'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemsChange,
event: null,
items: ['1', '2'],
previousItems: ['0', '1', '2'],
context: {
items: ['1', '2'],
itemComparer: (o, v) => o === v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal(['2']);
});
});
describe('using custom item comparer', () => {
type ItemType = { v: string };
it('keeps the highlighted value if it is present among the new items', () => {
const state: ListState<ItemType> = {
highlightedValue: { v: '1' },
selectedValues: [],
};
const action: ListReducerAction<ItemType> = {
type: ListActionTypes.itemsChange,
event: null,
items: [{ v: '1' }, { v: '2' }],
previousItems: [{ v: '0' }, { v: '1' }, { v: '2' }],
context: {
items: [{ v: '1' }, { v: '2' }],
itemComparer: (a, b) => a.v === b.v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.highlightedValue?.v).to.equal('1');
});
it('resets the highlighted value if it is not present among the new items', () => {
const state: ListState<ItemType> = {
highlightedValue: { v: '0' },
selectedValues: [],
};
const action: ListReducerAction<ItemType> = {
type: ListActionTypes.itemsChange,
event: null,
items: [{ v: '1' }, { v: '2' }],
previousItems: [{ v: '0' }, { v: '1' }, { v: '2' }],
context: {
items: [{ v: '1' }, { v: '2' }],
itemComparer: (a, b) => a.v === b.v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal(null);
});
it('keeps the selected values if they are present among the new items', () => {
const state: ListState<ItemType> = {
highlightedValue: { v: '1' },
selectedValues: [{ v: '1' }, { v: '2' }],
};
const action: ListReducerAction<ItemType> = {
type: ListActionTypes.itemsChange,
event: null,
items: [{ v: '1' }, { v: '2' }],
previousItems: [{ v: '0' }, { v: '1' }, { v: '2' }],
context: {
items: [{ v: '1' }, { v: '2' }],
itemComparer: (a, b) => a.v === b.v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.selectedValues.map((sv) => sv.v)).to.deep.equal(['1', '2']);
});
it('removes the values from the selection if they are no longer present among the new items', () => {
const state: ListState<ItemType> = {
highlightedValue: { v: '1' },
selectedValues: [{ v: '0' }, { v: '2' }],
};
const action: ListReducerAction<ItemType> = {
type: ListActionTypes.itemsChange,
event: null,
items: [{ v: '1' }, { v: '2' }],
previousItems: [{ v: '0' }, { v: '1' }, { v: '2' }],
context: {
items: [{ v: '1' }, { v: '2' }],
itemComparer: (a, b) => a.v === b.v,
...irrelevantConfig,
},
};
const result = listReducer(state, action);
expect(result.selectedValues.map((sv) => sv.v)).to.deep.equal(['2']);
});
});
describe('after the items are initialized', () => {
it('highlights the first item when using DOM focus management', () => {
const state: ListState<string> = {
highlightedValue: null,
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemsChange,
event: null,
items: ['1', '2'],
previousItems: [],
context: {
...irrelevantConfig,
items: ['1', '2'],
itemComparer: (o, v) => o === v,
focusManagement: 'DOM',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('1');
});
it('highlights the first enabled item when using DOM focus management', () => {
const state: ListState<string> = {
highlightedValue: null,
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.itemsChange,
event: null,
items: ['1', '2', '3'],
previousItems: [],
context: {
...irrelevantConfig,
items: ['1', '2', '3'],
itemComparer: (o, v) => o === v,
focusManagement: 'DOM',
isItemDisabled: (item) => ['1', '2'].includes(item),
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('3');
});
});
});
describe('action: resetHighlight', () => {
it('highlights the first item', () => {
const state: ListState<string> = {
highlightedValue: 'three',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.resetHighlight,
event: null,
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'DOM',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'none',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('one');
});
it('highlights the first non-disabled item', () => {
const state: ListState<string> = {
highlightedValue: 'three',
selectedValues: [],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.resetHighlight,
event: null,
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'DOM',
isItemDisabled: (item) => item === 'one',
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'none',
},
};
const result = listReducer(state, action);
expect(result.highlightedValue).to.equal('two');
});
});
describe('action: clearSelection', () => {
it('clears the selection', () => {
const state: ListState<string> = {
highlightedValue: null,
selectedValues: ['one', 'two'],
};
const action: ListReducerAction<string> = {
type: ListActionTypes.clearSelection,
context: {
items: ['one', 'two', 'three'],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'DOM',
isItemDisabled: () => false,
itemComparer: (o, v) => o === v,
getItemAsString: (option) => option,
orientation: 'vertical',
pageSize: 5,
selectionMode: 'none',
},
};
const result = listReducer(state, action);
expect(result.selectedValues).to.deep.equal([]);
});
});
});
| 6,314
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/listReducer.ts
|
import { ListActionTypes } from './listActions.types';
import { ListState, ListReducerAction, ListActionContext, SelectionMode } from './useList.types';
type ItemPredicate<ItemValue> = (item: ItemValue, index: number) => boolean;
/**
* 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<ItemValue>(
currentIndex: number,
lookupDirection: 'next' | 'previous',
items: ItemValue[],
includeDisabledItems: boolean,
isItemDisabled: ItemPredicate<ItemValue>,
wrapAround: boolean,
): number {
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<ItemValue>(
previouslyHighlightedValue: ItemValue | null,
offset: number | 'reset' | 'start' | 'end',
context: ListActionContext<ItemValue>,
) {
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: number;
let lookupDirection: 'next' | 'previous';
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] ?? 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<ItemValue>(
item: ItemValue,
selectedValues: ItemValue[],
selectionMode: SelectionMode,
itemComparer: (item1: ItemValue, item2: ItemValue) => boolean,
) {
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<ItemValue, State extends ListState<ItemValue>>(
item: ItemValue,
state: State,
context: ListActionContext<ItemValue>,
): State {
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 {
...state,
selectedValues: newSelectedValues,
highlightedValue: item,
};
}
function handleKeyDown<ItemValue, State extends ListState<ItemValue>>(
key: string,
state: State,
context: ListActionContext<ItemValue>,
): State {
const previouslySelectedValue = state.highlightedValue;
const { orientation, pageSize } = context;
switch (key) {
case 'Home':
return {
...state,
highlightedValue: moveHighlight(previouslySelectedValue, 'start', context),
};
case 'End':
return {
...state,
highlightedValue: moveHighlight(previouslySelectedValue, 'end', context),
};
case 'PageUp':
return {
...state,
highlightedValue: moveHighlight(previouslySelectedValue, -pageSize, context),
};
case 'PageDown':
return {
...state,
highlightedValue: moveHighlight(previouslySelectedValue, pageSize, context),
};
case 'ArrowUp':
if (orientation !== 'vertical') {
break;
}
return {
...state,
highlightedValue: moveHighlight(previouslySelectedValue, -1, context),
};
case 'ArrowDown':
if (orientation !== 'vertical') {
break;
}
return {
...state,
highlightedValue: moveHighlight(previouslySelectedValue, 1, context),
};
case 'ArrowLeft': {
if (orientation === 'vertical') {
break;
}
const offset = orientation === 'horizontal-ltr' ? -1 : 1;
return {
...state,
highlightedValue: moveHighlight(previouslySelectedValue, offset, context),
};
}
case 'ArrowRight': {
if (orientation === 'vertical') {
break;
}
const offset = orientation === 'horizontal-ltr' ? 1 : -1;
return {
...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<ItemValue, State extends ListState<ItemValue>>(
state: State,
context: ListActionContext<ItemValue>,
): State {
if (context.focusManagement === 'DOM') {
return state;
}
return {
...state,
highlightedValue: null,
};
}
function textCriteriaMatches<ItemValue>(
nextFocus: ItemValue,
searchString: string,
stringifyItem: (item: ItemValue) => string | undefined,
) {
const text = stringifyItem(nextFocus)?.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<ItemValue, State extends ListState<ItemValue>>(
state: State,
searchString: string,
context: ListActionContext<ItemValue>,
): State {
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 {
...state,
highlightedValue: nextItem,
};
}
// Move to the next element.
nextItem = moveHighlight(nextItem, 1, context);
}
// No item matches the text search criteria
return state;
}
function handleItemsChange<ItemValue, State extends ListState<ItemValue>>(
items: ItemValue[],
previousItems: ItemValue[],
state: State,
context: ListActionContext<ItemValue>,
): State {
const { itemComparer, focusManagement } = context;
let newHighlightedValue: ItemValue | null = null;
if (state.highlightedValue != null) {
newHighlightedValue = items.find((item) => itemComparer(item, state.highlightedValue!)) ?? 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 ?? [];
const newSelectedValues = selectedValues.filter((selectedValue) =>
items.some((item) => itemComparer(item, selectedValue)),
);
return {
...state,
highlightedValue: newHighlightedValue,
selectedValues: newSelectedValues,
};
}
function handleResetHighlight<ItemValue, State extends ListState<ItemValue>>(
state: State,
context: ListActionContext<ItemValue>,
) {
return {
...state,
highlightedValue: moveHighlight(null, 'reset', context),
};
}
function handleClearSelection<ItemValue, State extends ListState<ItemValue>>(
state: State,
context: ListActionContext<ItemValue>,
) {
return {
...state,
selectedValues: [],
highlightedValue: moveHighlight(null, 'reset', context),
};
}
export function listReducer<ItemValue, State extends ListState<ItemValue>>(
state: State,
action: ListReducerAction<ItemValue> & { context: ListActionContext<ItemValue> },
): State {
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.clearSelection:
return handleClearSelection(state, context);
default:
return state;
}
}
| 6,315
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/useList.test.tsx
|
import * as React from 'react';
import { expect } from 'chai';
import { SinonSpy, spy } from 'sinon';
import { createRenderer, createEvent, fireEvent } from '@mui-internal/test-utils';
import { useList } from './useList';
describe('useList', () => {
const { render } = createRenderer();
describe('preventing default behavior on keyDown', () => {
['ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown', 'Enter', ' '].forEach((key) =>
it(`prevents default behavior when ${key} is pressed in activeDescendant focus management mode`, () => {
function Listbox() {
const { getRootProps } = useList({
items: [],
focusManagement: 'activeDescendant',
getItemId: () => undefined,
});
return <div role="listbox" {...getRootProps()} />;
}
const { getByRole } = render(<Listbox />);
const listbox = getByRole('listbox');
listbox.focus();
const event = createEvent.keyDown(listbox, {
key,
});
event.preventDefault = spy();
fireEvent(listbox, event);
expect((event.preventDefault as SinonSpy).calledOnce).to.equal(true);
}),
);
['ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown'].forEach((key) =>
it(`prevents default behavior when ${key} is pressed in DOM focus management mode`, () => {
function Listbox() {
const { getRootProps } = useList({
items: [],
focusManagement: 'DOM',
getItemDomElement: () => null,
});
return <div role="listbox" {...getRootProps()} />;
}
const { getByRole } = render(<Listbox />);
const listbox = getByRole('listbox');
listbox.focus();
const event = createEvent.keyDown(listbox, {
key,
});
event.preventDefault = spy();
fireEvent(listbox, event);
expect((event.preventDefault as SinonSpy).calledOnce).to.equal(true);
}),
);
['Enter', ' '].forEach((key) =>
it(`does not prevent default behavior when ${key} is pressed in DOM focus management mode`, () => {
function Listbox() {
const { getRootProps } = useList({
items: [],
focusManagement: 'DOM',
getItemDomElement: () => null,
});
return <div role="listbox" {...getRootProps()} />;
}
const { getByRole } = render(<Listbox />);
const listbox = getByRole('listbox');
listbox.focus();
const event = createEvent.keyDown(listbox, {
key,
});
event.preventDefault = spy();
fireEvent(listbox, event);
expect((event.preventDefault as SinonSpy).notCalled).to.equal(true);
}),
);
});
describe('external props', () => {
it('should pass arbitrary props to the root slot', () => {
const handleClick = spy();
function Listbox() {
const { getRootProps } = useList({
items: [],
getItemId: () => undefined,
});
return (
<div
role="listbox"
{...getRootProps({ 'data-testid': 'test-listbox', onClick: handleClick })}
/>
);
}
const { getByRole } = render(<Listbox />);
const listbox = getByRole('listbox');
expect(listbox).to.have.attribute('data-testid', 'test-listbox');
fireEvent.click(listbox);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,316
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/useList.ts
|
'use client';
import * as React from 'react';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import {
UseListParameters,
ListItemState,
UseListRootSlotProps,
ListState,
ListActionContext,
UseListReturnValue,
} from './useList.types';
import { ListActionTypes, ListAction } from './listActions.types';
import { ListContextValue } from './ListContext';
import { listReducer as defaultReducer } from './listReducer';
import { useControllableReducer } from '../utils/useControllableReducer';
import {
ControllableReducerAction,
StateChangeCallback,
StateComparers,
} from '../utils/useControllableReducer.types';
import { areArraysEqual } from '../utils/areArraysEqual';
import { useTextNavigation } from '../utils/useTextNavigation';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { EventHandlers } from '../utils/types';
const EMPTY_OBJECT = {};
const NOOP = () => {};
const defaultItemComparer = <ItemValue>(optionA: ItemValue, optionB: ItemValue) =>
optionA === optionB;
const defaultIsItemDisabled = () => false;
const defaultItemStringifier = <ItemValue>(item: ItemValue) =>
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<
ItemValue,
State extends ListState<ItemValue> = ListState<ItemValue>,
CustomAction extends ControllableReducerAction = never,
CustomActionContext = {},
>(
params: UseListParameters<ItemValue, State, CustomAction, CustomActionContext>,
): UseListReturnValue<ItemValue, State, CustomAction> {
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 as CustomActionContext,
selectionMode = 'single',
stateReducer: externalReducer,
} = 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<HTMLUListElement>(null);
const handleRef = useForkRef(externalListRef, listRef);
const handleHighlightChange = React.useCallback(
(
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null,
value: ItemValue | null,
reason: string,
) => {
onHighlightChange?.(event, value, reason);
if (
focusManagement === 'DOM' &&
value != null &&
(reason === ListActionTypes.itemClick ||
reason === ListActionTypes.keyDown ||
reason === ListActionTypes.textNavigation)
) {
getItemDomElement?.(value)?.focus();
}
},
[getItemDomElement, onHighlightChange, focusManagement],
);
const stateComparers = React.useMemo(
() =>
({
highlightedValue: itemComparer,
selectedValues: (valuesArray1, valuesArray2) =>
areArraysEqual(valuesArray1, valuesArray2, itemComparer),
} as StateComparers<State>),
[itemComparer],
);
// This gets called whenever a reducer changes the state.
const handleStateChange: StateChangeCallback<State> = React.useCallback(
(event, field, value, reason, state) => {
onStateChange?.(event, field, value, reason, state);
switch (field) {
case 'highlightedValue':
handleHighlightChange(
event as React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null,
value as ItemValue | null,
reason,
);
break;
case 'selectedValues':
onChange?.(
event as React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null,
value as ItemValue[],
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: ListActionContext<ItemValue> = 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 ?? defaultReducer) as React.Reducer<
State,
ListAction<ItemValue> | CustomAction
>;
const actionContext: ListActionContext<ItemValue> & CustomActionContext = React.useMemo(
() => ({ ...reducerActionContext, ...listActionContext }),
[reducerActionContext, listActionContext],
);
const [state, dispatch] = useControllableReducer<
State,
ListAction<ItemValue> | CustomAction,
ListActionContext<ItemValue> & CustomActionContext
>({
reducer,
actionContext,
initialState: initialState as State,
controlledProps,
stateComparers,
onStateChange: handleStateChange,
});
const { highlightedValue, selectedValues } = state;
const handleTextNavigation = useTextNavigation((searchString, event) =>
dispatch({
type: ListActionTypes.textNavigation,
event,
searchString,
}),
);
const previousItems = React.useRef<ItemValue[]>([]);
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?.(items);
}, [items, itemComparer, dispatch, onItemsChange]);
const createHandleKeyDown =
(externalHandlers: EventHandlers) =>
(event: React.KeyboardEvent<HTMLElement> & MuiCancellableEvent) => {
externalHandlers.onKeyDown?.(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: EventHandlers) =>
(event: React.FocusEvent<HTMLElement> & MuiCancellableEvent) => {
externalHandlers.onBlur?.(event);
if (event.defaultMuiPrevented) {
return;
}
if (listRef.current?.contains(event.relatedTarget)) {
// focus remains within the list
return;
}
dispatch({
type: ListActionTypes.blur,
event,
});
};
const getRootProps = <ExternalProps extends Record<string, any> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseListRootSlotProps<ExternalProps> => {
const externalEventHandlers = extractEventHandlers(externalProps);
return {
...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: ItemValue): ListItemState => {
const selected = (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: ListContextValue<ItemValue> = React.useMemo(
() => ({
dispatch,
getItemState,
}),
[dispatch, getItemState],
);
React.useDebugValue({
state,
});
return {
contextValue,
dispatch,
getRootProps,
rootRef: handleRef,
state,
};
}
export { useList };
| 6,317
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/useList.types.ts
|
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;
}
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;
}
| 6,318
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/useListItem.ts
|
'use client';
import * as React from 'react';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { EventHandlers } from '../utils/types';
import { UseListItemParameters, UseListItemReturnValue } from './useListItem.types';
import { ListActionTypes } from './listActions.types';
import { ListContext } from './ListContext';
/**
* Contains the logic for an item of a list-like component (e.g. 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<ItemValue>(
parameters: UseListItemParameters<ItemValue>,
): UseListItemReturnValue {
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: EventHandlers) => (event: React.MouseEvent) => {
externalHandlers.onClick?.(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: EventHandlers) => (event: React.PointerEvent) => {
externalHandlers.onMouseOver?.(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: number | undefined;
if (focusable) {
tabIndex = highlighted ? 0 : -1;
}
const getRootProps = <ExternalProps extends Record<string, any>>(
externalProps: ExternalProps = {} as ExternalProps,
) => {
const externalEventHandlers = extractEventHandlers(externalProps);
return {
...externalProps,
onClick: createHandleClick(externalEventHandlers),
onPointerOver: handlePointerOverEvents
? createHandlePointerOver(externalEventHandlers)
: undefined,
tabIndex,
};
};
return {
getRootProps,
highlighted,
selected,
};
}
| 6,319
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useList/useListItem.types.ts
|
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;
}
| 6,320
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenu/MenuProvider.tsx
|
'use client';
import * as React from 'react';
import { ListContext, ListContextValue } from '../useList/ListContext';
import { MenuItemMetadata } from '../useMenuItem';
import { CompoundComponentContext, CompoundComponentContextValue } from '../useCompound';
export type MenuProviderValue = CompoundComponentContextValue<string, MenuItemMetadata> &
ListContextValue<string>;
export interface MenuProviderProps {
value: MenuProviderValue;
children: React.ReactNode;
}
/**
* Sets up the contexts for the underlying MenuItem components.
*
* @ignore - do not document.
*/
export function MenuProvider(props: MenuProviderProps) {
const { value, children } = props;
const { dispatch, getItemIndex, getItemState, registerItem, totalSubitemCount } = value;
const listContextValue: ListContextValue<string> = React.useMemo(
() => ({
dispatch,
getItemState,
getItemIndex,
}),
[dispatch, getItemIndex, getItemState],
);
const compoundComponentContextValue: CompoundComponentContextValue<string, MenuItemMetadata> =
React.useMemo(
() => ({
getItemIndex,
registerItem,
totalSubitemCount,
}),
[registerItem, getItemIndex, totalSubitemCount],
);
return (
<CompoundComponentContext.Provider value={compoundComponentContextValue}>
<ListContext.Provider value={listContextValue}>{children}</ListContext.Provider>
</CompoundComponentContext.Provider>
);
}
| 6,321
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenu/index.ts
|
'use client';
export { useMenu } from './useMenu';
export * from './useMenu.types';
export * from './MenuProvider';
| 6,322
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenu/menuReducer.ts
|
import { ListAction, ListActionContext, ListActionTypes, listReducer } from '../useList';
import { ActionWithContext } from '../utils/useControllableReducer.types';
import { MenuInternalState } from './useMenu.types';
export type MenuActionContext = ListActionContext<string> & {
listboxRef: React.RefObject<HTMLElement>;
};
export function menuReducer(
state: MenuInternalState,
action: ActionWithContext<ListAction<string>, MenuActionContext>,
) {
if (action.type === ListActionTypes.itemHover) {
return state;
}
const newState = listReducer(state, action);
// make sure an item is always highlighted
if (newState.highlightedValue === null && action.context.items.length > 0) {
return {
...newState,
highlightedValue: action.context.items[0],
};
}
if (action.type === ListActionTypes.keyDown) {
if (action.event.key === 'Escape') {
return {
...newState,
open: false,
};
}
}
if (action.type === ListActionTypes.blur) {
if (!action.context.listboxRef.current?.contains(action.event.relatedTarget)) {
// To prevent the menu from closing when the focus leaves the menu to the button.
// For more details, see https://github.com/mui/material-ui/pull/36917#issuecomment-1566992698
const listboxId = action.context.listboxRef.current?.getAttribute('id');
const controlledBy = action.event.relatedTarget?.getAttribute('aria-controls');
if (listboxId && controlledBy && listboxId === controlledBy) {
return newState;
}
return {
...newState,
open: false,
highlightedValue: action.context.items[0],
};
}
}
return newState;
}
| 6,323
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenu/useMenu.test.js
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from '@mui-internal/test-utils';
import { MenuItem } from '../MenuItem';
import { useMenu } from './useMenu';
describe('useMenu', () => {
const { render } = createRenderer();
describe('getListboxProps', () => {
it('returns props for root slot', () => {
function TestMenu() {
const listboxRef = React.createRef();
const { getListboxProps } = useMenu({ listboxRef });
return <div {...getListboxProps()} />;
}
function Test() {
return (
<TestMenu>
<MenuItem />
</TestMenu>
);
}
const { getByRole } = render(<Test />);
const menu = getByRole('menu');
expect(menu).not.to.equal(null);
});
it('forwards external props including event handlers', () => {
const handleClick = spy();
function TestMenu() {
const listboxRef = React.createRef();
const { getListboxProps } = useMenu({ listboxRef });
return (
<div {...getListboxProps({ 'data-testid': 'test-listbox', onClick: handleClick })} />
);
}
function Test() {
return (
<TestMenu>
<MenuItem />
</TestMenu>
);
}
render(<Test />);
const listbox = screen.getByTestId('test-listbox');
expect(listbox).not.to.equal(null);
fireEvent.click(listbox);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,324
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenu/useMenu.ts
|
'use client';
import * as React from 'react';
import {
unstable_useForkRef as useForkRef,
unstable_useId as useId,
unstable_useEnhancedEffect as useEnhancedEffect,
} from '@mui/utils';
import { UseMenuListboxSlotProps, UseMenuParameters, UseMenuReturnValue } from './useMenu.types';
import { menuReducer } from './menuReducer';
import { DropdownContext, DropdownContextValue } from '../useDropdown/DropdownContext';
import { useList } from '../useList';
import { MenuItemMetadata } from '../useMenuItem';
import { DropdownActionTypes } from '../useDropdown';
import { EventHandlers } from '../utils/types';
import { useCompoundParent } from '../useCompound';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
import { combineHooksSlotProps } from '../utils/combineHooksSlotProps';
import { extractEventHandlers } from '../utils/extractEventHandlers';
const FALLBACK_MENU_CONTEXT: DropdownContextValue = {
dispatch: () => {},
popupId: '',
registerPopup: () => {},
registerTrigger: () => {},
state: { open: true },
triggerElement: null,
};
/**
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/#hooks)
*
* API:
*
* - [useMenu API](https://mui.com/base-ui/react-menu/hooks-api/#use-menu)
*/
export function useMenu(parameters: UseMenuParameters = {}): UseMenuReturnValue {
const {
listboxRef: listboxRefProp,
onItemsChange,
id: idParam,
disabledItemsFocusable = true,
disableListWrap = false,
// autoFocus = true,
} = parameters;
const rootRef = React.useRef<HTMLElement>(null);
const handleRef = useForkRef(rootRef, listboxRefProp);
const listboxId = useId(idParam) ?? '';
const {
state: { open },
dispatch: menuDispatch,
triggerElement,
registerPopup,
} = React.useContext(DropdownContext) ?? FALLBACK_MENU_CONTEXT;
// store the initial open state to prevent focus stealing
// (the first menu items gets focued only when the menu is opened by the user)
const isInitiallyOpen = React.useRef(open);
const { subitems, contextValue: compoundComponentContextValue } = useCompoundParent<
string,
MenuItemMetadata
>();
const subitemKeys = React.useMemo(() => Array.from(subitems.keys()), [subitems]);
const getItemDomElement = React.useCallback(
(itemId: string) => {
if (itemId == null) {
return null;
}
return subitems.get(itemId)?.ref.current ?? null;
},
[subitems],
);
const isItemDisabled = React.useCallback(
(id: string) => subitems?.get(id)?.disabled || false,
[subitems],
);
const getItemAsString = React.useCallback(
(id: string) => subitems.get(id)?.label || subitems.get(id)?.ref.current?.innerText,
[subitems],
);
const reducerActionContext = React.useMemo(() => ({ listboxRef: rootRef }), [rootRef]);
const {
dispatch: listDispatch,
getRootProps: getListRootProps,
contextValue: listContextValue,
state: { highlightedValue },
rootRef: mergedListRef,
} = useList({
disabledItemsFocusable,
disableListWrap,
focusManagement: 'DOM',
getItemDomElement,
getInitialState: () => ({
selectedValues: [],
highlightedValue: null,
}),
isItemDisabled,
items: subitemKeys,
getItemAsString,
rootRef: handleRef,
onItemsChange,
reducerActionContext,
selectionMode: 'none',
stateReducer: menuReducer,
});
useEnhancedEffect(() => {
registerPopup(listboxId);
}, [listboxId, registerPopup]);
React.useEffect(() => {
if (open && highlightedValue === subitemKeys[0] && !isInitiallyOpen.current) {
// TODO v6: focus only if autoFocus is true
subitems.get(subitemKeys[0])?.ref?.current?.focus();
}
}, [open, highlightedValue, subitems, subitemKeys]);
React.useEffect(() => {
// set focus to the highlighted item (but prevent stealing focus from other elements on the page)
if (rootRef.current?.contains(document.activeElement) && highlightedValue !== null) {
subitems?.get(highlightedValue)?.ref.current?.focus();
}
}, [highlightedValue, subitems]);
const createHandleBlur =
(otherHandlers: EventHandlers) => (event: React.FocusEvent & MuiCancellableEvent) => {
otherHandlers.onBlur?.(event);
if (event.defaultMuiPrevented) {
return;
}
if (
rootRef.current?.contains(event.relatedTarget as HTMLElement) ||
event.relatedTarget === triggerElement
) {
return;
}
menuDispatch({
type: DropdownActionTypes.blur,
event,
});
};
const createHandleKeyDown =
(otherHandlers: EventHandlers) => (event: React.KeyboardEvent & MuiCancellableEvent) => {
otherHandlers.onKeyDown?.(event);
if (event.defaultMuiPrevented) {
return;
}
if (event.key === 'Escape') {
menuDispatch({
type: DropdownActionTypes.escapeKeyDown,
event,
});
}
};
const getOwnListboxHandlers = (otherHandlers: EventHandlers = {}) => ({
onBlur: createHandleBlur(otherHandlers),
onKeyDown: createHandleKeyDown(otherHandlers),
});
const getListboxProps = <ExternalProps extends Record<string, unknown>>(
externalProps: ExternalProps = {} as ExternalProps,
): UseMenuListboxSlotProps => {
const getCombinedRootProps = combineHooksSlotProps(getOwnListboxHandlers, getListRootProps);
const externalEventHandlers = extractEventHandlers(externalProps);
return {
...externalProps,
...externalEventHandlers,
...getCombinedRootProps(externalEventHandlers),
id: listboxId,
role: 'menu',
};
};
React.useDebugValue({ subitems, highlightedValue });
return {
contextValue: {
...compoundComponentContextValue,
...listContextValue,
},
dispatch: listDispatch,
getListboxProps,
highlightedValue,
listboxRef: mergedListRef,
menuItems: subitems,
open,
triggerElement,
};
}
| 6,325
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenu/useMenu.types.ts
|
import * as React from 'react';
import { ListAction, ListState, UseListRootSlotProps } from '../useList';
import { MenuItemMetadata } from '../useMenuItem';
import { MenuProviderValue } from './MenuProvider';
export interface UseMenuParameters {
/**
* The id of the menu. If not provided, it will be generated.
*/
id?: string;
/**
* If `true`, it will be possible to highlight disabled items.
* @default true
*/
disabledItemsFocusable?: boolean;
/**
* If `true`, the highlight will not wrap around the list if arrow keys are used.
* @default false
*/
disableListWrap?: boolean;
/**
* Callback fired when the menu items change.
*/
onItemsChange?: (items: string[]) => void;
/**
* The ref to the menu's listbox node.
*/
listboxRef?: React.Ref<Element>;
}
export interface UseMenuReturnValue {
/**
* The value to be passed into the MenuProvider.
*/
contextValue: MenuProviderValue;
/**
* Action dispatcher for the menu component.
* Allows to programmatically control the menu.
*/
dispatch: (action: ListAction<string>) => void;
/**
* Resolver for the listbox slot's props.
* @param externalProps additional props for the listbox component
* @returns props that should be spread on the listbox component
*/
getListboxProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseMenuListboxSlotProps;
/**
* The highlighted option in the menu listbox.
*/
highlightedValue: string | null;
/**
* The ref to the menu's listbox node.
*/
listboxRef: React.RefCallback<Element> | null;
/**
* Items in the menu listbox.
*/
menuItems: Map<string, MenuItemMetadata>;
/**
* If `true`, the menu is open.
*/
open: boolean;
/**
* An element that triggers the visibility of the menu.
*/
triggerElement: HTMLElement | null;
}
interface UseMenuListboxSlotEventHandlers {
onBlur: React.FocusEventHandler;
onKeyDown: React.KeyboardEventHandler;
}
export type UseMenuListboxSlotProps<ExternalProps = {}> = UseListRootSlotProps<
Omit<ExternalProps, keyof UseMenuListboxSlotEventHandlers> & UseMenuListboxSlotEventHandlers
> & {
ref: React.RefCallback<Element> | null;
role: React.AriaRole;
};
export interface MenuInternalState extends ListState<string> {}
| 6,326
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuButton/index.ts
|
'use client';
export { useMenuButton } from './useMenuButton';
export * from './useMenuButton.types';
| 6,327
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuButton/useMenuButton.test.tsx
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from '@mui-internal/test-utils';
import { DropdownContext, DropdownContextValue } from '@mui/base/useDropdown';
import { useMenuButton } from './useMenuButton';
const testContext: DropdownContextValue = {
dispatch: () => {},
popupId: 'menu-popup',
registerPopup: () => {},
registerTrigger: () => {},
state: { open: true },
triggerElement: null,
};
describe('useMenuButton', () => {
const { render } = createRenderer();
describe('getRootProps', () => {
it('returns props for root slot', () => {
function TestMenuButton() {
const { getRootProps } = useMenuButton();
return <div {...getRootProps()} />;
}
function Test() {
return (
<DropdownContext.Provider value={testContext}>
<TestMenuButton />
</DropdownContext.Provider>
);
}
const { getByRole } = render(<Test />);
const button = getByRole('button');
expect(button).not.to.equal(null);
});
it('forwards external props including event handlers', () => {
const handleClick = spy();
function TestMenuButton() {
const { getRootProps } = useMenuButton();
return (
<div {...getRootProps({ 'data-testid': 'test-menu-button', onClick: handleClick })} />
);
}
function Test() {
return (
<DropdownContext.Provider value={testContext}>
<TestMenuButton />
</DropdownContext.Provider>
);
}
render(<Test />);
const button = screen.getByTestId('test-menu-button');
expect(button).not.to.equal(null);
fireEvent.click(button);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,328
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuButton/useMenuButton.ts
|
'use client';
import * as React from 'react';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import { UseMenuButtonParameters, UseMenuButtonReturnValue } from './useMenuButton.types';
import { DropdownContext } from '../useDropdown/DropdownContext';
import { DropdownActionTypes } from '../useDropdown/useDropdown.types';
import { useButton } from '../useButton/useButton';
import { EventHandlers } from '../utils/types';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
import { combineHooksSlotProps } from '../utils/combineHooksSlotProps';
import { extractEventHandlers } from '../utils';
/**
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/#hooks)
*
* API:
*
* - [useMenuButton API](https://mui.com/base-ui/react-menu/hooks-api/#use-menu-button)
*/
export function useMenuButton(parameters: UseMenuButtonParameters = {}): UseMenuButtonReturnValue {
const { disabled = false, focusableWhenDisabled, rootRef: externalRef } = parameters;
const menuContext = React.useContext(DropdownContext);
if (menuContext === null) {
throw new Error('useMenuButton: no menu context available.');
}
const { state, dispatch, registerTrigger, popupId } = menuContext;
const {
getRootProps: getButtonRootProps,
rootRef: buttonRootRef,
active,
} = useButton({
disabled,
focusableWhenDisabled,
rootRef: externalRef,
});
const handleRef = useForkRef(buttonRootRef, registerTrigger);
const createHandleClick =
(otherHandlers: EventHandlers) => (event: React.MouseEvent & MuiCancellableEvent) => {
otherHandlers.onClick?.(event);
if (event.defaultMuiPrevented) {
return;
}
dispatch({
type: DropdownActionTypes.toggle,
event,
});
};
const createHandleKeyDown =
(otherHandlers: EventHandlers) => (event: React.KeyboardEvent & MuiCancellableEvent) => {
otherHandlers.onKeyDown?.(event);
if (event.defaultMuiPrevented) {
return;
}
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
dispatch({
type: DropdownActionTypes.open,
event,
});
}
};
const getOwnRootProps = (otherHandlers: EventHandlers = {}) => ({
onClick: createHandleClick(otherHandlers),
onKeyDown: createHandleKeyDown(otherHandlers),
});
const getRootProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
) => {
const externalEventHandlers = extractEventHandlers(externalProps);
const getCombinedProps = combineHooksSlotProps(getButtonRootProps, getOwnRootProps);
return {
'aria-haspopup': 'menu' as const,
'aria-expanded': state.open,
'aria-controls': popupId,
...externalProps,
...externalEventHandlers,
...getCombinedProps(externalEventHandlers),
tabIndex: 0, // this is needed to make the button focused after click in Safari
ref: handleRef,
};
};
return {
active,
getRootProps,
open: state.open,
rootRef: handleRef,
};
}
| 6,329
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuButton/useMenuButton.types.ts
|
export interface UseMenuButtonParameters {
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean;
/**
* If `true`, allows a disabled button to receive focus.
* @default false
*/
focusableWhenDisabled?: boolean;
/**
* The ref to the root element.
*/
rootRef?: React.Ref<HTMLElement>;
}
type UseMenuButtonRootSlotProps<ExternalProps = {}> = ExternalProps & UseMenuButtonRootSlotOwnProps;
interface UseMenuButtonRootSlotOwnProps {
'aria-haspopup': 'menu';
'aria-expanded': boolean;
'aria-controls': string;
/**
* Callback fired when the button is clicked.
*/
onClick: React.MouseEventHandler;
/**
* The ref to the button element.
*/
ref: React.RefCallback<Element> | null;
}
export interface UseMenuButtonReturnValue {
/**
* If `true`, the component is active (pressed).
*/
active: boolean;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseMenuButtonRootSlotProps<ExternalProps>;
/*
* If `true`, the menu is open.
*/
open: boolean;
/**
* The ref to the root element.
*/
rootRef: React.RefCallback<Element> | null;
}
| 6,330
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuItem/index.ts
|
'use client';
export { useMenuItem } from './useMenuItem';
export * from './useMenuItem.types';
export * from './useMenuItemContextStabilizer';
| 6,331
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuItem/useMenuItem.test.tsx
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from '@mui-internal/test-utils';
import { Menu } from '../Menu';
import { useMenuItem } from './useMenuItem';
describe('useMenuItem', () => {
const { render } = createRenderer();
describe('getRootProps', () => {
it('returns props for root slot', () => {
function TestMenuItem() {
const rootRef = React.createRef<HTMLElement>();
const { getRootProps } = useMenuItem({ rootRef });
return <div {...getRootProps()} />;
}
function Test() {
return (
<Menu>
<TestMenuItem />
</Menu>
);
}
const { getByRole } = render(<Test />);
const menuItem = getByRole('menuitem');
expect(menuItem).not.to.equal(null);
});
it('forwards external props including event handlers', () => {
const handleClick = spy();
function TestMenuItem() {
const rootRef = React.createRef<HTMLElement>();
const { getRootProps } = useMenuItem({ rootRef, id: 'test-menu-item-1' });
return <div {...getRootProps({ 'data-testid': 'test-menu-item', onClick: handleClick })} />;
}
function Test() {
return (
<Menu>
<TestMenuItem />
</Menu>
);
}
render(<Test />);
const menuItem = screen.getByTestId('test-menu-item');
expect(menuItem).not.to.equal(null);
fireEvent.click(menuItem);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,332
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuItem/useMenuItem.ts
|
'use client';
import * as React from 'react';
import { unstable_useId as useId, unstable_useForkRef as useForkRef } from '@mui/utils';
import { useButton } from '../useButton';
import type {
MenuItemMetadata,
UseMenuItemParameters,
UseMenuItemReturnValue,
UseMenuItemRootSlotProps,
} from './useMenuItem.types';
import { useListItem } from '../useList';
import { DropdownActionTypes } from '../useDropdown';
import { DropdownContext, DropdownContextValue } from '../useDropdown/DropdownContext';
import { combineHooksSlotProps } from '../utils/combineHooksSlotProps';
import { useCompoundItem } from '../useCompound';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
import { EventHandlers } from '../utils/types';
import { extractEventHandlers } from '../utils/extractEventHandlers';
function idGenerator(existingKeys: Set<string>) {
return `menu-item-${existingKeys.size}`;
}
const FALLBACK_MENU_CONTEXT: DropdownContextValue = {
dispatch: () => {},
popupId: '',
registerPopup: () => {},
registerTrigger: () => {},
state: { open: true },
triggerElement: null,
};
/**
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/#hooks)
*
* API:
*
* - [useMenuItem API](https://mui.com/base-ui/react-menu/hooks-api/#use-menu-item)
*/
export function useMenuItem(params: UseMenuItemParameters): UseMenuItemReturnValue {
const { disabled = false, id: idParam, rootRef: externalRef, label } = params;
const id = useId(idParam);
const itemRef = React.useRef<HTMLElement>(null);
const itemMetadata: MenuItemMetadata = React.useMemo(
() => ({ disabled, id: id ?? '', label, ref: itemRef }),
[disabled, id, label],
);
const { dispatch } = React.useContext(DropdownContext) ?? FALLBACK_MENU_CONTEXT;
const { getRootProps: getListRootProps, highlighted } = useListItem({
item: id,
});
const { index, totalItemCount } = useCompoundItem(id ?? idGenerator, itemMetadata);
const {
getRootProps: getButtonProps,
focusVisible,
rootRef: buttonRefHandler,
} = useButton({
disabled,
focusableWhenDisabled: true,
});
const handleRef = useForkRef(buttonRefHandler, externalRef, itemRef);
React.useDebugValue({ id, highlighted, disabled, label });
const createHandleClick =
(otherHandlers: EventHandlers) => (event: React.MouseEvent & MuiCancellableEvent) => {
otherHandlers.onClick?.(event);
if (event.defaultMuiPrevented) {
return;
}
dispatch({
type: DropdownActionTypes.close,
event,
});
};
const getOwnHandlers = <ExternalProps extends EventHandlers>(
otherHandlers: ExternalProps = {} as ExternalProps,
) => ({
...otherHandlers,
onClick: createHandleClick(otherHandlers),
});
function getRootProps<ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseMenuItemRootSlotProps<ExternalProps> {
const externalEventHandlers = extractEventHandlers(externalProps);
const getCombinedRootProps = combineHooksSlotProps(
getOwnHandlers,
combineHooksSlotProps(getButtonProps, getListRootProps),
);
return {
...externalProps,
...externalEventHandlers,
...getCombinedRootProps(externalEventHandlers),
id,
ref: handleRef,
role: 'menuitem',
};
}
// If `id` is undefined (during SSR in React < 18), we fall back to rendering a simplified menu item
// which does not have access to infortmation about its position or highlighted state.
if (id === undefined) {
return {
getRootProps,
disabled: false,
focusVisible,
highlighted: false,
index: -1,
totalItemCount: 0,
rootRef: handleRef,
};
}
return {
getRootProps,
disabled,
focusVisible,
highlighted,
index,
totalItemCount,
rootRef: handleRef,
};
}
| 6,333
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuItem/useMenuItem.types.ts
|
import { UseButtonRootSlotProps } from '../useButton';
import { MuiCancellableEventHandler } from '../utils/MuiCancellableEvent';
interface UseMenuItemRootSlotOwnProps {
id: string | undefined;
role: 'menuitem';
ref: React.RefCallback<Element> | null;
}
export interface MenuItemMetadata {
id: string;
disabled: boolean;
label?: string;
ref: React.RefObject<HTMLElement>;
}
export type UseMenuItemRootSlotProps<ExternalProps = {}> = ExternalProps &
UseMenuItemRootSlotOwnProps &
UseButtonRootSlotProps<ExternalProps> & {
onClick: MuiCancellableEventHandler<React.MouseEvent>;
};
export interface UseMenuItemParameters {
disabled?: boolean;
id?: string;
label?: string;
onClick?: React.MouseEventHandler<any>;
rootRef: React.Ref<Element>;
}
export interface UseMenuItemReturnValue {
/**
* Resolver for the root slot's props.
* @param externalProps event handlers for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseMenuItemRootSlotProps<ExternalProps>;
/**
* If `true`, the component is disabled.
*/
disabled: boolean;
/**
* If `true`, the component is being focused using keyboard.
*/
focusVisible: boolean;
/**
* If `true`, the component is being highlighted.
*/
highlighted: boolean;
/**
* 0-based index of the item in the menu.
*/
index: number;
/**
* The ref to the component's root DOM element.
*/
rootRef: React.RefCallback<Element> | null;
/**
* Total number of items in the menu.
*/
totalItemCount: number;
}
| 6,334
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useMenuItem/useMenuItemContextStabilizer.ts
|
'use client';
import * as React from 'react';
import { unstable_useId as useId } from '@mui/utils';
import { ListContext, ListContextValue, ListItemState } from '../useList';
/**
* Stabilizes the ListContext value for the MenuItem component, so it doesn't change when sibling items update.
*
* @param id The id of the MenuItem. If undefined, it will be generated with useId.
* @returns The stable ListContext value and the id of the MenuItem.
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/#hooks)
*
* API:
*
* - [useMenuItemContextStabilizer API](https://mui.com/base-ui/react-menu/hooks-api/#use-menu-item-context-stabilizer)
*/
export function useMenuItemContextStabilizer(id: string | undefined) {
const listContext = React.useContext(ListContext as React.Context<ListContextValue<string>>);
if (!listContext) {
throw new Error('MenuItem: ListContext was not found.');
}
const itemId = useId(id);
const { getItemState, dispatch } = listContext;
let itemState: ListItemState;
if (itemId != null) {
itemState = getItemState(itemId);
} else {
itemState = { focusable: true, highlighted: false, selected: false };
}
const { highlighted, selected, focusable } = itemState;
// The local version of getItemState can be only called with the current Option's value.
// It doesn't make much sense to render an Option depending on other Options' state anyway.
const localGetItemState = React.useCallback(
(itemValue: string) => {
if (itemValue !== itemId) {
throw new Error(
[
'Base UI MenuItem: Tried to access the state of another MenuItem.',
`itemValue: ${itemValue} | id: ${itemId}`,
'This is unsupported when the MenuItem uses the MenuItemContextStabilizer as a performance optimization.',
].join('/n'),
);
}
return {
highlighted,
selected,
focusable,
};
},
[highlighted, selected, focusable, itemId],
);
// Create a local (per MenuItem) instance of the ListContext that changes only when
// the getItemState's return value changes.
// This makes MenuItems re-render only when their state actually change, not when any MenuItem's state changes.
const localContextValue = React.useMemo(
() => ({
dispatch,
getItemState: localGetItemState,
}),
[dispatch, localGetItemState],
);
return {
contextValue: localContextValue,
id: itemId,
};
}
| 6,335
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useOption/index.ts
|
'use client';
export { useOption } from './useOption';
export * from './useOption.types';
export * from './useOptionContextStabilizer';
| 6,336
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useOption/useOption.ts
|
'use client';
import * as React from 'react';
import { unstable_useForkRef as useForkRef, unstable_useId as useId } from '@mui/utils';
import { SelectOption, UseOptionParameters, UseOptionReturnValue } from './useOption.types';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { useListItem } from '../useList';
import { useCompoundItem } from '../useCompound';
/**
*
* Demos:
*
* - [Select](https://mui.com/base-ui/react-select/#hooks)
*
* API:
*
* - [useOption API](https://mui.com/base-ui/react-select/hooks-api/#use-option)
*/
export function useOption<Value>(params: UseOptionParameters<Value>): UseOptionReturnValue {
const { value, label, disabled, rootRef: optionRefParam, id: idParam } = params;
const {
getRootProps: getListItemProps,
highlighted,
selected,
} = useListItem({
item: value,
});
const id = useId(idParam);
const optionRef = React.useRef<Element>(null);
const selectOption: SelectOption<Value> = React.useMemo(
() => ({
disabled,
label,
value,
ref: optionRef,
id,
}),
[disabled, label, value, id],
);
const { index } = useCompoundItem<Value, SelectOption<Value>>(value, selectOption);
const handleRef = useForkRef(optionRefParam, optionRef)!;
return {
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
) => {
const externalEventHandlers = extractEventHandlers(externalProps);
return {
...externalProps,
...getListItemProps(externalEventHandlers),
id,
ref: handleRef,
role: 'option',
'aria-selected': selected,
};
},
highlighted,
index,
selected,
rootRef: handleRef,
};
}
| 6,337
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useOption/useOption.types.ts
|
import { UseListItemRootSlotProps } from '../useList';
export interface SelectOption<Value> {
value: Value;
label: React.ReactNode;
disabled?: boolean;
ref: React.RefObject<Element>;
id?: string;
}
export interface UseOptionParameters<Value> {
disabled: boolean;
id?: string;
label: string | React.ReactNode;
rootRef?: React.Ref<Element>;
value: Value;
}
export interface UseOptionReturnValue {
/**
* If `true`, the option is selected.
*/
selected: boolean;
/**
* If `true`, the option is highlighted.
*/
highlighted: boolean;
index: number;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown>>(
externalProps?: ExternalProps,
) => UseOptionRootSlotProps<ExternalProps>;
/**
* Ref to the root slot DOM node.
*/
rootRef: React.RefCallback<Element> | null;
}
export type UseOptionRootSlotProps<ExternalProps extends Record<string, unknown> = {}> =
UseListItemRootSlotProps<ExternalProps> & {
ref?: React.RefCallback<Element> | null;
} & ExternalProps;
| 6,338
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useOption/useOptionContextStabilizer.ts
|
'use client';
import * as React from 'react';
import { ListContext, ListContextValue } from '../useList';
/**
* Stabilizes the ListContext value for the Option component, so it doesn't change when sibling Options update.
*
* @param value The value of the Option.
* @returns The stable ListContext value.
*
* Demos:
*
* - [Select](https://mui.com/base-ui/react-select/#hooks)
*
* API:
*
* - [useOptionContextStabilizer API](https://mui.com/base-ui/react-select/hooks-api/#use-option-context-stabilizer)
*/
export function useOptionContextStabilizer<OptionValue>(value: OptionValue) {
const listContext = React.useContext(ListContext as React.Context<ListContextValue<OptionValue>>);
if (!listContext) {
throw new Error('Option: ListContext was not found.');
}
const { getItemState, dispatch } = listContext;
const { highlighted, selected, focusable } = getItemState(value);
// The local version of getItemState can be only called with the current Option's value.
// It doesn't make much sense to render an Option depending on other Options' state anyway.
const localGetItemState = React.useCallback(
(itemValue: OptionValue) => {
if (itemValue !== value) {
throw new Error(
[
'Base UI Option: Tried to access the state of another Option.',
'This is unsupported when the Option uses the OptionContextStabilizer as a performance optimization.',
].join('/n'),
);
}
return {
highlighted,
selected,
focusable,
};
},
[highlighted, selected, focusable, value],
);
// Create a local (per Option) instance of the ListContext that changes only when
// the getItemState's return value changes.
// This makes Options re-render only when their state actually change, not when any Option's state changes.
const localContextValue = React.useMemo(
() => ({
dispatch,
getItemState: localGetItemState,
}),
[dispatch, localGetItemState],
);
return {
contextValue: localContextValue,
};
}
| 6,339
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/SelectProvider.tsx
|
'use client';
import * as React from 'react';
import { ListContext, ListContextValue } from '../useList/ListContext';
import { SelectOption } from '../useOption';
import { CompoundComponentContext, CompoundComponentContextValue } from '../useCompound';
export type SelectProviderValue<Value> = CompoundComponentContextValue<Value, SelectOption<Value>> &
ListContextValue<Value>;
export interface SelectProviderProps<Value> {
value: SelectProviderValue<Value>;
children: React.ReactNode;
}
/**
* Sets up the contexts for the underlying Option components.
*
* @ignore - do not document.
*/
export function SelectProvider<Value>(props: SelectProviderProps<Value>) {
const { value, children } = props;
const { dispatch, getItemIndex, getItemState, registerItem, totalSubitemCount } = value;
const listContextValue: ListContextValue<Value> = React.useMemo(
() => ({
dispatch,
getItemState,
getItemIndex,
}),
[dispatch, getItemIndex, getItemState],
);
const compoundComponentContextValue: CompoundComponentContextValue<
Value,
SelectOption<Value>
> = React.useMemo(
() => ({
getItemIndex,
registerItem,
totalSubitemCount,
}),
[registerItem, getItemIndex, totalSubitemCount],
);
return (
<CompoundComponentContext.Provider value={compoundComponentContextValue}>
<ListContext.Provider value={listContextValue}>{children}</ListContext.Provider>
</CompoundComponentContext.Provider>
);
}
| 6,340
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/defaultOptionStringifier.ts
|
import { SelectOption } from '../useOption';
const defaultOptionStringifier = <OptionValue>(option: SelectOption<OptionValue>) => {
const { label, value } = option;
if (typeof label === 'string') {
return label;
}
if (typeof value === 'string') {
return value;
}
// Fallback string representation
return String(option);
};
export { defaultOptionStringifier };
| 6,341
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/index.ts
|
'use client';
export { useSelect } from './useSelect';
export * from './useSelect.types';
export * from './SelectProvider';
| 6,342
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/selectReducer.test.ts
|
import { expect } from 'chai';
import { selectReducer } from './selectReducer';
import { SelectAction, SelectActionTypes, SelectInternalState } from './useSelect.types';
import { ActionWithContext } from '../utils/useControllableReducer.types';
import { ListActionContext } from '../useList';
describe('selectReducer', () => {
const irrelevantConfig = {
items: [],
disableListWrap: false,
disabledItemsFocusable: false,
focusManagement: 'activeDescendant' as const,
isItemDisabled: () => false,
itemComparer: (a: any, b: any) => a === b,
getItemAsString: (option: any) => option,
orientation: 'vertical' as const,
pageSize: 5,
selectionMode: 'single' as const,
};
describe('action: buttonClick', () => {
it('opens the select if it was closed', () => {
const state: SelectInternalState<unknown> = {
highlightedValue: null,
selectedValues: [],
open: false,
};
const action: ActionWithContext<SelectAction<string>, ListActionContext<unknown>> = {
type: SelectActionTypes.buttonClick,
event: {} as any, // not relevant
context: irrelevantConfig,
};
const result = selectReducer(state, action);
expect(result.open).to.equal(true);
});
it('closes the select if it was open', () => {
const state: SelectInternalState<unknown> = {
highlightedValue: null,
selectedValues: [],
open: true,
};
const action: ActionWithContext<SelectAction<string>, ListActionContext<unknown>> = {
type: SelectActionTypes.buttonClick,
event: {} as any, // not relevant
context: {
...irrelevantConfig,
},
};
const result = selectReducer(state, action);
expect(result.open).to.equal(false);
});
it('highlights the first selected value if the select was closed', () => {
const state: SelectInternalState<string> = {
highlightedValue: null,
selectedValues: ['2'],
open: false,
};
const action: ActionWithContext<SelectAction<string>, ListActionContext<string>> = {
type: SelectActionTypes.buttonClick,
event: {} as any, // not relevant
context: {
...irrelevantConfig,
items: ['1', '2', '3'],
},
};
const result = selectReducer(state, action);
expect(result.highlightedValue).to.equal('2');
});
it('highlights the first value if the select was closed and nothing was selected', () => {
const state: SelectInternalState<string> = {
highlightedValue: null,
selectedValues: [],
open: false,
};
const action: ActionWithContext<SelectAction<string>, ListActionContext<string>> = {
type: SelectActionTypes.buttonClick,
event: {} as any, // not relevant
context: {
...irrelevantConfig,
items: ['1', '2', '3'],
},
};
const result = selectReducer(state, action);
expect(result.highlightedValue).to.equal('1');
});
});
describe('action: browserAutoFill', () => {
it('selects the item and highlights it', () => {
const state: SelectInternalState<string> = {
highlightedValue: null,
selectedValues: [],
open: false,
};
const action: ActionWithContext<SelectAction<string>, ListActionContext<string>> = {
type: SelectActionTypes.browserAutoFill,
event: {} as any, // not relevant
item: '1',
context: {
...irrelevantConfig,
items: ['1', '2', '3'],
},
};
const result = selectReducer(state, action);
expect(result.highlightedValue).to.equal('1');
expect(result.selectedValues).to.deep.equal(['1']);
});
});
});
| 6,343
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/selectReducer.ts
|
import {
ListAction,
ListActionContext,
moveHighlight,
listReducer,
ListActionTypes,
handleItemSelection,
} from '../useList';
import { ActionWithContext } from '../utils/useControllableReducer.types';
import { SelectAction, SelectActionTypes, SelectInternalState } from './useSelect.types';
export function selectReducer<OptionValue>(
state: SelectInternalState<OptionValue>,
action: ActionWithContext<
ListAction<OptionValue> | SelectAction<OptionValue>,
ListActionContext<OptionValue>
>,
) {
const { open } = state;
const {
context: { selectionMode },
} = action;
if (action.type === SelectActionTypes.buttonClick) {
const itemToHighlight =
state.selectedValues[0] ?? moveHighlight<OptionValue>(null, 'start', action.context);
return {
...state,
open: !open,
highlightedValue: !open ? itemToHighlight : null,
};
}
if (action.type === SelectActionTypes.browserAutoFill) {
return handleItemSelection<OptionValue, SelectInternalState<OptionValue>>(
action.item,
state,
action.context,
);
}
const newState: SelectInternalState<OptionValue> = listReducer(
state,
action as ActionWithContext<ListAction<OptionValue>, ListActionContext<OptionValue>>,
);
switch (action.type) {
case ListActionTypes.keyDown:
if (state.open) {
if (action.event.key === 'Escape') {
return {
...newState,
open: false,
};
}
if (
selectionMode === 'single' &&
(action.event.key === 'Enter' || action.event.key === ' ')
) {
return {
...newState,
open: false,
};
}
} else {
if (
action.event.key === 'Enter' ||
action.event.key === ' ' ||
action.event.key === 'ArrowDown'
) {
return {
...state,
open: true,
highlightedValue:
state.selectedValues[0] ?? moveHighlight<OptionValue>(null, 'start', action.context),
};
}
if (action.event.key === 'ArrowUp') {
return {
...state,
open: true,
highlightedValue:
state.selectedValues[0] ?? moveHighlight<OptionValue>(null, 'end', action.context),
};
}
}
break;
case ListActionTypes.itemClick:
if (selectionMode === 'single') {
return {
...newState,
open: false,
};
}
break;
case ListActionTypes.blur:
return {
...newState,
open: false,
};
default:
return newState;
}
return newState;
}
| 6,344
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/useSelect.test.tsx
|
import { expect } from 'chai';
import sinon from 'sinon';
import { renderHook } from '@testing-library/react';
import { useSelect } from './useSelect';
describe('useSelect', () => {
describe('param: options', () => {
it('lets define options explicitly', () => {
const options = [
{ value: 'a', label: 'A' },
{ value: 'b', label: 'B' },
{ value: 'c', label: 'C', disabled: true },
];
const { result } = renderHook(() => useSelect({ options }));
expect(result.current.options).to.deep.equal(['a', 'b', 'c']);
expect(result.current.getOptionMetadata('a')?.label).to.equal('A');
expect(result.current.getOptionMetadata('b')?.label).to.equal('B');
expect(result.current.getOptionMetadata('c')?.label).to.equal('C');
expect(result.current.getOptionMetadata('c')?.disabled).to.equal(true);
});
});
describe('getHiddenInputProps', () => {
it('returns props for hidden input', () => {
const options = [
{ value: 'a', label: 'A' },
{ value: 'b', label: 'B' },
{ value: 'c', label: 'C', disabled: true },
];
const { result } = renderHook(() =>
useSelect({ options, defaultValue: 'b', name: 'foo', required: true }),
);
sinon.assert.match(result.current.getHiddenInputProps(), {
name: 'foo',
tabIndex: -1,
'aria-hidden': true,
required: true,
value: 'b',
style: {
clip: 'rect(1px, 1px, 1px, 1px)',
clipPath: 'inset(50%)',
height: '1px',
width: '1px',
margin: '-1px',
overflow: 'hidden',
padding: 0,
position: 'absolute',
left: '50%',
bottom: 0,
},
});
});
it('[multiple] returns correct value for the hidden input', () => {
const options = [
{ value: 'a', label: 'A' },
{ value: 'b', label: 'B' },
{ value: 'c', label: 'C', disabled: true },
];
const { result } = renderHook(() =>
useSelect({
multiple: true,
options,
defaultValue: ['a', 'b'],
name: 'foo',
required: true,
}),
);
sinon.assert.match(result.current.getHiddenInputProps(), {
name: 'foo',
tabIndex: -1,
'aria-hidden': true,
required: true,
value: JSON.stringify(['a', 'b']),
});
});
it('[multiple with object value] returns correct value for the hidden input', () => {
const options = [
{ value: { name: 'a' }, label: 'A' },
{ value: { name: 'b' }, label: 'B' },
{ value: { name: 'c' }, label: 'C', disabled: true },
];
const { result } = renderHook(() =>
useSelect<{ name: string }, true>({
multiple: true,
options,
areOptionsEqual: (a, b) => a.name === b.name,
defaultValue: [{ name: 'a' }, { name: 'b' }],
name: 'foo',
required: true,
}),
);
sinon.assert.match(result.current.getHiddenInputProps(), {
name: 'foo',
tabIndex: -1,
'aria-hidden': true,
required: true,
value: JSON.stringify([{ name: 'a' }, { name: 'b' }]),
});
});
describe('onChange handler', () => {
it('calls external onChange handler', () => {
const externalOnChangeSpy = sinon.spy();
const { result } = renderHook(() => useSelect({}));
const { getHiddenInputProps } = result.current;
const { onChange: hiddenInputOnChange } = getHiddenInputProps({
onChange: externalOnChangeSpy,
});
// @ts-ignore We only need the target value for this test
hiddenInputOnChange({ target: { value: 'foo' } });
expect(externalOnChangeSpy.calledOnce).to.equal(true);
expect(externalOnChangeSpy.calledWith({ target: { value: 'foo' } })).to.equal(true);
});
});
});
});
| 6,345
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/useSelect.ts
|
'use client';
import * as React from 'react';
import {
unstable_useForkRef as useForkRef,
unstable_useId as useId,
unstable_useEnhancedEffect as useEnhancedEffect,
} from '@mui/utils';
import { useButton } from '../useButton';
import {
ButtonClickAction,
SelectAction,
SelectActionTypes,
SelectInternalState,
SelectValue,
UseSelectButtonSlotProps,
UseSelectHiddenInputSlotProps,
UseSelectListboxSlotProps,
UseSelectParameters,
UseSelectReturnValue,
} from './useSelect.types';
import { ListActionTypes, useList, UseListParameters } from '../useList';
import { EventHandlers } from '../utils/types';
import { defaultOptionStringifier } from './defaultOptionStringifier';
import { SelectProviderValue } from './SelectProvider';
import { useCompoundParent } from '../useCompound';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { SelectOption } from '../useOption/useOption.types';
import { selectReducer } from './selectReducer';
import { combineHooksSlotProps } from '../utils/combineHooksSlotProps';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
// visually hidden style based on https://webaim.org/techniques/css/invisiblecontent/
const visuallyHiddenStyle: React.CSSProperties = {
clip: 'rect(1px, 1px, 1px, 1px)',
clipPath: 'inset(50%)',
height: '1px',
width: '1px',
margin: '-1px',
overflow: 'hidden',
padding: 0,
position: 'absolute',
left: '50%',
bottom: 0, // to display the native browser validation error at the bottom of the Select.
};
function defaultFormValueProvider<OptionValue>(
selectedOption: SelectOption<OptionValue> | SelectOption<OptionValue>[] | null,
) {
if (Array.isArray(selectedOption)) {
if (selectedOption.length === 0) {
return '';
}
return JSON.stringify(selectedOption.map((o) => o.value));
}
if (selectedOption?.value == null) {
return '';
}
if (typeof selectedOption.value === 'string' || typeof selectedOption.value === 'number') {
return selectedOption.value;
}
return JSON.stringify(selectedOption.value);
}
function preventDefault(event: React.SyntheticEvent) {
event.preventDefault();
}
/**
*
* Demos:
*
* - [Select](https://mui.com/base-ui/react-select/#hooks)
*
* API:
*
* - [useSelect API](https://mui.com/base-ui/react-select/hooks-api/#use-select)
*/
function useSelect<OptionValue, Multiple extends boolean = false>(
props: UseSelectParameters<OptionValue, Multiple>,
): UseSelectReturnValue<OptionValue, Multiple> {
const {
areOptionsEqual,
buttonRef: buttonRefProp,
defaultOpen = false,
defaultValue: defaultValueProp,
disabled = false,
listboxId: listboxIdProp,
listboxRef: listboxRefProp,
multiple = false as Multiple,
name,
required,
onChange,
onHighlightChange,
onOpenChange,
open: openProp,
options: optionsParam,
getOptionAsString = defaultOptionStringifier,
getSerializedValue = defaultFormValueProvider,
value: valueProp,
} = props;
const buttonRef = React.useRef<HTMLElement>(null);
const handleButtonRef = useForkRef(buttonRefProp, buttonRef);
const listboxRef = React.useRef<HTMLElement>(null);
const listboxId = useId(listboxIdProp);
let defaultValue: OptionValue[] | undefined;
if (valueProp === undefined && defaultValueProp === undefined) {
defaultValue = [];
} else if (defaultValueProp !== undefined) {
if (multiple) {
defaultValue = defaultValueProp as OptionValue[];
} else {
defaultValue = defaultValueProp == null ? [] : [defaultValueProp as OptionValue];
}
}
const value = React.useMemo(() => {
if (valueProp !== undefined) {
if (multiple) {
return valueProp as OptionValue[];
}
return valueProp == null ? [] : [valueProp as OptionValue];
}
return undefined;
}, [valueProp, multiple]);
const { subitems, contextValue: compoundComponentContextValue } = useCompoundParent<
OptionValue,
SelectOption<OptionValue>
>();
const options = React.useMemo(() => {
if (optionsParam != null) {
return new Map(
optionsParam.map((option, index) => [
option.value,
{
value: option.value,
label: option.label,
disabled: option.disabled,
ref: React.createRef<HTMLElement>(),
id: `${listboxId}_${index}`,
},
]),
);
}
return subitems;
}, [optionsParam, subitems, listboxId]);
const handleListboxRef = useForkRef(listboxRefProp, listboxRef);
const {
getRootProps: getButtonRootProps,
active: buttonActive,
focusVisible: buttonFocusVisible,
rootRef: mergedButtonRef,
} = useButton({
disabled,
rootRef: handleButtonRef,
});
const optionValues = React.useMemo(() => Array.from(options.keys()), [options]);
const getOptionByValue = React.useCallback(
(valueToGet: OptionValue) => {
// This can't be simply `options.get(valueToGet)` because of the `areOptionsEqual` prop.
// If it's provided, we assume that the user wants to compare the options by value.
if (areOptionsEqual !== undefined) {
const similarValue = optionValues.find((optionValue) =>
areOptionsEqual(optionValue, valueToGet),
)!;
return options.get(similarValue);
}
return options.get(valueToGet);
},
[options, areOptionsEqual, optionValues],
);
const isItemDisabled = React.useCallback(
(valueToCheck: OptionValue) => {
const option = getOptionByValue(valueToCheck);
return option?.disabled ?? false;
},
[getOptionByValue],
);
const stringifyOption = React.useCallback(
(valueToCheck: OptionValue) => {
const option = getOptionByValue(valueToCheck);
if (!option) {
return '';
}
return getOptionAsString(option);
},
[getOptionByValue, getOptionAsString],
);
const controlledState = React.useMemo(
() => ({
selectedValues: value,
open: openProp,
}),
[value, openProp],
);
const getItemId = React.useCallback(
(itemValue: OptionValue) => options.get(itemValue)?.id,
[options],
);
const handleSelectionChange = React.useCallback(
(
event:
| React.MouseEvent<Element, MouseEvent>
| React.KeyboardEvent<Element>
| React.FocusEvent<Element, Element>
| null,
newValues: OptionValue[],
) => {
if (multiple) {
onChange?.(event, newValues as SelectValue<OptionValue, Multiple>);
} else {
onChange?.(event, (newValues[0] ?? null) as SelectValue<OptionValue, Multiple>);
}
},
[multiple, onChange],
);
const handleHighlightChange = React.useCallback(
(
event:
| React.MouseEvent<Element, MouseEvent>
| React.KeyboardEvent<Element>
| React.FocusEvent<Element, Element>
| null,
newValue: OptionValue | null,
) => {
onHighlightChange?.(event, newValue ?? null);
},
[onHighlightChange],
);
const handleStateChange = React.useCallback(
(event: React.SyntheticEvent | null, field: string, fieldValue: any) => {
if (field === 'open') {
onOpenChange?.(fieldValue as boolean);
if (fieldValue === false && event?.type !== 'blur') {
buttonRef.current?.focus();
}
}
},
[onOpenChange],
);
const useListParameters: UseListParameters<
OptionValue,
SelectInternalState<OptionValue>,
SelectAction<OptionValue>,
{ multiple: boolean }
> = {
getInitialState: () => ({
highlightedValue: null,
selectedValues: defaultValue ?? [],
open: defaultOpen,
}),
getItemId,
controlledProps: controlledState,
itemComparer: areOptionsEqual,
isItemDisabled,
rootRef: mergedButtonRef,
onChange: handleSelectionChange,
onHighlightChange: handleHighlightChange,
onStateChange: handleStateChange,
reducerActionContext: React.useMemo(() => ({ multiple }), [multiple]),
items: optionValues,
getItemAsString: stringifyOption,
selectionMode: multiple ? 'multiple' : 'single',
stateReducer: selectReducer,
};
const {
dispatch,
getRootProps: getListboxRootProps,
contextValue: listContextValue,
state: { open, highlightedValue: highlightedOption, selectedValues: selectedOptions },
rootRef: mergedListRootRef,
} = useList(useListParameters);
const createHandleButtonMouseDown =
(externalEventHandlers?: EventHandlers) => (event: React.MouseEvent & MuiCancellableEvent) => {
externalEventHandlers?.onMouseDown?.(event);
if (!event.defaultMuiPrevented) {
const action: ButtonClickAction = {
type: SelectActionTypes.buttonClick,
event,
};
dispatch(action);
}
};
useEnhancedEffect(() => {
// Scroll to the currently highlighted option.
if (highlightedOption != null) {
const optionRef = getOptionByValue(highlightedOption)?.ref;
if (!listboxRef.current || !optionRef?.current) {
return;
}
const listboxClientRect = listboxRef.current.getBoundingClientRect();
const optionClientRect = optionRef.current.getBoundingClientRect();
if (optionClientRect.top < listboxClientRect.top) {
listboxRef.current.scrollTop -= listboxClientRect.top - optionClientRect.top;
} else if (optionClientRect.bottom > listboxClientRect.bottom) {
listboxRef.current.scrollTop += optionClientRect.bottom - listboxClientRect.bottom;
}
}
}, [highlightedOption, getOptionByValue]);
const getOptionMetadata = React.useCallback(
(optionValue: OptionValue) => getOptionByValue(optionValue),
[getOptionByValue],
);
const getSelectTriggerProps = <OtherHandlers extends EventHandlers>(
otherHandlers: OtherHandlers = {} as OtherHandlers,
) => {
return {
...otherHandlers,
onMouseDown: createHandleButtonMouseDown(otherHandlers),
ref: mergedListRootRef,
role: 'combobox' as const,
'aria-expanded': open,
'aria-controls': listboxId,
};
};
const getButtonProps = <ExternalProps extends Record<string, unknown>>(
externalProps: ExternalProps = {} as ExternalProps,
): UseSelectButtonSlotProps<ExternalProps> => {
const externalEventHandlers = extractEventHandlers(externalProps);
const listboxAndButtonProps = combineHooksSlotProps(getButtonRootProps, getListboxRootProps);
const combinedProps = combineHooksSlotProps(listboxAndButtonProps, getSelectTriggerProps);
return {
...externalProps,
...combinedProps(externalEventHandlers),
};
};
const getListboxProps = <ExternalProps extends Record<string, unknown>>(
externalProps: ExternalProps = {} as ExternalProps,
): UseSelectListboxSlotProps<ExternalProps> => {
return {
...externalProps,
id: listboxId,
role: 'listbox' as const,
'aria-multiselectable': multiple ? 'true' : undefined,
ref: handleListboxRef,
onMouseDown: preventDefault, // to prevent the button from losing focus when interacting with the listbox
};
};
React.useDebugValue({
selectedOptions,
highlightedOption,
open,
});
const contextValue: SelectProviderValue<OptionValue> = React.useMemo(
() => ({
...listContextValue,
...compoundComponentContextValue,
}),
[listContextValue, compoundComponentContextValue],
);
let selectValue: SelectValue<OptionValue, Multiple>;
if (props.multiple) {
selectValue = selectedOptions as SelectValue<OptionValue, Multiple>;
} else {
selectValue = (selectedOptions.length > 0 ? selectedOptions[0] : null) as SelectValue<
OptionValue,
Multiple
>;
}
let selectedOptionsMetadata: SelectValue<SelectOption<OptionValue>, Multiple>;
if (multiple) {
selectedOptionsMetadata = (selectValue as OptionValue[])
.map((v) => getOptionMetadata(v))
.filter((o) => o !== undefined) as SelectValue<SelectOption<OptionValue>, Multiple>;
} else {
selectedOptionsMetadata = (getOptionMetadata(selectValue as OptionValue) ??
null) as SelectValue<SelectOption<OptionValue>, Multiple>;
}
const createHandleHiddenInputChange =
(externalEventHandlers?: EventHandlers) =>
(event: React.ChangeEvent<HTMLInputElement> & MuiCancellableEvent) => {
externalEventHandlers?.onChange?.(event);
if (event.defaultMuiPrevented) {
return;
}
const option = options.get(event.target.value as OptionValue);
// support autofill
if (event.target.value === '') {
dispatch({
type: ListActionTypes.clearSelection,
});
} else if (option !== undefined) {
dispatch({
type: SelectActionTypes.browserAutoFill,
item: option.value,
event,
});
}
};
const getHiddenInputProps = <ExternalProps extends Record<string, unknown>>(
externalProps: ExternalProps = {} as ExternalProps,
): UseSelectHiddenInputSlotProps<ExternalProps> => {
const externalEventHandlers = extractEventHandlers(externalProps);
return {
name,
tabIndex: -1,
'aria-hidden': true,
required: required ? true : undefined,
value: getSerializedValue(selectedOptionsMetadata),
style: visuallyHiddenStyle,
...externalProps,
onChange: createHandleHiddenInputChange(externalEventHandlers),
};
};
return {
buttonActive,
buttonFocusVisible,
buttonRef: mergedButtonRef,
contextValue,
disabled,
dispatch,
getButtonProps,
getHiddenInputProps,
getListboxProps,
getOptionMetadata,
listboxRef: mergedListRootRef,
open,
options: optionValues,
value: selectValue,
highlightedOption,
};
}
export { useSelect };
| 6,346
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSelect/useSelect.types.ts
|
import * as React from 'react';
import { ListAction, ListState, UseListRootSlotProps } from '../useList';
import { SelectOption } from '../useOption/useOption.types';
import { SelectProviderValue } from './SelectProvider';
import { MuiCancellableEventHandler } from '../utils/MuiCancellableEvent';
export type SelectChangeEventType =
| React.MouseEvent<Element, MouseEvent>
| React.KeyboardEvent<Element>
| React.FocusEvent<Element, Element>
| null;
export type SelectValue<Value, Multiple> = Multiple extends true ? Value[] : Value | null;
export interface SelectOptionDefinition<Value> {
value: Value;
disabled?: boolean;
label: string;
}
export interface UseSelectParameters<OptionValue, Multiple extends boolean = false> {
/**
* A function used to determine if two options' values are equal.
* By default, reference equality is used.
*
* There is a performance impact when using the `areOptionsEqual` prop (proportional to the number of options).
* Therefore, it's recommented to use the default reference equality comparison whenever possible.
*/
areOptionsEqual?: (a: OptionValue, b: OptionValue) => boolean;
/**
* If `true`, the select will be open by default.
* @default false
*/
defaultOpen?: boolean;
/**
* The default selected value. Use when the component is not controlled.
*/
defaultValue?: SelectValue<OptionValue, Multiple>;
/**
* If `true`, the select is disabled.
* @default false
*/
disabled?: boolean;
/**
* The ref of the trigger button element.
*/
buttonRef?: React.Ref<Element>;
/**
* The `id` attribute of the listbox element.
*/
listboxId?: string;
/**
* The ref of the listbox element.
*/
listboxRef?: React.Ref<Element>;
/**
* If `true`, the end user can select multiple values.
* This affects the type of the `value`, `defaultValue`, and `onChange` props.
*
* @default false
*/
multiple?: Multiple;
/**
* The `name` attribute of the hidden input element.
* This is useful when the select is embedded in a form and you want to access the selected value in the form data.
*/
name?: string;
/**
* If `true`, the select embedded in a form must have a selected value.
* Otherwise, the form submission will fail.
*/
required?: boolean;
/**
* Callback fired when an option is selected.
*/
onChange?: (
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null,
value: SelectValue<OptionValue, Multiple>,
) => void;
/**
* Callback fired when an option is highlighted.
*/
onHighlightChange?: (
event:
| React.MouseEvent<Element, MouseEvent>
| React.KeyboardEvent<Element>
| React.FocusEvent<Element, Element>
| null,
highlighted: OptionValue | null,
) => void;
/**
* Callback fired when the listbox is opened or closed.
*/
onOpenChange?: (open: boolean) => void;
/**
* Controls the open state of the select's listbox.
* This is the controlled equivalent of the `defaultOpen` prop.
*/
open?: boolean;
/**
* An alternative way to specify the options.
* If this parameter is set, options defined as JSX children are ignored.
*/
options?: SelectOptionDefinition<OptionValue>[];
/**
* A function to convert the currently selected value to a string.
* Used to set a value of a hidden input associated with the select,
* so that the selected value can be posted with a form.
*/
getSerializedValue?: (
option: SelectValue<SelectOption<OptionValue>, Multiple>,
) => React.InputHTMLAttributes<HTMLInputElement>['value'];
/**
* A function used to convert the option label to a string.
* This is useful when labels are elements and need to be converted to plain text
* to enable keyboard navigation with character keys.
*
* @default defaultOptionStringifier
*/
getOptionAsString?: (option: SelectOption<OptionValue>) => string;
/**
* The selected value.
* Set to `null` to deselect all options.
*/
value?: SelectValue<OptionValue, Multiple>;
}
interface UseSelectButtonSlotEventHandlers {
onMouseDown: MuiCancellableEventHandler<React.MouseEvent>;
}
export type UseSelectButtonSlotProps<TOther = {}> = UseListRootSlotProps<
Omit<TOther, keyof UseSelectButtonSlotEventHandlers>
> &
UseSelectButtonSlotEventHandlers & {
'aria-expanded': React.AriaAttributes['aria-expanded'];
'aria-controls': React.AriaAttributes['aria-controls'];
role: React.HTMLAttributes<Element>['role'];
ref: React.RefCallback<Element> | null;
};
interface UseSelectHiddenInputSlotEventHandlers {
onChange: MuiCancellableEventHandler<React.ChangeEvent<HTMLInputElement>>;
}
export type UseSelectHiddenInputSlotProps<TOther = {}> = UseSelectHiddenInputSlotEventHandlers &
React.InputHTMLAttributes<HTMLInputElement> &
TOther;
interface UseSelectListboxSlotEventHandlers {
onMouseDown: React.MouseEventHandler;
}
export type UseSelectListboxSlotProps<TOther = {}> = Omit<
TOther,
keyof UseSelectListboxSlotEventHandlers
> &
UseSelectListboxSlotEventHandlers & {
'aria-multiselectable': React.AriaAttributes['aria-multiselectable'];
id: string | undefined;
ref: React.RefCallback<Element> | null;
role: React.HTMLAttributes<Element>['role'];
};
export interface UseSelectReturnValue<Value, Multiple> {
/**
* If `true`, the trigger button is active (pressed).
*/
buttonActive: boolean;
/**
* If `true`, the trigger button has a visible focus.
*/
buttonFocusVisible: boolean;
/**
* Ref to the button slot DOM node.
*/
buttonRef: React.RefCallback<Element> | null;
/**
* If `true`, the select is disabled.
*/
disabled: boolean;
/**
* Action dispatcher for the select component.
* Allows to programmatically control the select.
*/
dispatch: (action: ListAction<Value> | SelectAction<Value>) => void;
/**
* Resolver for the button slot's props.
* @param externalProps event handlers for the button slot
* @returns props that should be spread on the button slot
*/
getButtonProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseSelectButtonSlotProps<ExternalProps>;
/**
* Resolver for the hidden input slot's props.
* @param externalProps event handlers for the hidden input slot
* @returns HTML input attributes that should be spread on the hidden input slot
*/
getHiddenInputProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseSelectHiddenInputSlotProps<ExternalProps>;
/**
* Resolver for the listbox slot's props.
* @param externalProps event handlers for the listbox slot
* @returns props that should be spread on the listbox slot
*/
getListboxProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseSelectListboxSlotProps<ExternalProps>;
/**
* A function that returns the metadata of an option with a given value.
*
* @param optionValue the value of the option
* @returns
*/
getOptionMetadata: (optionValue: Value) => SelectOption<Value> | undefined;
/**
* A value to be passed to the `SelectProvider` component.
*/
contextValue: SelectProviderValue<Value>;
/**
* The value of the highlighted option.
*/
highlightedOption: Value | null;
/**
* Ref to the listbox slot DOM node.
*/
listboxRef: React.RefCallback<Element> | null;
/**
* If `true`, the listbox is open.
*/
open: boolean;
/**
* Values of all the registered options.
*/
options: Value[];
/**
* The value of the selected option(s).
*/
value: SelectValue<Value, Multiple>;
}
export const SelectActionTypes = {
buttonClick: 'buttonClick',
browserAutoFill: 'browserAutoFill',
} as const;
export interface ButtonClickAction {
type: typeof SelectActionTypes.buttonClick;
event: React.MouseEvent;
}
export interface BrowserAutofillAction<OptionValue> {
type: typeof SelectActionTypes.browserAutoFill;
item: OptionValue;
event: React.ChangeEvent;
}
export type SelectAction<OptionValue> = ButtonClickAction | BrowserAutofillAction<OptionValue>;
export interface SelectInternalState<OptionValue> extends ListState<OptionValue> {
open: boolean;
}
| 6,347
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSlider/index.ts
|
'use client';
export * from './useSlider';
export * from './useSlider.types';
| 6,348
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSlider/useSlider.test.js
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from '@mui-internal/test-utils';
import { useSlider } from './useSlider';
describe('useSlider', () => {
const { render } = createRenderer();
describe('getRootProps', () => {
it('forwards external props including event handlers', () => {
const rootRef = React.createRef();
const handleClick = spy();
function Test() {
const { getRootProps } = useSlider({
rootRef,
marks: [
{
label: 'One',
value: 1,
},
],
});
return (
<div {...getRootProps({ 'data-testid': 'test-slider-root', onClick: handleClick })} />
);
}
render(<Test />);
const slider = screen.getByTestId('test-slider-root');
expect(slider).not.to.equal(null);
expect(rootRef.current).to.deep.equal(slider);
fireEvent.click(slider);
expect(handleClick.callCount).to.equal(1);
});
});
describe('getHiddenInputProps', () => {
function Test(
props = {
slotProps: {
input: {},
},
},
) {
const { getRootProps, getThumbProps, getHiddenInputProps } = useSlider({
marks: [
{
label: 'One',
value: 1,
},
],
});
return (
<div {...getRootProps()}>
<div {...getThumbProps()}>
<input
value={1}
{...getHiddenInputProps({ 'data-testid': 'test-input', ...props.slotProps.input })}
/>
</div>
</div>
);
}
it('forwards external props including event handlers', () => {
const handleClick = spy();
render(
<Test
slotProps={{
input: {
onClick: handleClick,
},
}}
/>,
);
const input = screen.getByTestId('test-input');
expect(input).not.to.equal(null);
fireEvent.click(input);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,349
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSlider/useSlider.ts
|
'use client';
import * as React from 'react';
import {
unstable_ownerDocument as ownerDocument,
unstable_useControlled as useControlled,
unstable_useEnhancedEffect as useEnhancedEffect,
unstable_useEventCallback as useEventCallback,
unstable_useForkRef as useForkRef,
unstable_useIsFocusVisible as useIsFocusVisible,
visuallyHidden,
} from '@mui/utils';
import {
Mark,
UseSliderHiddenInputProps,
UseSliderParameters,
UseSliderReturnValue,
UseSliderRootSlotProps,
UseSliderThumbSlotProps,
} from './useSlider.types';
import { areArraysEqual, EventHandlers, extractEventHandlers } from '../utils';
const INTENTIONAL_DRAG_COUNT_THRESHOLD = 2;
function asc(a: number, b: number) {
return a - b;
}
function clamp(value: number, min: number, max: number) {
if (value == null) {
return min;
}
return Math.min(Math.max(min, value), max);
}
function findClosest(values: number[], currentValue: number) {
const { index: closestIndex } =
values.reduce<{ distance: number; index: number } | null>(
(acc, value: number, index: number) => {
const distance = Math.abs(currentValue - value);
if (acc === null || distance < acc.distance || distance === acc.distance) {
return {
distance,
index,
};
}
return acc;
},
null,
) ?? {};
return closestIndex;
}
function trackFinger(
event: TouchEvent | MouseEvent | React.MouseEvent,
touchId: React.RefObject<any>,
) {
// The event is TouchEvent
if (touchId.current !== undefined && (event as TouchEvent).changedTouches) {
const touchEvent = event as TouchEvent;
for (let i = 0; i < touchEvent.changedTouches.length; i += 1) {
const touch = touchEvent.changedTouches[i];
if (touch.identifier === touchId.current) {
return {
x: touch.clientX,
y: touch.clientY,
};
}
}
return false;
}
// The event is MouseEvent
return {
x: (event as MouseEvent).clientX,
y: (event as MouseEvent).clientY,
};
}
export function valueToPercent(value: number, min: number, max: number) {
return ((value - min) * 100) / (max - min);
}
function percentToValue(percent: number, min: number, max: number) {
return (max - min) * percent + min;
}
function getDecimalPrecision(num: number) {
// This handles the case when num is very small (0.00000001), js will turn this into 1e-8.
// When num is bigger than 1 or less than -1 it won't get converted to this notation so it's fine.
if (Math.abs(num) < 1) {
const parts = num.toExponential().split('e-');
const matissaDecimalPart = parts[0].split('.')[1];
return (matissaDecimalPart ? matissaDecimalPart.length : 0) + parseInt(parts[1], 10);
}
const decimalPart = num.toString().split('.')[1];
return decimalPart ? decimalPart.length : 0;
}
function roundValueToStep(value: number, step: number, min: number) {
const nearest = Math.round((value - min) / step) * step + min;
return Number(nearest.toFixed(getDecimalPrecision(step)));
}
function setValueIndex({
values,
newValue,
index,
}: {
values: number[];
newValue: number;
index: number;
}) {
const output = values.slice();
output[index] = newValue;
return output.sort(asc);
}
function focusThumb({
sliderRef,
activeIndex,
setActive,
}: {
sliderRef: React.RefObject<any>;
activeIndex: number;
setActive?: (num: number) => void;
}) {
const doc = ownerDocument(sliderRef.current);
if (
!sliderRef.current?.contains(doc.activeElement) ||
Number(doc?.activeElement?.getAttribute('data-index')) !== activeIndex
) {
sliderRef.current?.querySelector(`[type="range"][data-index="${activeIndex}"]`).focus();
}
if (setActive) {
setActive(activeIndex);
}
}
function areValuesEqual(
newValue: number | Array<number>,
oldValue: number | Array<number>,
): boolean {
if (typeof newValue === 'number' && typeof oldValue === 'number') {
return newValue === oldValue;
}
if (typeof newValue === 'object' && typeof oldValue === 'object') {
return areArraysEqual(newValue, oldValue);
}
return false;
}
const axisProps = {
horizontal: {
offset: (percent: number) => ({ left: `${percent}%` }),
leap: (percent: number) => ({ width: `${percent}%` }),
},
'horizontal-reverse': {
offset: (percent: number) => ({ right: `${percent}%` }),
leap: (percent: number) => ({ width: `${percent}%` }),
},
vertical: {
offset: (percent: number) => ({ bottom: `${percent}%` }),
leap: (percent: number) => ({ height: `${percent}%` }),
},
};
export const Identity = (x: any) => x;
// TODO: remove support for Safari < 13.
// https://caniuse.com/#search=touch-action
//
// Safari, on iOS, supports touch action since v13.
// Over 80% of the iOS phones are compatible
// in August 2020.
// Utilizing the CSS.supports method to check if touch-action is supported.
// Since CSS.supports is supported on all but Edge@12 and IE and touch-action
// is supported on both Edge@12 and IE if CSS.supports is not available that means that
// touch-action will be supported
let cachedSupportsTouchActionNone: any;
function doesSupportTouchActionNone() {
if (cachedSupportsTouchActionNone === undefined) {
if (typeof CSS !== 'undefined' && typeof CSS.supports === 'function') {
cachedSupportsTouchActionNone = CSS.supports('touch-action', 'none');
} else {
cachedSupportsTouchActionNone = true;
}
}
return cachedSupportsTouchActionNone;
}
/**
*
* Demos:
*
* - [Slider](https://mui.com/base-ui/react-slider/#hook)
*
* API:
*
* - [useSlider API](https://mui.com/base-ui/react-slider/hooks-api/#use-slider)
*/
export function useSlider(parameters: UseSliderParameters): UseSliderReturnValue {
const {
'aria-labelledby': ariaLabelledby,
defaultValue,
disabled = false,
disableSwap = false,
isRtl = false,
marks: marksProp = false,
max = 100,
min = 0,
name,
onChange,
onChangeCommitted,
orientation = 'horizontal',
rootRef: ref,
scale = Identity,
step = 1,
tabIndex,
value: valueProp,
} = parameters;
const touchId = React.useRef<number>();
// We can't use the :active browser pseudo-classes.
// - The active state isn't triggered when clicking on the rail.
// - The active state isn't transferred when inversing a range slider.
const [active, setActive] = React.useState(-1);
const [open, setOpen] = React.useState(-1);
const [dragging, setDragging] = React.useState(false);
const moveCount = React.useRef(0);
const [valueDerived, setValueState] = useControlled({
controlled: valueProp,
default: defaultValue ?? min,
name: 'Slider',
});
const handleChange =
onChange &&
((event: Event | React.SyntheticEvent, value: number | number[], thumbIndex: number) => {
// Redefine target to allow name and value to be read.
// This allows seamless integration with the most popular form libraries.
// https://github.com/mui/material-ui/issues/13485#issuecomment-676048492
// Clone the event to not override `target` of the original event.
const nativeEvent = (event as React.SyntheticEvent).nativeEvent || event;
// @ts-ignore The nativeEvent is function, not object
const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
Object.defineProperty(clonedEvent, 'target', {
writable: true,
value: { value, name },
});
onChange(clonedEvent, value, thumbIndex);
});
const range = Array.isArray(valueDerived);
let values = range ? valueDerived.slice().sort(asc) : [valueDerived];
values = values.map((value) => clamp(value, min, max));
const marks =
marksProp === true && step !== null
? [...Array(Math.floor((max - min) / step) + 1)].map((_, index) => ({
value: min + step * index,
}))
: marksProp || [];
const marksValues = (marks as Mark[]).map((mark: Mark) => mark.value);
const {
isFocusVisibleRef,
onBlur: handleBlurVisible,
onFocus: handleFocusVisible,
ref: focusVisibleRef,
} = useIsFocusVisible();
const [focusedThumbIndex, setFocusedThumbIndex] = React.useState(-1);
const sliderRef = React.useRef<HTMLSpanElement>();
const handleFocusRef = useForkRef(focusVisibleRef, sliderRef);
const handleRef = useForkRef(ref, handleFocusRef);
const createHandleHiddenInputFocus =
(otherHandlers: EventHandlers) => (event: React.FocusEvent) => {
const index = Number(event.currentTarget.getAttribute('data-index'));
handleFocusVisible(event);
if (isFocusVisibleRef.current === true) {
setFocusedThumbIndex(index);
}
setOpen(index);
otherHandlers?.onFocus?.(event);
};
const createHandleHiddenInputBlur =
(otherHandlers: EventHandlers) => (event: React.FocusEvent) => {
handleBlurVisible(event);
if (isFocusVisibleRef.current === false) {
setFocusedThumbIndex(-1);
}
setOpen(-1);
otherHandlers?.onBlur?.(event);
};
useEnhancedEffect(() => {
if (disabled && sliderRef.current!.contains(document.activeElement)) {
// This is necessary because Firefox and Safari will keep focus
// on a disabled element:
// https://codesandbox.io/s/mui-pr-22247-forked-h151h?file=/src/App.js
// @ts-ignore
document.activeElement?.blur();
}
}, [disabled]);
if (disabled && active !== -1) {
setActive(-1);
}
if (disabled && focusedThumbIndex !== -1) {
setFocusedThumbIndex(-1);
}
const createHandleHiddenInputChange =
(otherHandlers: EventHandlers) => (event: React.ChangeEvent) => {
otherHandlers.onChange?.(event);
const index = Number(event.currentTarget.getAttribute('data-index'));
const value = values[index];
const marksIndex = marksValues.indexOf(value);
// @ts-ignore
let newValue = event.target.valueAsNumber;
if (marks && step == null) {
const maxMarksValue = marksValues[marksValues.length - 1];
if (newValue > maxMarksValue) {
newValue = maxMarksValue;
} else if (newValue < marksValues[0]) {
newValue = marksValues[0];
} else {
newValue = newValue < value ? marksValues[marksIndex - 1] : marksValues[marksIndex + 1];
}
}
newValue = clamp(newValue, min, max);
if (range) {
// Bound the new value to the thumb's neighbours.
if (disableSwap) {
newValue = clamp(newValue, values[index - 1] || -Infinity, values[index + 1] || Infinity);
}
const previousValue = newValue;
newValue = setValueIndex({
values,
newValue,
index,
});
let activeIndex = index;
// Potentially swap the index if needed.
if (!disableSwap) {
activeIndex = newValue.indexOf(previousValue);
}
focusThumb({ sliderRef, activeIndex });
}
setValueState(newValue);
setFocusedThumbIndex(index);
if (handleChange && !areValuesEqual(newValue, valueDerived)) {
handleChange(event, newValue, index);
}
if (onChangeCommitted) {
onChangeCommitted(event, newValue);
}
};
const previousIndex = React.useRef<number>();
let axis = orientation;
if (isRtl && orientation === 'horizontal') {
axis += '-reverse';
}
const getFingerNewValue = ({
finger,
move = false,
}: {
finger: { x: number; y: number };
move?: boolean;
}) => {
const { current: slider } = sliderRef;
const { width, height, bottom, left } = slider!.getBoundingClientRect();
let percent;
if (axis.indexOf('vertical') === 0) {
percent = (bottom - finger.y) / height;
} else {
percent = (finger.x - left) / width;
}
if (axis.indexOf('-reverse') !== -1) {
percent = 1 - percent;
}
let newValue;
newValue = percentToValue(percent, min, max);
if (step) {
newValue = roundValueToStep(newValue, step, min);
} else {
const closestIndex = findClosest(marksValues, newValue);
newValue = marksValues[closestIndex!];
}
newValue = clamp(newValue, min, max);
let activeIndex = 0;
if (range) {
if (!move) {
activeIndex = findClosest(values, newValue)!;
} else {
activeIndex = previousIndex.current!;
}
// Bound the new value to the thumb's neighbours.
if (disableSwap) {
newValue = clamp(
newValue,
values[activeIndex - 1] || -Infinity,
values[activeIndex + 1] || Infinity,
);
}
const previousValue = newValue;
newValue = setValueIndex({
values,
newValue,
index: activeIndex,
});
// Potentially swap the index if needed.
if (!(disableSwap && move)) {
activeIndex = newValue.indexOf(previousValue);
previousIndex.current = activeIndex;
}
}
return { newValue, activeIndex };
};
const handleTouchMove = useEventCallback((nativeEvent: TouchEvent | MouseEvent) => {
const finger = trackFinger(nativeEvent, touchId);
if (!finger) {
return;
}
moveCount.current += 1;
// Cancel move in case some other element consumed a mouseup event and it was not fired.
// @ts-ignore buttons doesn't not exists on touch event
if (nativeEvent.type === 'mousemove' && nativeEvent.buttons === 0) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
handleTouchEnd(nativeEvent);
return;
}
const { newValue, activeIndex } = getFingerNewValue({
finger,
move: true,
});
focusThumb({ sliderRef, activeIndex, setActive });
setValueState(newValue);
if (!dragging && moveCount.current > INTENTIONAL_DRAG_COUNT_THRESHOLD) {
setDragging(true);
}
if (handleChange && !areValuesEqual(newValue, valueDerived)) {
handleChange(nativeEvent, newValue, activeIndex);
}
});
const handleTouchEnd = useEventCallback((nativeEvent: TouchEvent | MouseEvent) => {
const finger = trackFinger(nativeEvent, touchId);
setDragging(false);
if (!finger) {
return;
}
const { newValue } = getFingerNewValue({ finger, move: true });
setActive(-1);
if (nativeEvent.type === 'touchend') {
setOpen(-1);
}
if (onChangeCommitted) {
onChangeCommitted(nativeEvent, newValue);
}
touchId.current = undefined;
// eslint-disable-next-line @typescript-eslint/no-use-before-define
stopListening();
});
const handleTouchStart = useEventCallback((nativeEvent: TouchEvent) => {
if (disabled) {
return;
}
// If touch-action: none; is not supported we need to prevent the scroll manually.
if (!doesSupportTouchActionNone()) {
nativeEvent.preventDefault();
}
const touch = nativeEvent.changedTouches[0];
if (touch != null) {
// A number that uniquely identifies the current finger in the touch session.
touchId.current = touch.identifier;
}
const finger = trackFinger(nativeEvent, touchId);
if (finger !== false) {
const { newValue, activeIndex } = getFingerNewValue({ finger });
focusThumb({ sliderRef, activeIndex, setActive });
setValueState(newValue);
if (handleChange && !areValuesEqual(newValue, valueDerived)) {
handleChange(nativeEvent, newValue, activeIndex);
}
}
moveCount.current = 0;
const doc = ownerDocument(sliderRef.current);
doc.addEventListener('touchmove', handleTouchMove);
doc.addEventListener('touchend', handleTouchEnd);
});
const stopListening = React.useCallback(() => {
const doc = ownerDocument(sliderRef.current);
doc.removeEventListener('mousemove', handleTouchMove);
doc.removeEventListener('mouseup', handleTouchEnd);
doc.removeEventListener('touchmove', handleTouchMove);
doc.removeEventListener('touchend', handleTouchEnd);
}, [handleTouchEnd, handleTouchMove]);
React.useEffect(() => {
const { current: slider } = sliderRef;
slider!.addEventListener('touchstart', handleTouchStart, {
passive: doesSupportTouchActionNone(),
});
return () => {
// @ts-ignore
slider!.removeEventListener('touchstart', handleTouchStart, {
passive: doesSupportTouchActionNone(),
});
stopListening();
};
}, [stopListening, handleTouchStart]);
React.useEffect(() => {
if (disabled) {
stopListening();
}
}, [disabled, stopListening]);
const createHandleMouseDown =
(otherHandlers: EventHandlers) => (event: React.MouseEvent<HTMLSpanElement>) => {
otherHandlers.onMouseDown?.(event);
if (disabled) {
return;
}
if (event.defaultPrevented) {
return;
}
// Only handle left clicks
if (event.button !== 0) {
return;
}
// Avoid text selection
event.preventDefault();
const finger = trackFinger(event, touchId);
if (finger !== false) {
const { newValue, activeIndex } = getFingerNewValue({ finger });
focusThumb({ sliderRef, activeIndex, setActive });
setValueState(newValue);
if (handleChange && !areValuesEqual(newValue, valueDerived)) {
handleChange(event, newValue, activeIndex);
}
}
moveCount.current = 0;
const doc = ownerDocument(sliderRef.current);
doc.addEventListener('mousemove', handleTouchMove);
doc.addEventListener('mouseup', handleTouchEnd);
};
const trackOffset = valueToPercent(range ? values[0] : min, min, max);
const trackLeap = valueToPercent(values[values.length - 1], min, max) - trackOffset;
const getRootProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseSliderRootSlotProps<ExternalProps> => {
const externalHandlers = extractEventHandlers(externalProps);
const ownEventHandlers = {
onMouseDown: createHandleMouseDown(externalHandlers || {}),
};
const mergedEventHandlers = {
...externalHandlers,
...ownEventHandlers,
};
return {
...externalProps,
ref: handleRef,
...mergedEventHandlers,
};
};
const createHandleMouseOver =
(otherHandlers: EventHandlers) => (event: React.MouseEvent<HTMLSpanElement, MouseEvent>) => {
otherHandlers.onMouseOver?.(event);
const index = Number(event.currentTarget.getAttribute('data-index'));
setOpen(index);
};
const createHandleMouseLeave =
(otherHandlers: EventHandlers) => (event: React.MouseEvent<HTMLSpanElement, MouseEvent>) => {
otherHandlers.onMouseLeave?.(event);
setOpen(-1);
};
const getThumbProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseSliderThumbSlotProps<ExternalProps> => {
const externalHandlers = extractEventHandlers(externalProps);
const ownEventHandlers = {
onMouseOver: createHandleMouseOver(externalHandlers || {}),
onMouseLeave: createHandleMouseLeave(externalHandlers || {}),
};
return {
...externalProps,
...externalHandlers,
...ownEventHandlers,
};
};
const getThumbStyle = (index: number) => {
return {
// So the non active thumb doesn't show its label on hover.
pointerEvents: active !== -1 && active !== index ? 'none' : undefined,
};
};
const getHiddenInputProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseSliderHiddenInputProps<ExternalProps> => {
const externalHandlers = extractEventHandlers(externalProps);
const ownEventHandlers = {
onChange: createHandleHiddenInputChange(externalHandlers || {}),
onFocus: createHandleHiddenInputFocus(externalHandlers || {}),
onBlur: createHandleHiddenInputBlur(externalHandlers || {}),
};
const mergedEventHandlers = {
...externalHandlers,
...ownEventHandlers,
};
return {
tabIndex,
'aria-labelledby': ariaLabelledby,
'aria-orientation': orientation,
'aria-valuemax': scale(max),
'aria-valuemin': scale(min),
name,
type: 'range',
min: parameters.min,
max: parameters.max,
step: parameters.step === null && parameters.marks ? 'any' : parameters.step ?? undefined,
disabled,
...externalProps,
...mergedEventHandlers,
style: {
...visuallyHidden,
direction: isRtl ? 'rtl' : 'ltr',
// So that VoiceOver's focus indicator matches the thumb's dimensions
width: '100%',
height: '100%',
},
};
};
return {
active,
axis: axis as keyof typeof axisProps,
axisProps,
dragging,
focusedThumbIndex,
getHiddenInputProps,
getRootProps,
getThumbProps,
marks: marks as Mark[],
open,
range,
rootRef: handleRef,
trackLeap,
trackOffset,
values,
getThumbStyle,
};
}
| 6,350
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSlider/useSlider.types.ts
|
import * as React from 'react';
export interface UseSliderParameters {
/**
* The id of the element containing a label for the slider.
*/
'aria-labelledby'?: string;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: number | number[];
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean;
/**
* If `true`, the active thumb doesn't swap when moving pointer over a thumb while dragging another thumb.
* @default false
*/
disableSwap?: boolean;
/**
* If `true` the Slider will be rendered right-to-left (with the lowest value on the right-hand side).
* @default false
*/
isRtl?: boolean;
/**
* Marks indicate predetermined values to which the user can move the slider.
* If `true` the marks are spaced according the value of the `step` prop.
* If an array, it should contain objects with `value` and an optional `label` keys.
* @default false
*/
marks?: boolean | Mark[];
/**
* The maximum allowed value of the slider.
* Should not be equal to min.
* @default 100
*/
max?: number;
/**
* The minimum allowed value of the slider.
* Should not be equal to max.
* @default 0
*/
min?: number;
/**
* Name attribute of the hidden `input` element.
*/
name?: string;
/**
* Callback function that is fired when the slider's value changed.
*
* @param {Event} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
* @param {number} activeThumb Index of the currently moved thumb.
*/
onChange?: (event: Event, value: number | number[], activeThumb: number) => void;
/**
* Callback function that is fired when the `mouseup` is triggered.
*
* @param {React.SyntheticEvent | Event} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
*/
onChangeCommitted?: (event: React.SyntheticEvent | Event, value: number | number[]) => void;
/**
* The component orientation.
* @default 'horizontal'
*/
orientation?: 'horizontal' | 'vertical';
/**
* The ref attached to the root of the Slider.
*/
rootRef?: React.Ref<Element>;
/**
* A transformation function, to change the scale of the slider.
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
scale?: (value: number) => number;
/**
* The granularity with which the slider can step through values. (A "discrete" slider.)
* The `min` prop serves as the origin for the valid values.
* We recommend (max - min) to be evenly divisible by the step.
*
* When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
* @default 1
*/
step?: number | null;
/**
* Tab index attribute of the hidden `input` element.
*/
tabIndex?: number;
/**
* The value of the slider.
* For ranged sliders, provide an array with two values.
*/
value?: number | number[];
}
export interface Mark {
value: number;
label?: React.ReactNode;
}
export type UseSliderRootSlotOwnProps = {
onMouseDown: React.MouseEventHandler;
ref: React.RefCallback<Element> | null;
};
export type UseSliderRootSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseSliderRootSlotOwnProps
> &
UseSliderRootSlotOwnProps;
export type UseSliderThumbSlotOwnProps = {
onMouseLeave: React.MouseEventHandler;
onMouseOver: React.MouseEventHandler;
};
export type UseSliderThumbSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseSliderThumbSlotOwnProps
> &
UseSliderThumbSlotOwnProps;
export type UseSliderHiddenInputOwnProps = {
'aria-labelledby'?: string;
'aria-orientation'?: React.AriaAttributes['aria-orientation'];
'aria-valuemax'?: React.AriaAttributes['aria-valuemax'];
'aria-valuemin'?: React.AriaAttributes['aria-valuemin'];
disabled: boolean;
name?: string;
onBlur: React.FocusEventHandler;
onChange: React.ChangeEventHandler;
onFocus: React.FocusEventHandler;
step?: number | 'any';
style: React.CSSProperties;
tabIndex?: number;
type?: React.InputHTMLAttributes<HTMLInputElement>['type'];
};
export type UseSliderHiddenInputProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseSliderHiddenInputOwnProps
> &
UseSliderHiddenInputOwnProps;
export type Axis = 'horizontal' | 'vertical' | 'horizontal-reverse';
export interface AxisProps<T extends Axis> {
offset: (
percent: number,
) => T extends 'horizontal'
? { left: string }
: T extends 'vertical'
? { bottom: string }
: T extends 'horizontal-reverse'
? { right: string }
: never;
leap: (
percent: number,
) => T extends 'horizontal' | 'horizontal-reverse'
? { width: string }
: T extends 'vertical'
? { height: string }
: never;
}
export interface UseSliderReturnValue {
/**
* The active index of the slider.
*/
active: number;
/**
* The orientation of the slider.
*/
axis: Axis;
/**
* Returns the `offset` and `leap` methods to calculate the positioning styles based on the slider axis.
*/
axisProps: { [key in Axis]: AxisProps<key> };
/**
* If `true`, the slider is being dragged.
*/
dragging: boolean;
/**
* The index of the thumb which is focused on the slider.
*/
focusedThumbIndex: number;
/**
* Resolver for the hidden input slot's props.
* @param externalProps props for the hidden input slot
* @returns props that should be spread on the hidden input slot
*/
getHiddenInputProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseSliderHiddenInputProps<ExternalProps>;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseSliderRootSlotProps<ExternalProps>;
/**
* Resolver for the thumb slot's props.
* @param externalProps props for the thumb slot
* @returns props that should be spread on the thumb slot
*/
getThumbProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseSliderThumbSlotProps<ExternalProps>;
/**
* Resolver for the thumb slot's style prop.
* @param index of the currently moved thumb
* @returns props that should be spread on the style prop of thumb slot
*/
getThumbStyle: (index: number) => object;
/**
* The marks of the slider. Marks indicate predetermined values to which the user can move the slider.
*/
marks: Mark[];
/**
* The thumb index for the current value when in hover state.
*/
open: number;
/**
* If `true`, the slider is a range slider when the `value` prop passed is an array.
*/
range: boolean;
/**
* Ref to the root slot's DOM node.
*/
rootRef: React.RefCallback<Element> | null;
/**
* The track leap for the current value of the slider.
*/
trackLeap: number;
/**
* The track offset for the current value of the slider.
*/
trackOffset: number;
/**
* The possible values of the slider.
*/
values: number[];
}
| 6,351
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSnackbar/index.ts
|
'use client';
export { useSnackbar } from './useSnackbar';
export * from './useSnackbar.types';
| 6,352
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSnackbar/useSnackbar.test.tsx
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { fireEvent, createRenderer } from '@mui-internal/test-utils';
import { useSnackbar, UseSnackbarParameters } from '@mui/base/useSnackbar';
describe('useSnackbar', () => {
const { render } = createRenderer();
const invokeUseSnackbar = (props: UseSnackbarParameters) => {
const ref = React.createRef<ReturnType<typeof useSnackbar>>();
function TestComponent() {
const snackbarDefinition = useSnackbar(props);
React.useImperativeHandle(ref, () => snackbarDefinition, [snackbarDefinition]);
return null;
}
render(<TestComponent />);
return ref.current!;
};
describe('getRootProps', () => {
it('returns props for the root slot', () => {
const props: UseSnackbarParameters = {};
const { getRootProps } = invokeUseSnackbar(props);
const rootProps = getRootProps();
expect(rootProps.role).to.equal('presentation');
});
it('forwards external props including event handlers', () => {
const handleClickSpy = spy();
function Snackbar() {
const { getRootProps } = useSnackbar();
return <div {...getRootProps({ onClick: handleClickSpy, random: 'arbitraryValue' })} />;
}
const { getByRole } = render(<Snackbar />);
const snackbar = getByRole('presentation');
expect(snackbar).to.have.attribute('random', 'arbitraryValue');
fireEvent.click(snackbar);
expect(handleClickSpy.callCount).to.equal(1);
});
});
});
| 6,353
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSnackbar/useSnackbar.ts
|
'use client';
import * as React from 'react';
import { unstable_useEventCallback as useEventCallback } from '@mui/utils';
import {
UseSnackbarParameters,
SnackbarCloseReason,
UseSnackbarReturnValue,
} from './useSnackbar.types';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { EventHandlers } from '../utils/types';
/**
* The basic building block for creating custom snackbar.
*
* Demos:
*
* - [Snackbar](https://mui.com/base-ui/react-snackbar/#hook)
*
* API:
*
* - [useSnackbar API](https://mui.com/base-ui/react-snackbar/hooks-api/#use-snackbar)
*/
export function useSnackbar(parameters: UseSnackbarParameters = {}): UseSnackbarReturnValue {
const {
autoHideDuration = null,
disableWindowBlurListener = false,
onClose,
open,
resumeHideDuration,
} = parameters;
const timerAutoHide = React.useRef<ReturnType<typeof setTimeout>>();
React.useEffect(() => {
if (!open) {
return undefined;
}
/**
* @param {KeyboardEvent} nativeEvent
*/
function handleKeyDown(nativeEvent: KeyboardEvent) {
if (!nativeEvent.defaultPrevented) {
// IE11, Edge (prior to using Blink?) use 'Esc'
if (nativeEvent.key === 'Escape' || nativeEvent.key === 'Esc') {
// not calling `preventDefault` since we don't know if people may ignore this event e.g. a permanently open snackbar
onClose?.(nativeEvent, 'escapeKeyDown');
}
}
}
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [open, onClose]);
const handleClose = useEventCallback((event: null, reason: SnackbarCloseReason) => {
onClose?.(event, reason);
});
const setAutoHideTimer = useEventCallback((autoHideDurationParam: number | null) => {
if (!onClose || autoHideDurationParam == null) {
return;
}
clearTimeout(timerAutoHide.current);
timerAutoHide.current = setTimeout(() => {
handleClose(null, 'timeout');
}, autoHideDurationParam);
});
React.useEffect(() => {
if (open) {
setAutoHideTimer(autoHideDuration);
}
return () => {
clearTimeout(timerAutoHide.current);
};
}, [open, autoHideDuration, setAutoHideTimer]);
const handleClickAway = (event: React.SyntheticEvent<any> | Event) => {
onClose?.(event, 'clickaway');
};
// Pause the timer when the user is interacting with the Snackbar
// or when the user hide the window.
const handlePause = () => {
clearTimeout(timerAutoHide.current);
};
// Restart the timer when the user is no longer interacting with the Snackbar
// or when the window is shown back.
const handleResume = React.useCallback(() => {
if (autoHideDuration != null) {
setAutoHideTimer(resumeHideDuration != null ? resumeHideDuration : autoHideDuration * 0.5);
}
}, [autoHideDuration, resumeHideDuration, setAutoHideTimer]);
const createHandleBlur =
(otherHandlers: EventHandlers) => (event: React.FocusEvent<HTMLDivElement, Element>) => {
const onBlurCallback = otherHandlers.onBlur;
onBlurCallback?.(event);
handleResume();
};
const createHandleFocus =
(otherHandlers: EventHandlers) => (event: React.FocusEvent<HTMLDivElement, Element>) => {
const onFocusCallback = otherHandlers.onFocus;
onFocusCallback?.(event);
handlePause();
};
const createMouseEnter =
(otherHandlers: EventHandlers) => (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
const onMouseEnterCallback = otherHandlers.onMouseEnter;
onMouseEnterCallback?.(event);
handlePause();
};
const createMouseLeave =
(otherHandlers: EventHandlers) => (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
const onMouseLeaveCallback = otherHandlers.onMouseLeave;
onMouseLeaveCallback?.(event);
handleResume();
};
React.useEffect(() => {
// TODO: window global should be refactored here
if (!disableWindowBlurListener && open) {
window.addEventListener('focus', handleResume);
window.addEventListener('blur', handlePause);
return () => {
window.removeEventListener('focus', handleResume);
window.removeEventListener('blur', handlePause);
};
}
return undefined;
}, [disableWindowBlurListener, handleResume, open]);
const getRootProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
) => {
const externalEventHandlers = {
...extractEventHandlers(parameters),
...extractEventHandlers(externalProps),
};
return {
// ClickAwayListener adds an `onClick` prop which results in the alert not being announced.
// See https://github.com/mui/material-ui/issues/29080
role: 'presentation',
...externalProps,
...externalEventHandlers,
onBlur: createHandleBlur(externalEventHandlers),
onFocus: createHandleFocus(externalEventHandlers),
onMouseEnter: createMouseEnter(externalEventHandlers),
onMouseLeave: createMouseLeave(externalEventHandlers),
};
};
return { getRootProps, onClickAway: handleClickAway };
}
| 6,354
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSnackbar/useSnackbar.types.ts
|
export type SnackbarCloseReason = 'timeout' | 'clickaway' | 'escapeKeyDown';
export interface UseSnackbarParameters {
/**
* The number of milliseconds to wait before automatically calling the
* `onClose` function. `onClose` should then set the state of the `open`
* prop to hide the Snackbar. This behavior is disabled by default with
* the `null` value.
* @default null
*/
autoHideDuration?: number | null;
/**
* If `true`, the `autoHideDuration` timer will expire even if the window is not focused.
* @default false
*/
disableWindowBlurListener?: boolean;
/**
* Callback fired when the component requests to be closed.
* Typically `onClose` is used to set state in the parent component,
* which is used to control the `Snackbar` `open` prop.
* The `reason` parameter can optionally be used to control the response to `onClose`,
* for example ignoring `clickaway`.
*
* @param {React.SyntheticEvent<any> | Event} event The event source of the callback.
* @param {string} reason Can be: `"timeout"` (`autoHideDuration` expired), `"clickaway"`, or `"escapeKeyDown"`.
*/
onClose?: (event: React.SyntheticEvent<any> | Event | null, reason: SnackbarCloseReason) => void;
/**
* If `true`, the component is shown.
*/
open?: boolean;
/**
* The number of milliseconds to wait before dismissing after user interaction.
* If `autoHideDuration` prop isn't specified, it does nothing.
* If `autoHideDuration` prop is specified but `resumeHideDuration` isn't,
* we default to `autoHideDuration / 2` ms.
*/
resumeHideDuration?: number;
}
export type UseSnackbarRootSlotProps<ExternalProps = {}> = ExternalProps &
UseSnackbarRootSlotOwnProps;
export interface UseSnackbarRootSlotOwnProps {
onBlur: React.FocusEventHandler;
onFocus: React.FocusEventHandler;
onMouseEnter: React.MouseEventHandler;
onMouseLeave: React.MouseEventHandler;
ref?: React.RefCallback<Element>;
role: React.AriaRole;
}
export interface UseSnackbarReturnValue {
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseSnackbarRootSlotProps<ExternalProps>;
/**
* Callback fired when a "click away" event is detected.
*/
onClickAway: (event: React.SyntheticEvent<any> | Event) => void;
}
| 6,355
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSwitch/index.ts
|
'use client';
export { useSwitch } from './useSwitch';
export * from './useSwitch.types';
| 6,356
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSwitch/useSwitch.test.tsx
|
import { expect } from 'chai';
import * as React from 'react';
import { spy } from 'sinon';
import {
act,
createRenderer,
focusVisible,
programmaticFocusTriggersFocusVisible,
screen,
simulatePointerDevice,
} from '@mui-internal/test-utils';
import { useSwitch, UseSwitchParameters } from '@mui/base/useSwitch';
describe('useSwitch', () => {
const { render } = createRenderer();
const invokeUseSwitch = (props: UseSwitchParameters) => {
const ref = React.createRef<ReturnType<typeof useSwitch>>();
function TestComponent() {
const switchDefinition = useSwitch(props);
React.useImperativeHandle(ref, () => switchDefinition, [switchDefinition]);
return null;
}
render(<TestComponent />);
return ref.current!;
};
describe('getInputProps', () => {
it('should include the incoming uncontrolled props in the output', () => {
const props: UseSwitchParameters = {
defaultChecked: true,
disabled: true,
readOnly: true,
required: true,
};
const { getInputProps } = invokeUseSwitch(props);
const inputProps = getInputProps();
expect(inputProps.defaultChecked).to.equal(true);
expect(inputProps.disabled).to.equal(true);
expect(inputProps.readOnly).to.equal(true);
expect(inputProps.required).to.equal(true);
});
it('should include the incoming controlled prop in the output', () => {
const props = {
checked: true,
};
const { getInputProps } = invokeUseSwitch(props);
const inputProps = getInputProps();
expect(inputProps!.checked).to.equal(true);
});
it('should call onChange if a change event is fired', () => {
const handleChange = spy();
function Switch() {
const { getInputProps } = useSwitch({ onChange: handleChange });
return <input {...getInputProps()} />;
}
render(<Switch />);
act(() => {
screen.getByRole('checkbox').click();
});
expect(handleChange.callCount).to.equal(1);
});
it('should call focus event handlers if focus events are fired', () => {
const handleBlur = spy();
const handleFocus = spy();
const handleFocusVisible = spy();
function Switch() {
const { getInputProps } = useSwitch({
onBlur: handleBlur,
onFocus: handleFocus,
onFocusVisible: handleFocusVisible,
});
return <input {...getInputProps()} />;
}
render(<Switch />);
const checkbox = screen.getByRole('checkbox');
simulatePointerDevice();
act(() => {
checkbox.focus();
});
expect(handleBlur.callCount).to.equal(0);
expect(handleFocus.callCount).to.equal(1);
expect(handleFocusVisible.callCount).to.equal(
programmaticFocusTriggersFocusVisible() ? 1 : 0,
);
act(() => {
checkbox.blur();
});
expect(handleBlur.callCount).to.equal(1);
expect(handleFocus.callCount).to.equal(1);
expect(handleFocusVisible.callCount).to.equal(
programmaticFocusTriggersFocusVisible() ? 1 : 0,
);
focusVisible(checkbox);
expect(handleBlur.callCount).to.equal(1);
expect(handleFocus.callCount).to.equal(2);
expect(handleFocusVisible.callCount).to.equal(
programmaticFocusTriggersFocusVisible() ? 2 : 1,
);
});
});
});
| 6,357
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSwitch/useSwitch.ts
|
'use client';
import * as React from 'react';
import {
unstable_useControlled as useControlled,
unstable_useForkRef as useForkRef,
unstable_useIsFocusVisible as useIsFocusVisible,
} from '@mui/utils';
import { UseSwitchParameters, UseSwitchReturnValue } from './useSwitch.types';
/**
* The basic building block for creating custom switches.
*
* Demos:
*
* - [Switch](https://mui.com/base-ui/react-switch/#hook)
*
* API:
*
* - [useSwitch API](https://mui.com/base-ui/react-switch/hooks-api/#use-switch)
*/
export function useSwitch(props: UseSwitchParameters): UseSwitchReturnValue {
const {
checked: checkedProp,
defaultChecked,
disabled,
onBlur,
onChange,
onFocus,
onFocusVisible,
readOnly,
required,
} = props;
const [checked, setCheckedState] = useControlled({
controlled: checkedProp,
default: Boolean(defaultChecked),
name: 'Switch',
state: 'checked',
});
const createHandleInputChange =
(otherProps: React.InputHTMLAttributes<HTMLInputElement>) =>
(event: React.ChangeEvent<HTMLInputElement>) => {
// Workaround for https://github.com/facebook/react/issues/9023
if (event.nativeEvent.defaultPrevented) {
return;
}
setCheckedState(event.target.checked);
onChange?.(event);
otherProps.onChange?.(event);
};
const {
isFocusVisibleRef,
onBlur: handleBlurVisible,
onFocus: handleFocusVisible,
ref: focusVisibleRef,
} = useIsFocusVisible();
const [focusVisible, setFocusVisible] = React.useState(false);
if (disabled && focusVisible) {
setFocusVisible(false);
}
React.useEffect(() => {
isFocusVisibleRef.current = focusVisible;
}, [focusVisible, isFocusVisibleRef]);
const inputRef = React.useRef<HTMLInputElement | null>(null);
const createHandleFocus =
(otherProps: React.InputHTMLAttributes<HTMLInputElement>) =>
(event: React.FocusEvent<HTMLInputElement>) => {
// Fix for https://github.com/facebook/react/issues/7769
if (!inputRef.current) {
inputRef.current = event.currentTarget;
}
handleFocusVisible(event);
if (isFocusVisibleRef.current === true) {
setFocusVisible(true);
onFocusVisible?.(event);
}
onFocus?.(event);
otherProps.onFocus?.(event);
};
const createHandleBlur =
(otherProps: React.InputHTMLAttributes<HTMLInputElement>) =>
(event: React.FocusEvent<HTMLInputElement>) => {
handleBlurVisible(event);
if (isFocusVisibleRef.current === false) {
setFocusVisible(false);
}
onBlur?.(event);
otherProps.onBlur?.(event);
};
const handleInputRef = useForkRef(focusVisibleRef, inputRef);
const getInputProps: UseSwitchReturnValue['getInputProps'] = (otherProps = {}) => ({
checked: checkedProp,
defaultChecked,
disabled,
readOnly,
ref: handleInputRef,
required,
type: 'checkbox',
...otherProps,
onChange: createHandleInputChange(otherProps),
onFocus: createHandleFocus(otherProps),
onBlur: createHandleBlur(otherProps),
});
return {
checked,
disabled: Boolean(disabled),
focusVisible,
getInputProps,
inputRef: handleInputRef,
readOnly: Boolean(readOnly),
};
}
| 6,358
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useSwitch/useSwitch.types.ts
|
import * as React from 'react';
export interface UseSwitchParameters {
/**
* If `true`, the component is checked.
*/
checked?: boolean;
/**
* The default checked state. Use when the component is not controlled.
*/
defaultChecked?: boolean;
/**
* If `true`, the component is disabled.
*/
disabled?: boolean;
onBlur?: React.FocusEventHandler;
/**
* Callback fired when the state is changed.
*
* @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
* You can pull out the new checked state by accessing `event.target.checked` (boolean).
*/
onChange?: React.ChangeEventHandler<HTMLInputElement>;
onFocus?: React.FocusEventHandler;
onFocusVisible?: React.FocusEventHandler;
/**
* If `true`, the component is read only.
*/
readOnly?: boolean;
/**
* If `true`, the `input` element is required.
*/
required?: boolean;
}
interface UseSwitchInputSlotOwnProps {
checked?: boolean;
defaultChecked?: boolean;
disabled?: boolean;
onBlur: React.FocusEventHandler;
onChange: React.ChangeEventHandler<HTMLInputElement>;
onFocus: React.FocusEventHandler;
readOnly?: boolean;
ref: React.RefCallback<HTMLInputElement> | null;
required?: boolean;
type: React.HTMLInputTypeAttribute;
}
export type UseSwitchInputSlotProps<TOther = {}> = Omit<TOther, keyof UseSwitchInputSlotOwnProps> &
UseSwitchInputSlotOwnProps;
export interface UseSwitchReturnValue {
/**
* If `true`, the component will be checked.
*/
checked: boolean;
/**
* If `true`, the component will be disabled.
*/
disabled: boolean;
/**
* If `true`, it indicates that the component is being focused using keyboard.
*/
focusVisible: boolean;
/**
* Resolver for the input slot's props.
* @param externalProps props for the input slot
* @returns props that should be spread on the input slot
*/
getInputProps: (
externalProps?: React.HTMLAttributes<HTMLInputElement>,
) => UseSwitchInputSlotProps;
/**
* Ref to the input slot's DOM node.
*/
inputRef: React.RefCallback<HTMLInputElement> | null;
/**
* If `true`, the component will be read only.
*/
readOnly: boolean;
}
| 6,359
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTab/index.ts
|
'use client';
export { useTab } from './useTab';
export * from './useTab.types';
| 6,360
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTab/useTab.test.tsx
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from '@mui-internal/test-utils';
import { Tabs } from '../Tabs';
import { TabsList } from '../TabsList';
import { useTab } from './useTab';
describe('useTab', () => {
const { render } = createRenderer();
describe('getRootProps', () => {
it('returns props for root slot', () => {
function TestTab() {
const rootRef = React.createRef<HTMLDivElement>();
const { getRootProps } = useTab({ rootRef });
return <div {...getRootProps()} />;
}
function Test() {
return (
<Tabs>
<TabsList>
<TestTab />
</TabsList>
</Tabs>
);
}
const { getByRole } = render(<Test />);
const tab = getByRole('tab');
expect(tab).not.to.equal(null);
});
it('forwards external props including event handlers', () => {
const handleClick = spy();
function TestTab() {
const rootRef = React.createRef<HTMLDivElement>();
const { getRootProps } = useTab({ rootRef });
return <div {...getRootProps({ 'data-testid': 'test-tab', onClick: handleClick })} />;
}
function Test() {
return (
<Tabs>
<TabsList>
<TestTab />
</TabsList>
</Tabs>
);
}
render(<Test />);
const tab = screen.getByTestId('test-tab');
expect(tab).not.to.equal(null);
fireEvent.click(tab);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,361
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTab/useTab.ts
|
'use client';
import * as React from 'react';
import { unstable_useId as useId, unstable_useForkRef as useForkRef } from '@mui/utils';
import { useTabsContext } from '../Tabs';
import { UseTabParameters, UseTabReturnValue, UseTabRootSlotProps } from './useTab.types';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { useCompoundItem } from '../useCompound';
import { useListItem } from '../useList';
import { useButton } from '../useButton';
import { TabMetadata } from '../useTabs';
import { combineHooksSlotProps } from '../utils/combineHooksSlotProps';
function tabValueGenerator(otherTabValues: Set<string | number>) {
return otherTabValues.size;
}
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/#hooks)
*
* API:
*
* - [useTab API](https://mui.com/base-ui/react-tabs/hooks-api/#use-tab)
*/
function useTab(parameters: UseTabParameters): UseTabReturnValue {
const { value: valueParam, rootRef: externalRef, disabled = false, id: idParam } = parameters;
const tabRef = React.useRef<HTMLElement>(null);
const id = useId(idParam);
const { value: selectedValue, selectionFollowsFocus, getTabPanelId } = useTabsContext();
const tabMetadata = React.useMemo(() => ({ disabled, ref: tabRef, id }), [disabled, tabRef, id]);
const {
id: value,
index,
totalItemCount: totalTabsCount,
} = useCompoundItem<string | number, TabMetadata>(valueParam ?? tabValueGenerator, tabMetadata);
const {
getRootProps: getTabProps,
highlighted,
selected,
} = useListItem({
item: value,
});
const {
getRootProps: getButtonProps,
rootRef: buttonRefHandler,
active,
focusVisible,
setFocusVisible,
} = useButton({
disabled,
focusableWhenDisabled: !selectionFollowsFocus,
type: 'button',
});
const handleRef = useForkRef(tabRef, externalRef, buttonRefHandler);
const tabPanelId = value !== undefined ? getTabPanelId(value) : undefined;
const getRootProps = <ExternalProps extends Record<string, unknown>>(
externalProps: ExternalProps = {} as ExternalProps,
): UseTabRootSlotProps<ExternalProps> => {
const externalEventHandlers = extractEventHandlers(externalProps);
const getCombinedRootProps = combineHooksSlotProps(getTabProps, getButtonProps);
return {
...externalProps,
...getCombinedRootProps(externalEventHandlers),
role: 'tab',
'aria-controls': tabPanelId,
'aria-selected': selected,
id,
ref: handleRef,
};
};
return {
getRootProps,
active,
focusVisible,
highlighted,
index,
rootRef: handleRef,
// the `selected` state isn't set on the server (it relies on effects to be calculated),
// so we fall back to checking the `value` prop with the selectedValue from the TabsContext
selected: selected || value === selectedValue,
setFocusVisible,
totalTabsCount,
};
}
export { useTab };
| 6,362
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTab/useTab.types.ts
|
import * as React from 'react';
import { UseButtonRootSlotProps } from '../useButton';
export interface UseTabParameters {
/**
* The value of the tab.
* It's used to associate the tab with a tab panel(s) with the same value.
* If the value is not provided, it falls back to the position index.
*/
value?: number | string;
/**
* If `true`, the tab will be disabled.
*/
onChange?: (event: React.SyntheticEvent, value: number | string) => void;
/**
* Callback fired when the tab is clicked.
*/
onClick?: React.MouseEventHandler;
/**
* If `true`, the tab will be disabled.
*/
disabled?: boolean;
/**
* The id of the tab.
* If not provided, it will be automatically generated.
*/
id?: string;
/**
* Ref to the root slot's DOM element.
*/
rootRef?: React.Ref<Element>;
}
export type UseTabRootSlotProps<ExternalProps = {}> = UseButtonRootSlotProps<ExternalProps> & {
'aria-controls': React.AriaAttributes['aria-controls'];
'aria-selected': React.AriaAttributes['aria-selected'];
id: string | undefined;
ref: React.RefCallback<Element> | null;
role: React.AriaRole;
};
export interface UseTabReturnValue {
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseTabRootSlotProps<ExternalProps>;
/**
* If `true`, the tab is active (as in `:active` pseudo-class; in other words, pressed).
*/
active: boolean;
/**
* If `true`, the tab has visible focus.
* This is a workaround for browsers that do not support this feature natively.
*/
focusVisible: boolean;
/**
* If `true`, the tab is highlighted.
*/
highlighted: boolean;
/**
* 0-based index of the tab in the list of tabs.
*/
index: number;
/**
* Ref to the root slot's DOM element.
*/
rootRef: React.RefCallback<Element> | null;
/**
* If `true`, the tab is selected.
*/
selected: boolean;
/**
* Sets the focus-visible state of the tab.
* This is a workaround for browsers that do not support this feature natively.
*/
setFocusVisible: React.Dispatch<React.SetStateAction<boolean>>;
/**
* Total number of tabs in the nearest parent TabsList.
* This can be used to determine if the tab is the last one to style it accordingly.
*/
totalTabsCount: number;
}
| 6,363
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabPanel/index.ts
|
'use client';
export { useTabPanel } from './useTabPanel';
export * from './useTabPanel.types';
| 6,364
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabPanel/useTabPanel.test.js
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from '@mui-internal/test-utils';
import { Tabs } from '../Tabs';
import { Tab } from '../Tab';
import { TabsList } from '../TabsList';
import { useTabPanel } from './useTabPanel';
describe('useTabPanel', () => {
const { render } = createRenderer();
describe('getRootProps', () => {
it('returns props for root slot', () => {
const rootRef = React.createRef();
function TestTabPanel() {
const { getRootProps } = useTabPanel({ rootRef, id: 'test-tabpanel', value: 0 });
return <div {...getRootProps()} />;
}
function Test() {
return (
<Tabs>
<TabsList>
<Tab value={0}>0</Tab>
</TabsList>
<TestTabPanel />
</Tabs>
);
}
render(<Test />);
const tabpanel = document.querySelector('#test-tabpanel');
expect(tabpanel).to.equal(rootRef.current);
});
it('forwards external props including event handlers', () => {
const handleClick = spy();
const rootRef = React.createRef();
function TestTabPanel() {
const { getRootProps } = useTabPanel({ rootRef, value: 0 });
return <div {...getRootProps({ 'data-testid': 'test-tabpanel', onClick: handleClick })} />;
}
function Test() {
return (
<Tabs>
<TabsList>
<Tab value={0}>0</Tab>
</TabsList>
<TestTabPanel />
</Tabs>
);
}
render(<Test />);
const tabPanel = screen.getByTestId('test-tabpanel');
expect(tabPanel).not.to.equal(null);
fireEvent.click(tabPanel);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,365
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabPanel/useTabPanel.ts
|
'use client';
import * as React from 'react';
import { unstable_useId as useId, unstable_useForkRef as useForkRef } from '@mui/utils';
import { useTabsContext } from '../Tabs';
import { useCompoundItem } from '../useCompound';
import {
UseTabPanelParameters,
UseTabPanelReturnValue,
UseTabPanelRootSlotProps,
} from './useTabPanel.types';
function tabPanelValueGenerator(otherTabPanelValues: Set<string | number>) {
return otherTabPanelValues.size;
}
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/#hooks)
*
* API:
*
* - [useTabPanel API](https://mui.com/base-ui/react-tabs/hooks-api/#use-tab-panel)
*/
function useTabPanel(parameters: UseTabPanelParameters): UseTabPanelReturnValue {
const { value: valueParam, id: idParam, rootRef: externalRef } = parameters;
const context = useTabsContext();
if (context === null) {
throw new Error('No TabContext provided');
}
const { value: selectedTabValue, getTabId } = context;
const id = useId(idParam);
const ref = React.useRef<HTMLElement>(null);
const handleRef = useForkRef(ref, externalRef);
const metadata = React.useMemo(() => ({ id, ref }), [id]);
const { id: value } = useCompoundItem(valueParam ?? tabPanelValueGenerator, metadata);
const hidden = value !== selectedTabValue;
const correspondingTabId = value !== undefined ? getTabId(value) : undefined;
const getRootProps = <ExternalProps extends Record<string, any> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseTabPanelRootSlotProps<ExternalProps> => {
return {
'aria-labelledby': correspondingTabId ?? undefined,
hidden,
id: id ?? undefined,
...externalProps,
ref: handleRef,
};
};
return {
hidden,
getRootProps,
rootRef: handleRef,
};
}
export { useTabPanel };
| 6,366
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabPanel/useTabPanel.types.ts
|
export interface UseTabPanelParameters {
/**
* The id of the TabPanel.
*/
id?: string;
/**
* The ref of the TabPanel.
*/
rootRef?: React.Ref<HTMLElement>;
/**
* The value of the TabPanel. It will be shown when the Tab with the corresponding value is selected.
*/
value?: number | string;
}
interface UseTabPanelRootSlotOwnProps {
'aria-labelledby'?: string;
hidden?: boolean;
id?: string;
ref: React.Ref<HTMLElement>;
}
export type UseTabPanelRootSlotProps<ExternalProps = {}> = ExternalProps &
UseTabPanelRootSlotOwnProps;
export interface UseTabPanelReturnValue {
/**
* If `true`, it indicates that the tab panel will be hidden.
*/
hidden: boolean;
/**
* 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,
) => UseTabPanelRootSlotProps<ExternalProps>;
rootRef: React.Ref<HTMLElement>;
}
| 6,367
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabs/TabsProvider.tsx
|
'use client';
import * as React from 'react';
import { TabsContext, TabsContextValue } from '../Tabs/TabsContext';
import { CompoundComponentContext, CompoundComponentContextValue } from '../useCompound';
export type TabPanelMetadata = {
id: string | undefined;
ref: React.RefObject<HTMLElement>;
};
export type TabsProviderValue = CompoundComponentContextValue<string | number, TabPanelMetadata> &
TabsContextValue;
export interface TabsProviderProps {
value: TabsProviderValue;
children: React.ReactNode;
}
/**
* Sets up the contexts for the underlying Tab and TabPanel components.
*
* @ignore - do not document.
*/
export function TabsProvider(props: TabsProviderProps) {
const { value: valueProp, children } = props;
const {
direction,
getItemIndex,
onSelected,
orientation,
registerItem,
registerTabIdLookup,
selectionFollowsFocus,
totalSubitemCount,
value,
getTabId,
getTabPanelId,
} = valueProp;
const compoundComponentContextValue: CompoundComponentContextValue<
string | number,
TabPanelMetadata
> = React.useMemo(
() => ({
getItemIndex,
registerItem,
totalSubitemCount,
}),
[registerItem, getItemIndex, totalSubitemCount],
);
const tabsContextValue: TabsContextValue = React.useMemo(
() => ({
direction,
getTabId,
getTabPanelId,
onSelected,
orientation,
registerTabIdLookup,
selectionFollowsFocus,
value,
}),
[
direction,
getTabId,
getTabPanelId,
onSelected,
orientation,
registerTabIdLookup,
selectionFollowsFocus,
value,
],
);
return (
<CompoundComponentContext.Provider value={compoundComponentContextValue}>
<TabsContext.Provider value={tabsContextValue}>{children}</TabsContext.Provider>
</CompoundComponentContext.Provider>
);
}
| 6,368
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabs/index.ts
|
'use client';
export * from './useTabs';
export * from './useTabs.types';
export * from './TabsProvider';
| 6,369
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabs/useTabs.ts
|
'use client';
import * as React from 'react';
import { unstable_useControlled as useControlled } from '@mui/utils';
import { UseTabsParameters, UseTabsReturnValue } from './useTabs.types';
import { useCompoundParent } from '../useCompound';
import { TabPanelMetadata } from './TabsProvider';
export interface TabMetadata {
disabled: boolean;
id: string | undefined;
ref: React.RefObject<HTMLElement>;
}
type IdLookupFunction = (id: string | number) => string | undefined;
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/#hooks)
*
* API:
*
* - [useTabs API](https://mui.com/base-ui/react-tabs/hooks-api/#use-tabs)
*/
function useTabs(parameters: UseTabsParameters): UseTabsReturnValue {
const {
value: valueProp,
defaultValue,
onChange,
orientation = 'horizontal',
direction = 'ltr',
selectionFollowsFocus = false,
} = parameters;
const [value, setValue] = useControlled({
controlled: valueProp,
default: defaultValue,
name: 'Tabs',
state: 'value',
});
const onSelected = React.useCallback(
(event: React.SyntheticEvent | null, newValue: string | number | null) => {
setValue(newValue);
onChange?.(event, newValue);
},
[onChange, setValue],
);
const { subitems: tabPanels, contextValue: compoundComponentContextValue } = useCompoundParent<
string | number,
TabPanelMetadata
>();
const tabIdLookup = React.useRef<IdLookupFunction>(() => undefined);
const getTabPanelId = React.useCallback(
(tabValue: string | number) => {
return tabPanels.get(tabValue)?.id;
},
[tabPanels],
);
const getTabId = React.useCallback((tabPanelId: string | number) => {
return tabIdLookup.current(tabPanelId);
}, []);
const registerTabIdLookup = React.useCallback((lookupFunction: IdLookupFunction) => {
tabIdLookup.current = lookupFunction;
}, []);
return {
contextValue: {
direction,
getTabId,
getTabPanelId,
onSelected,
orientation,
registerTabIdLookup,
selectionFollowsFocus,
value,
...compoundComponentContextValue,
},
};
}
export { useTabs };
| 6,370
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabs/useTabs.types.ts
|
import { TabsProviderValue } from './TabsProvider';
export interface UseTabsParameters {
/**
* The value of the currently selected `Tab`.
* If you don't want any selected `Tab`, you can set this prop to `false`.
*/
value?: string | number | null;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: string | number | null;
/**
* The component orientation (layout flow direction).
* @default 'horizontal'
*/
orientation?: 'horizontal' | 'vertical';
/**
* The direction of the text.
* @default 'ltr'
*/
direction?: 'ltr' | 'rtl';
/**
* Callback invoked when new value is being set.
*/
onChange?: (event: React.SyntheticEvent | null, value: number | string | null) => void;
/**
* If `true` the selected tab changes on focus. Otherwise it only
* changes on activation.
*/
selectionFollowsFocus?: boolean;
}
export interface UseTabsReturnValue {
/**
* Returns the values to be passed to the tabs provider.
*/
contextValue: TabsProviderValue;
}
| 6,371
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabsList/TabsListProvider.tsx
|
'use client';
import * as React from 'react';
import { ListContext, ListContextValue } from '../useList/ListContext';
import { TabMetadata } from '../useTabs';
import { CompoundComponentContext, CompoundComponentContextValue } from '../useCompound';
export type TabsListProviderValue = CompoundComponentContextValue<string | number, TabMetadata> &
ListContextValue<string | number>;
export interface TabsListProviderProps {
value: TabsListProviderValue;
children: React.ReactNode;
}
/**
* Sets up the contexts for the underlying Tab components.
*
* @ignore - do not document.
*/
export function TabsListProvider(props: TabsListProviderProps) {
const { value, children } = props;
const { dispatch, getItemIndex, getItemState, registerItem, totalSubitemCount } = value;
const listContextValue: ListContextValue<string | number> = React.useMemo(
() => ({
dispatch,
getItemState,
getItemIndex,
}),
[dispatch, getItemIndex, getItemState],
);
const compoundComponentContextValue: CompoundComponentContextValue<string | number, TabMetadata> =
React.useMemo(
() => ({
getItemIndex,
registerItem,
totalSubitemCount,
}),
[registerItem, getItemIndex, totalSubitemCount],
);
return (
<CompoundComponentContext.Provider value={compoundComponentContextValue}>
<ListContext.Provider value={listContextValue}>{children}</ListContext.Provider>
</CompoundComponentContext.Provider>
);
}
| 6,372
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabsList/index.ts
|
'use client';
export { useTabsList } from './useTabsList';
export * from './useTabsList.types';
export * from './TabsListProvider';
| 6,373
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabsList/tabsListReducer.ts
|
import {
ListState,
ListAction,
ListActionContext,
listReducer,
ListActionTypes,
moveHighlight,
} from '../useList';
import { ActionWithContext } from '../utils/useControllableReducer.types';
import { TabsListActionTypes, ValueChangeAction } from './useTabsList.types';
export type TabsListActionContext = ListActionContext<string | number> & {
selectionFollowsFocus: boolean;
};
export function tabsListReducer(
state: ListState<string | number>,
action: ActionWithContext<ListAction<string | number> | ValueChangeAction, TabsListActionContext>,
) {
if (action.type === TabsListActionTypes.valueChange) {
return {
...state,
highlightedValue: action.value,
};
}
const newState = listReducer(state, action);
const {
context: { selectionFollowsFocus },
} = action;
if (action.type === ListActionTypes.itemsChange) {
if (newState.selectedValues.length > 0) {
return {
...newState,
highlightedValue: newState.selectedValues[0],
};
}
moveHighlight(null, 'reset', action.context);
}
if (selectionFollowsFocus && newState.highlightedValue != null) {
return {
...newState,
selectedValues: [newState.highlightedValue],
};
}
return newState;
}
| 6,374
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabsList/useTabsList.test.tsx
|
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, screen, fireEvent } from '@mui-internal/test-utils';
import { Tabs } from '../Tabs';
import { useTabsList } from './useTabsList';
describe('useTabsList', () => {
const { render } = createRenderer();
describe('getRootProps', () => {
it('returns props for root slot', () => {
function TestTabsList() {
const rootRef = React.createRef<HTMLDivElement>();
const { getRootProps } = useTabsList({ rootRef });
return <div {...getRootProps()} />;
}
function Test() {
return (
<Tabs>
<TestTabsList />
</Tabs>
);
}
const { getByRole } = render(<Test />);
const tablist = getByRole('tablist');
expect(tablist).not.to.equal(null);
});
it('forwards external props including event handlers', () => {
const handleClick = spy();
function TestTabsList() {
const rootRef = React.createRef<HTMLDivElement>();
const { getRootProps } = useTabsList({ rootRef });
return <div {...getRootProps({ 'data-testid': 'test-tabslist', onClick: handleClick })} />;
}
function Test() {
return (
<Tabs>
<TestTabsList />
</Tabs>
);
}
render(<Test />);
const tabsList = screen.getByTestId('test-tabslist');
expect(tabsList).not.to.equal(null);
fireEvent.click(tabsList);
expect(handleClick.callCount).to.equal(1);
});
});
});
| 6,375
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabsList/useTabsList.ts
|
'use client';
import * as React from 'react';
import { useTabsContext } from '../Tabs';
import {
TabsListActionTypes,
UseTabsListParameters,
UseTabsListReturnValue,
UseTabsListRootSlotProps,
ValueChangeAction,
} from './useTabsList.types';
import { useCompoundParent } from '../useCompound';
import { TabMetadata } from '../useTabs/useTabs';
import { useList, ListState, UseListParameters } from '../useList';
import { tabsListReducer } from './tabsListReducer';
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/#hooks)
*
* API:
*
* - [useTabsList API](https://mui.com/base-ui/react-tabs/hooks-api/#use-tabs-list)
*/
function useTabsList(parameters: UseTabsListParameters): UseTabsListReturnValue {
const { rootRef: externalRef } = parameters;
const {
direction = 'ltr',
onSelected,
orientation = 'horizontal',
value,
registerTabIdLookup,
selectionFollowsFocus,
} = useTabsContext();
const { subitems, contextValue: compoundComponentContextValue } = useCompoundParent<
string | number,
TabMetadata
>();
const tabIdLookup = React.useCallback(
(tabValue: string | number) => {
return subitems.get(tabValue)?.id;
},
[subitems],
);
registerTabIdLookup(tabIdLookup);
const subitemKeys = React.useMemo(() => Array.from(subitems.keys()), [subitems]);
const getTabElement = React.useCallback(
(tabValue: string | number) => {
if (tabValue == null) {
return null;
}
return subitems.get(tabValue)?.ref.current ?? null;
},
[subitems],
);
const isRtl = direction === 'rtl';
let listOrientation: UseListParameters<any, any>['orientation'];
if (orientation === 'vertical') {
listOrientation = 'vertical';
} else {
listOrientation = isRtl ? 'horizontal-rtl' : 'horizontal-ltr';
}
const handleChange = React.useCallback(
(
event:
| React.FocusEvent<Element, Element>
| React.KeyboardEvent<Element>
| React.MouseEvent<Element, MouseEvent>
| null,
newValue: (string | number)[],
) => {
onSelected(event, newValue[0] ?? null);
},
[onSelected],
);
const controlledProps = React.useMemo(() => {
if (value === undefined) {
return {};
}
return value != null ? { selectedValues: [value] } : { selectedValues: [] };
}, [value]);
const isItemDisabled = React.useCallback(
(item: string | number) => subitems.get(item)?.disabled ?? false,
[subitems],
);
const {
contextValue: listContextValue,
dispatch,
getRootProps: getListboxRootProps,
state: { highlightedValue, selectedValues },
rootRef: mergedRootRef,
} = useList<
string | number,
ListState<string | number>,
ValueChangeAction,
{ selectionFollowsFocus: boolean }
>({
controlledProps,
disabledItemsFocusable: !selectionFollowsFocus,
focusManagement: 'DOM',
getItemDomElement: getTabElement,
isItemDisabled,
items: subitemKeys,
rootRef: externalRef,
onChange: handleChange,
orientation: listOrientation,
reducerActionContext: React.useMemo(
() => ({ selectionFollowsFocus: selectionFollowsFocus || false }),
[selectionFollowsFocus],
),
selectionMode: 'single',
stateReducer: tabsListReducer,
});
React.useEffect(() => {
if (value === undefined) {
return;
}
// when a value changes externally, the highlighted value should be synced to it
if (value != null) {
dispatch({
type: TabsListActionTypes.valueChange,
value,
});
}
}, [dispatch, value]);
const getRootProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseTabsListRootSlotProps<ExternalProps> => {
return {
...externalProps,
...getListboxRootProps(externalProps),
'aria-orientation': orientation === 'vertical' ? 'vertical' : undefined,
role: 'tablist',
};
};
const contextValue = React.useMemo(
() => ({
...compoundComponentContextValue,
...listContextValue,
}),
[compoundComponentContextValue, listContextValue],
);
return {
contextValue,
dispatch,
getRootProps,
highlightedValue,
isRtl,
orientation,
rootRef: mergedRootRef,
selectedValue: selectedValues[0] ?? null,
};
}
export { useTabsList };
| 6,376
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/useTabsList/useTabsList.types.ts
|
import * as React from 'react';
import { TabsListProviderValue } from './TabsListProvider';
import { ListAction } from '../useList';
export interface UseTabsListParameters {
/**
* Ref to the root element.
*/
rootRef: React.Ref<Element>;
}
export type UseTabsListRootSlotProps<ExternalProps = {}> = ExternalProps & {
'aria-label'?: React.AriaAttributes['aria-label'];
'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
'aria-orientation'?: React.AriaAttributes['aria-orientation'];
role: React.AriaRole;
ref: React.RefCallback<Element> | null;
onKeyDown?: React.KeyboardEventHandler<HTMLElement>;
};
export interface UseTabsListReturnValue {
/**
* The value to be passed to the TabListProvider above all the tabs.
*/
contextValue: TabsListProviderValue;
/**
* Action dispatcher for the tabs list component.
* Allows to programmatically control the tabs list.
*/
dispatch: (action: ListAction<string | number>) => void;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseTabsListRootSlotProps<ExternalProps>;
/**
* The value of the currently highlighted tab.
*/
highlightedValue: string | number | null;
/**
* If `true`, it will indicate that the text's direction in right-to-left.
*/
isRtl: boolean;
/**
* The component orientation (layout flow direction).
*/
orientation: 'horizontal' | 'vertical';
rootRef: React.RefCallback<Element> | null;
/**
* The value of the currently selected tab.
*/
selectedValue: string | number | null;
}
export const TabsListActionTypes = {
valueChange: 'valueChange',
} as const;
export interface ValueChangeAction {
type: typeof TabsListActionTypes.valueChange;
value: string | number | null;
}
| 6,377
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/ClassNameConfigurator.test.tsx
|
import * as React from 'react';
import { createRenderer } from '@mui-internal/test-utils';
import { expect } from 'chai';
import { Switch, switchClasses } from '@mui/base/Switch';
import { ClassNameConfigurator } from '@mui/base/utils/ClassNameConfigurator';
describe('ClassNameConfigurator', () => {
const { render } = createRenderer();
it('should apply default classes when not configured', () => {
const { container } = render(<Switch defaultChecked disabled />);
const switchComponent = container.firstChild!;
expect(switchComponent).to.have.class(switchClasses.root);
expect(switchComponent).to.have.class(switchClasses.checked);
expect(switchComponent).to.have.class(switchClasses.disabled);
expect(switchComponent.childNodes[0]).to.have.class(switchClasses.track);
expect(switchComponent.childNodes[1]).to.have.class(switchClasses.thumb);
expect(switchComponent.childNodes[2]).to.have.class(switchClasses.input);
});
it('should not generate any classes when configured as such', () => {
const { container } = render(
<ClassNameConfigurator disableDefaultClasses>
<Switch defaultChecked disabled />
</ClassNameConfigurator>,
);
const switchComponent = container.firstChild!;
expect(switchComponent).not.to.have.class(switchClasses.root);
expect(switchComponent).not.to.have.class(switchClasses.checked);
expect(switchComponent).not.to.have.class(switchClasses.disabled);
expect(switchComponent.childNodes[0]).not.to.have.class(switchClasses.track);
expect(switchComponent.childNodes[1]).not.to.have.class(switchClasses.thumb);
expect(switchComponent.childNodes[2]).not.to.have.class(switchClasses.input);
});
it('should not remove custom classes when disableDefaultClasses is set', () => {
const { container } = render(
<ClassNameConfigurator disableDefaultClasses>
<Switch
className="custom-switch"
slotProps={{
track: { className: 'custom-track' },
thumb: { className: 'custom-thumb' },
input: { className: 'custom-input' },
}}
/>
</ClassNameConfigurator>,
);
const switchComponent = container.firstChild!;
expect(switchComponent).to.have.class('custom-switch');
expect(switchComponent.childNodes[0]).to.have.class('custom-track');
expect(switchComponent.childNodes[1]).to.have.class('custom-thumb');
expect(switchComponent.childNodes[2]).to.have.class('custom-input');
});
});
| 6,378
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/ClassNameConfigurator.tsx
|
'use client';
import * as React from 'react';
type ClassNameConfiguration = {
/**
* If `true`, the components within the context will not have built-in classes applied.
*/
disableDefaultClasses: boolean;
};
const defaultContextValue: ClassNameConfiguration = {
disableDefaultClasses: false,
};
const ClassNameConfiguratorContext =
React.createContext<ClassNameConfiguration>(defaultContextValue);
export interface ClassNameConfiguratorProps extends Partial<ClassNameConfiguration> {
children?: React.ReactNode;
}
/**
* @ignore - internal hook.
*
* Wraps the `generateUtilityClass` function and controls how the classes are generated.
* Currently it only affects whether the classes are applied or not.
*
* @returns Function to be called with the `generateUtilityClass` function specific to a component to generate the classes.
*/
export function useClassNamesOverride(generateUtilityClass: (slot: string) => string) {
const { disableDefaultClasses } = React.useContext(ClassNameConfiguratorContext);
return (slot: string) => {
if (disableDefaultClasses) {
return '';
}
return generateUtilityClass(slot);
};
}
/**
* Allows to configure the components within to not apply any built-in classes.
*/
export function ClassNameConfigurator(props: ClassNameConfiguratorProps) {
const { disableDefaultClasses, children } = props;
const contextValue = React.useMemo(
() => ({ disableDefaultClasses: disableDefaultClasses ?? false }),
[disableDefaultClasses],
);
return (
<ClassNameConfiguratorContext.Provider value={contextValue}>
{children}
</ClassNameConfiguratorContext.Provider>
);
}
| 6,379
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/MuiCancellableEvent.ts
|
export type MuiCancellableEvent = {
defaultMuiPrevented?: boolean;
};
export type MuiCancellableEventHandler<Event> = (event: Event & MuiCancellableEvent) => void;
| 6,380
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/PolymorphicComponent.ts
|
import * as React from 'react';
import { DistributiveOmit, OverridableTypeMap } from '@mui/types';
/**
* A component whose root component can be controlled explicitly with a generic type parameter.
* Adjusts valid props based on the type of `RootComponent`.
*
* @template TypeMap The interface the defines the props and a default root element of the component.
*/
export type PolymorphicComponent<TypeMap extends OverridableTypeMap> = {
<RootComponent extends React.ElementType = TypeMap['defaultComponent']>(
props: PolymorphicProps<TypeMap, RootComponent>,
): JSX.Element | null;
propTypes?: any;
displayName?: string | undefined;
};
/**
* Own props of the component augmented with props of the root component.
*/
export type PolymorphicProps<
TypeMap extends OverridableTypeMap,
RootComponent extends React.ElementType,
> = TypeMap['props'] &
DistributiveOmit<React.ComponentPropsWithRef<RootComponent>, keyof TypeMap['props']>;
| 6,381
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/appendOwnerState.spec.tsx
|
import * as React from 'react';
import { appendOwnerState } from './appendOwnerState';
const divProps = appendOwnerState('div', { otherProp: true }, { ownerStateProps: true });
// ownerState is not available on a host component
// @ts-expect-error
const test1 = divProps.ownerState.ownerStateProps;
// @ts-expect-error
const test2 = divProps.ownerState?.ownerStateProps;
const componentProps = appendOwnerState(
() => <div />,
{ otherProp: true },
{ ownerStateProps: true },
);
// ownerState is present on a custom component
const test3: boolean = componentProps.ownerState.ownerStateProps;
function test(element: React.ElementType) {
const props = appendOwnerState(element, { otherProp: true }, { ownerStateProps: true });
// ownerState may be present on a provided element type (it depends on its exact type)
// @ts-expect-error
const test4 = props.ownerState.ownerStateProps;
const test5: boolean | undefined = props.ownerState?.ownerStateProps;
}
| 6,382
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/appendOwnerState.test.ts
|
import { expect } from 'chai';
import { appendOwnerState } from './appendOwnerState';
const ownerState = {
className: 'bar',
checked: true,
};
function CustomComponent() {
return null;
}
describe('appendOwnerState', () => {
describe('when the provided elementType is undefined', () => {
it('returns the provided existingProps without modification ', () => {
const existingProps = { className: 'foo' };
const actual = appendOwnerState(undefined, existingProps, ownerState);
expect(actual).to.equal(existingProps);
});
});
describe('when a DOM element is provided as elementType', () => {
it('returns the provided existingProps without modification ', () => {
const existingProps = { className: 'foo' };
const actual = appendOwnerState('div', existingProps, ownerState);
expect(actual).to.equal(existingProps);
});
});
describe('when a React component is provided as elementType', () => {
it('returns the provided existingProps with added ownerState', () => {
const existingProps = { className: 'foo' };
const actual = appendOwnerState(CustomComponent, existingProps, ownerState);
expect(actual).to.deep.equal({
className: 'foo',
ownerState: {
className: 'bar',
checked: true,
},
});
});
it('merges the provided ownerState with existing ones', () => {
const existingProps = {
ownerState: {
className: 'foo',
id: 'foo',
},
className: 'foo',
};
const actual = appendOwnerState(CustomComponent, existingProps, ownerState);
expect(actual).to.deep.equal({
className: 'foo',
ownerState: {
className: 'bar',
id: 'foo',
checked: true,
},
});
});
});
});
| 6,383
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/appendOwnerState.ts
|
import * as React from 'react';
import { Simplify } from '@mui/types';
import { isHostComponent } from './isHostComponent';
/**
* Type of the ownerState based on the type of an element it applies to.
* This resolves to the provided OwnerState for React components and `undefined` for host components.
* Falls back to `OwnerState | undefined` when the exact type can't be determined in development time.
*/
type OwnerStateWhenApplicable<
ElementType extends React.ElementType,
OwnerState,
> = ElementType extends React.ComponentType<any>
? OwnerState
: ElementType extends keyof JSX.IntrinsicElements
? undefined
: OwnerState | undefined;
export type AppendOwnerStateReturnType<
ElementType extends React.ElementType,
OtherProps,
OwnerState,
> = Simplify<
OtherProps & {
ownerState: OwnerStateWhenApplicable<ElementType, OwnerState>;
}
>;
/**
* Appends the ownerState object to the props, merging with the existing one if necessary.
*
* @param elementType Type of the element that owns the `existingProps`. If the element is a DOM node or undefined, `ownerState` is not applied.
* @param otherProps Props of the element.
* @param ownerState
*/
export function appendOwnerState<
ElementType extends React.ElementType,
OtherProps extends Record<string, any>,
OwnerState,
>(
elementType: ElementType | undefined,
otherProps: OtherProps,
ownerState: OwnerState,
): AppendOwnerStateReturnType<ElementType, OtherProps, OwnerState> {
if (elementType === undefined || isHostComponent(elementType)) {
return otherProps as AppendOwnerStateReturnType<ElementType, OtherProps, OwnerState>;
}
return {
...otherProps,
ownerState: { ...otherProps.ownerState, ...ownerState },
} as AppendOwnerStateReturnType<ElementType, OtherProps, OwnerState>;
}
| 6,384
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/areArraysEqual.ts
|
type ItemComparer<Item> = (a: Item, b: Item) => boolean;
export function areArraysEqual<Item>(
array1: Item[],
array2: Item[],
itemComparer: ItemComparer<Item> = (a, b) => a === b,
) {
return (
array1.length === array2.length &&
array1.every((value, index) => itemComparer(value, array2[index]))
);
}
| 6,385
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/combineHooksSlotProps.test.ts
|
import { expect } from 'chai';
import { combineHooksSlotProps } from './combineHooksSlotProps';
import { EventHandlers } from './types';
describe('combineHooksSlotProps', () => {
let log: string[];
beforeEach(() => {
log = [];
});
function getFirstSlotProps<Other extends EventHandlers>(other: Other = {} as Other) {
return {
...other,
'data-testid': 'first',
onClick: (event: React.MouseEvent) => {
other?.onClick?.(event);
log.push('first onClick');
},
onMouseDown: (event: React.MouseEvent) => {
other?.onMouseDown?.(event);
log.push('first onMouseDown');
},
};
}
function getSecondSlotProps<Other extends EventHandlers>(other: Other = {} as Other) {
return {
...other,
'data-testid': 'second',
onClick: (event: React.MouseEvent) => {
other?.onClick?.(event);
log.push('second onClick');
},
onBlur: (event: React.FocusEvent) => {
other?.onBlur?.(event);
log.push('second onBlur');
},
};
}
function getThirdSlotProps<Other extends EventHandlers>(other: Other = {} as Other) {
return {
...other,
'data-testid': 'third',
onClick: (event: React.MouseEvent) => {
other?.onClick?.(event);
log.push('third onClick');
},
};
}
it('combines two prop getters', () => {
const externalEventHandlers = {
onClick: () => {
log.push('external onClick');
},
onBlur: () => {
log.push('external onBlur');
},
onFocus: () => {
log.push('external onFocus');
},
};
const createCombinedSlotProps = combineHooksSlotProps(getFirstSlotProps, getSecondSlotProps);
const slotProps = createCombinedSlotProps(externalEventHandlers);
expect(Object.keys(slotProps)).to.deep.equal([
'onClick',
'onBlur',
'onFocus',
'data-testid',
'onMouseDown',
]);
expect(slotProps['data-testid']).to.equal('second');
slotProps.onClick({} as React.MouseEvent);
expect(log).to.deep.equal(['external onClick', 'first onClick', 'second onClick']);
log = [];
slotProps.onMouseDown({} as React.MouseEvent);
expect(log).to.deep.equal(['first onMouseDown']);
log = [];
slotProps.onBlur({} as React.FocusEvent);
expect(log).to.deep.equal(['external onBlur', 'second onBlur']);
log = [];
slotProps.onFocus();
expect(log).to.deep.equal(['external onFocus']);
});
it('can be composed', () => {
const externalEventHandlers = {
onClick: () => {
log.push('external onClick');
},
};
const createCombinedSlotProps = combineHooksSlotProps(
getFirstSlotProps,
combineHooksSlotProps(getSecondSlotProps, getThirdSlotProps),
);
const slotProps = createCombinedSlotProps(externalEventHandlers);
expect(slotProps['data-testid']).to.equal('third');
slotProps.onClick({} as React.MouseEvent);
expect(log).to.deep.equal([
'external onClick',
'first onClick',
'second onClick',
'third onClick',
]);
});
it('can be composed in another way', () => {
const externalEventHandlers = {
onClick: () => {
log.push('external onClick');
},
};
const createCombinedSlotProps = combineHooksSlotProps(
combineHooksSlotProps(getFirstSlotProps, getSecondSlotProps),
getThirdSlotProps,
);
const slotProps = createCombinedSlotProps(externalEventHandlers);
expect(slotProps['data-testid']).to.equal('third');
slotProps.onClick({} as React.MouseEvent);
expect(log).to.deep.equal([
'external onClick',
'first onClick',
'second onClick',
'third onClick',
]);
});
});
| 6,386
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/combineHooksSlotProps.ts
|
import { EventHandlers } from './types';
/**
* Combines the two get*Props functions from Base UI hooks into one.
* Useful when a hook uses two other hooks behind the scenes
* (such as useSelect that depends on useList and useButton for its root slot).
*
* The resulting function will return the combined props.
* They are merged from left to right, similarly to how Object.assign works.
*
* The getSecondProps function will receive the result of the getFirstProps function as its argument,
* so its event handlers can call the previous handlers and act depending on its result.
*
* @param getFirstProps - A getter function that returns the props for the first slot. It receives the external event handlers as its argument.
* @param getSecondProps - A getter function that returns the props for the second slot. It receives the result of the getFirstProps function as its argument.
*/
export function combineHooksSlotProps<
ExternalHandlers extends EventHandlers,
FirstSlotProps extends ExternalHandlers,
SecondSlotProps extends ExternalHandlers,
>(
getFirstProps: (external?: ExternalHandlers) => FirstSlotProps,
getSecondProps: (external?: ExternalHandlers) => SecondSlotProps,
) {
return function getCombinedProps<OtherProps extends ExternalHandlers>(
external: OtherProps = {} as OtherProps,
) {
const firstResult = {
...external,
...getFirstProps(external),
};
const result = {
...firstResult,
...getSecondProps(firstResult),
};
return result;
};
}
| 6,387
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/extractEventHandlers.test.ts
|
import { expect } from 'chai';
import { extractEventHandlers } from './extractEventHandlers';
describe('extractEventHandlers', () => {
it('extracts the fields starting with `on[A-Z]` and being a function', () => {
const input = {
onClick: () => {},
onChange: () => {},
once: () => {},
on: () => {},
onInvalid: 0,
on1: () => {},
xonClick: () => {},
};
const result = extractEventHandlers(input);
expect(result).to.deep.equal({
onClick: input.onClick,
onChange: input.onChange,
});
});
it('returns an empty object if an empty object is provided', () => {
const result = extractEventHandlers({});
expect(result).to.deep.equal({});
});
it('returns an empty object if undefined is passed in', () => {
const result = extractEventHandlers(undefined);
expect(result).to.deep.equal({});
});
it('excludes the provided handlers from the result', () => {
const input = {
onClick: () => {},
onChange: () => {},
onFocus: () => {},
};
const result = extractEventHandlers(input, ['onClick', 'onFocus']);
expect(result).to.deep.equal({ onChange: input.onChange });
});
});
| 6,388
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/extractEventHandlers.ts
|
import { EventHandlers } from './types';
/**
* Extracts event handlers from a given object.
* A prop is considered an event handler if it is a function and its name starts with `on`.
*
* @param object An object to extract event handlers from.
* @param excludeKeys An array of keys to exclude from the returned object.
*/
export function extractEventHandlers(
object: Record<string, any> | undefined,
excludeKeys: string[] = [],
): EventHandlers {
if (object === undefined) {
return {};
}
const result: EventHandlers = {};
Object.keys(object)
.filter(
(prop) =>
prop.match(/^on[A-Z]/) && typeof object[prop] === 'function' && !excludeKeys.includes(prop),
)
.forEach((prop) => {
result[prop] = object[prop];
});
return result;
}
| 6,389
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/index.ts
|
'use client';
export { appendOwnerState } from './appendOwnerState';
export { areArraysEqual } from './areArraysEqual';
export { ClassNameConfigurator } from './ClassNameConfigurator';
export { extractEventHandlers } from './extractEventHandlers';
export { isHostComponent } from './isHostComponent';
export { resolveComponentProps } from './resolveComponentProps';
export { useSlotProps } from './useSlotProps';
export { mergeSlotProps } from './mergeSlotProps';
export { prepareForSlot } from './prepareForSlot';
export * from './PolymorphicComponent';
export * from './types';
| 6,390
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/isHostComponent.ts
|
import * as React from 'react';
/**
* Determines if a given element is a DOM element name (i.e. not a React component).
*/
export function isHostComponent(element: React.ElementType) {
return typeof element === 'string';
}
| 6,391
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/mergeSlotProps.test.ts
|
import * as React from 'react';
import { expect } from 'chai';
import { mergeSlotProps } from './mergeSlotProps';
import { EventHandlers } from './types';
describe('mergeSlotProps', () => {
it('overrides the internal props with the external ones', () => {
const getSlotProps = () => ({
prop1: 'internal',
prop2: 'internal',
prop3: 'internal',
prop4: 'internal',
});
const additionalProps = {
prop1: 'additional',
prop2: 'additional',
prop3: 'additional',
};
const externalForwardedProps = {
prop1: 'externalForwarded',
prop2: 'externalForwarded',
};
const externalSlotProps = {
prop1: 'externalSlot',
};
const merged = mergeSlotProps({
getSlotProps,
additionalProps,
externalForwardedProps,
externalSlotProps,
});
expect(merged.props.prop1).to.equal('externalSlot');
expect(merged.props.prop2).to.equal('externalForwarded');
expect(merged.props.prop3).to.equal('additional');
expect(merged.props.prop4).to.equal('internal');
});
describe('it joins all class names in order from least to most important', () => {
it('when internal classNames from getSlotProps are included', () => {
const getSlotProps = () => ({
className: 'internal',
});
const additionalProps = {
className: 'additional',
};
const externalForwardedProps = {
className: 'externalForwarded',
};
const externalSlotProps = {
className: 'externalSlot',
};
const className = ['class1', 'class2'];
const merged = mergeSlotProps({
getSlotProps,
additionalProps,
externalForwardedProps,
externalSlotProps,
className,
});
expect(merged.props.className).to.equal(
'internal additional class1 class2 externalForwarded externalSlot',
);
});
it('when getSlotProps is not present', () => {
const additionalProps = {
className: 'additional',
};
const externalForwardedProps = {
className: 'externalForwarded',
};
const externalSlotProps = {
className: 'externalSlot',
};
const className = ['class1', 'class2'];
const merged = mergeSlotProps({
additionalProps,
externalForwardedProps,
externalSlotProps,
className,
});
expect(merged.props.className).to.equal(
'additional class1 class2 externalForwarded externalSlot',
);
});
});
it('merges the style props', () => {
const getSlotProps = () => ({
style: {
fontSize: '12px',
textAlign: 'center' as const,
},
});
const additionalProps = {
style: {
fontSize: '14px',
color: 'red',
},
};
const externalForwardedProps = {
style: {
fontWeight: 500,
},
};
const externalSlotProps = {
style: {
textDecoration: 'underline',
},
};
const merged = mergeSlotProps({
getSlotProps,
additionalProps,
externalForwardedProps,
externalSlotProps,
});
expect(merged.props.style).to.deep.equal({
textAlign: 'center',
color: 'red',
fontSize: '14px',
fontWeight: 500,
textDecoration: 'underline',
});
});
it('returns the ref returned from the getSlotProps function', () => {
const ref = React.createRef();
const getSlotProps = () => ({
ref,
});
const merged = mergeSlotProps({
getSlotProps,
});
expect(merged.internalRef).to.equal(ref);
});
it('does not require any parameters', () => {
const merged = mergeSlotProps({});
expect(merged.props).to.deep.equal({});
});
it('passes the external event handlers to the getSlotProps function (if defined)', () => {
const externalClickHandler = () => {};
const externalMouseOverHandler = () => {};
const getSlotProps = (eventHandlers: EventHandlers) => {
expect(eventHandlers.onClick).to.equal(externalClickHandler);
expect(eventHandlers.onMouseOver).to.equal(externalMouseOverHandler);
return {};
};
const externalForwardedProps = {
onClick: externalClickHandler,
};
const externalSlotProps = {
onMouseOver: externalMouseOverHandler,
};
const merged = mergeSlotProps({
getSlotProps,
externalForwardedProps,
externalSlotProps,
});
expect(Object.keys(merged.props)).not.to.contain('onClick');
expect(Object.keys(merged.props)).not.to.contain('onMouseOver');
});
});
| 6,392
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/mergeSlotProps.ts
|
import * as React from 'react';
import clsx, { ClassValue } from 'clsx';
import { Simplify } from '@mui/types';
import { EventHandlers } from './types';
import { extractEventHandlers } from './extractEventHandlers';
import { omitEventHandlers } from './omitEventHandlers';
export type WithCommonProps<OtherProps> = OtherProps & {
className?: string;
style?: React.CSSProperties;
ref?: React.Ref<any>;
};
export interface MergeSlotPropsParameters<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps,
> {
/**
* A function that returns the internal props of the component.
* It accepts the event handlers passed into the component by the user
* and is responsible for calling them where appropriate.
*/
getSlotProps?: (other: EventHandlers) => WithCommonProps<SlotProps>;
/**
* Props provided to the `slotProps.*` of the Base UI component.
*/
externalSlotProps?: WithCommonProps<ExternalSlotProps>;
/**
* Extra props placed on the Base UI component that should be forwarded to the slot.
* This should usually be used only for the root slot.
*/
externalForwardedProps?: WithCommonProps<ExternalForwardedProps>;
/**
* Additional props to be placed on the slot.
*/
additionalProps?: WithCommonProps<AdditionalProps>;
/**
* Extra class name(s) to be placed on the slot.
*/
className?: ClassValue | ClassValue[];
}
export type MergeSlotPropsResult<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps,
> = {
props: Simplify<
SlotProps &
ExternalForwardedProps &
ExternalSlotProps &
AdditionalProps & { className?: string; style?: React.CSSProperties }
>;
internalRef: React.Ref<any> | undefined;
};
/**
* Merges the slot component internal props (usually coming from a hook)
* with the externally provided ones.
*
* The merge order is (the latter overrides the former):
* 1. The internal props (specified as a getter function to work with get*Props hook result)
* 2. Additional props (specified internally on a Base UI component)
* 3. External props specified on the owner component. These should only be used on a root slot.
* 4. External props specified in the `slotProps.*` prop.
* 5. The `className` prop - combined from all the above.
* @param parameters
* @returns
*/
export function mergeSlotProps<
SlotProps,
ExternalForwardedProps extends Record<string, unknown>,
ExternalSlotProps extends Record<string, unknown>,
AdditionalProps,
>(
parameters: MergeSlotPropsParameters<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps
>,
): MergeSlotPropsResult<SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps> {
const { getSlotProps, additionalProps, externalSlotProps, externalForwardedProps, className } =
parameters;
if (!getSlotProps) {
// The simpler case - getSlotProps is not defined, so no internal event handlers are defined,
// so we can simply merge all the props without having to worry about extracting event handlers.
const joinedClasses = clsx(
additionalProps?.className,
className,
externalForwardedProps?.className,
externalSlotProps?.className,
);
const mergedStyle = {
...additionalProps?.style,
...externalForwardedProps?.style,
...externalSlotProps?.style,
};
const props = {
...additionalProps,
...externalForwardedProps,
...externalSlotProps,
} as MergeSlotPropsResult<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps
>['props'];
if (joinedClasses.length > 0) {
props.className = joinedClasses;
}
if (Object.keys(mergedStyle).length > 0) {
props.style = mergedStyle;
}
return {
props,
internalRef: undefined,
};
}
// In this case, getSlotProps is responsible for calling the external event handlers.
// We don't need to include them in the merged props because of this.
const eventHandlers = extractEventHandlers({ ...externalForwardedProps, ...externalSlotProps });
const componentsPropsWithoutEventHandlers = omitEventHandlers(externalSlotProps);
const otherPropsWithoutEventHandlers = omitEventHandlers(externalForwardedProps);
const internalSlotProps = getSlotProps(eventHandlers);
// The order of classes is important here.
// Emotion (that we use in libraries consuming Base UI) depends on this order
// to properly override style. It requires the most important classes to be last
// (see https://github.com/mui/material-ui/pull/33205) for the related discussion.
const joinedClasses = clsx(
internalSlotProps?.className,
additionalProps?.className,
className,
externalForwardedProps?.className,
externalSlotProps?.className,
);
const mergedStyle = {
...internalSlotProps?.style,
...additionalProps?.style,
...externalForwardedProps?.style,
...externalSlotProps?.style,
};
const props = {
...internalSlotProps,
...additionalProps,
...otherPropsWithoutEventHandlers,
...componentsPropsWithoutEventHandlers,
} as MergeSlotPropsResult<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps
>['props'];
if (joinedClasses.length > 0) {
props.className = joinedClasses;
}
if (Object.keys(mergedStyle).length > 0) {
props.style = mergedStyle;
}
return {
props,
internalRef: internalSlotProps.ref,
};
}
| 6,393
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/omitEventHandlers.test.ts
|
import { expect } from 'chai';
import { omitEventHandlers } from './omitEventHandlers';
describe('omitEventHandlers', () => {
it('should remove functions with names beginning with `on` followed by uppercase letter', () => {
const obj = {
onClick: () => {},
onKeyDown: () => {},
foo: 12,
bar: 'baz',
onion: {},
once: () => {},
on2: () => {},
on: () => {},
};
const result = omitEventHandlers(obj);
expect(result).to.haveOwnProperty('foo');
expect(result).to.haveOwnProperty('bar');
expect(result).to.haveOwnProperty('onion');
expect(result).to.haveOwnProperty('once');
expect(result).to.haveOwnProperty('on2');
expect(result).to.haveOwnProperty('on');
expect(result).to.not.haveOwnProperty('onClick');
expect(result).to.not.haveOwnProperty('onKeyDown');
});
});
| 6,394
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/omitEventHandlers.ts
|
/**
* Removes event handlers from the given object.
* A field is considered an event handler if it is a function with a name beginning with `on`.
*
* @param object Object to remove event handlers from.
* @returns Object with event handlers removed.
*/
export function omitEventHandlers<Props extends Record<string, unknown>>(
object: Props | undefined,
) {
if (object === undefined) {
return {};
}
const result = {} as Partial<Props>;
Object.keys(object)
.filter((prop) => !(prop.match(/^on[A-Z]/) && typeof object[prop] === 'function'))
.forEach((prop) => {
(result[prop] as any) = object[prop];
});
return result;
}
| 6,395
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/prepareForSlot.spec.tsx
|
import * as React from 'react';
import { prepareForSlot } from './prepareForSlot';
interface Props {
a: string;
b?: number;
}
const Component = React.forwardRef<HTMLDivElement, Props>(function Component(props, ref) {
const { a, b, ...other } = props;
return <div {...other} />;
});
const SlotComponent = prepareForSlot(Component);
function MissingRequiredProps() {
// @ts-expect-error missing required props
return <SlotComponent />;
}
function ThrowsOnInvalidProps() {
// @ts-expect-error throws on invalid prop
return <SlotComponent a={false} />;
}
function WorkAsExpected() {
return <SlotComponent a="a" b={2} />;
}
| 6,396
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/prepareForSlot.test.tsx
|
import * as React from 'react';
import { expect } from 'chai';
import { createRenderer } from '@mui-internal/test-utils';
import { Button } from '@mui/base/Button';
import { prepareForSlot } from './prepareForSlot';
describe('prepareForSlot', () => {
const { render } = createRenderer();
it('should not warn about ownerState', () => {
const ThirdPartyComponent = React.forwardRef<HTMLButtonElement>((props, ref) => {
// @ts-ignore just double checking that it is not defined
expect(props.ownerState).to.equal(undefined);
return <button {...props} ref={ref} />;
});
expect(() =>
render(<Button slots={{ root: prepareForSlot(ThirdPartyComponent) }} />),
).not.toErrorDev();
});
});
| 6,397
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/prepareForSlot.tsx
|
import * as React from 'react';
export function prepareForSlot<ComponentType extends React.ElementType>(Component: ComponentType) {
type Props = React.ComponentProps<ComponentType>;
return React.forwardRef<HTMLElement, Props>(function Slot(props, ref) {
const { ownerState, ...other } = props;
return React.createElement<Props>(Component, {
...(other as Props),
ref,
});
});
}
| 6,398
|
0
|
petrpan-code/mui/material-ui/packages/mui-base/src
|
petrpan-code/mui/material-ui/packages/mui-base/src/utils/resolveComponentProps.ts
|
/**
* If `componentProps` is a function, calls it with the provided `ownerState`.
* Otherwise, just returns `componentProps`.
*/
export function resolveComponentProps<TProps, TOwnerState, TSlotState>(
componentProps:
| TProps
| ((ownerState: TOwnerState, slotState?: TSlotState) => TProps)
| undefined,
ownerState: TOwnerState,
slotState?: TSlotState,
): TProps | undefined {
if (typeof componentProps === 'function') {
return (componentProps as (ownerState: TOwnerState, slotState?: TSlotState) => TProps)(
ownerState,
slotState,
);
}
return componentProps;
}
| 6,399
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.