pre-installations and preparations

This commit is contained in:
MuhammadKhalilzadeh committed 2024-05-05 11:21:00 +03:30
1 parent 3e5a0329cb
commit 201d621ac3
6977 files changed
+742826

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
import * as React from 'react';
export const ListContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== 'production') {
ListContext.displayName = 'ListContext';
}
+9
View File
@@ -0,0 +1,9 @@
'use client';
export { useList } from './useList';
export * from './useList.types';
export { useListItem } from './useListItem';
export * from './useListItem.types';
export * from './listReducer';
export * from './listActions.types';
export * from './ListContext';
+16
View File
@@ -0,0 +1,16 @@
export const ListActionTypes = {
blur: 'list:blur',
focus: 'list:focus',
itemClick: 'list:itemClick',
itemHover: 'list:itemHover',
itemsChange: 'list:itemsChange',
keyDown: 'list:keyDown',
resetHighlight: 'list:resetHighlight',
highlightLast: 'list:highlightLast',
textNavigation: 'list:textNavigation',
clearSelection: 'list:clearSelection'
};
/**
* A union of all standard actions that can be dispatched to the list reducer.
*/
+350
View File
@@ -0,0 +1,350 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import { ListActionTypes } from './listActions.types';
/**
* Looks up the next valid item to highlight within the list.
*
* @param currentIndex The index of the start of the search.
* @param lookupDirection Whether to look for the next or previous item.
* @param items The array of items to search.
* @param includeDisabledItems Whether to include disabled items in the search.
* @param isItemDisabled A function that determines whether an item is disabled.
* @param wrapAround Whether to wrap around the list when searching.
* @returns The index of the next valid item to highlight or -1 if no valid item is found.
*/
function findValidItemToHighlight(currentIndex, lookupDirection, items, includeDisabledItems, isItemDisabled, wrapAround) {
if (items.length === 0 || !includeDisabledItems && items.every((item, itemIndex) => isItemDisabled(item, itemIndex))) {
return -1;
}
let nextFocus = currentIndex;
for (;;) {
// No valid items found
if (!wrapAround && lookupDirection === 'next' && nextFocus === items.length || !wrapAround && lookupDirection === 'previous' && nextFocus === -1) {
return -1;
}
const nextFocusDisabled = includeDisabledItems ? false : isItemDisabled(items[nextFocus], nextFocus);
if (nextFocusDisabled) {
nextFocus += lookupDirection === 'next' ? 1 : -1;
if (wrapAround) {
nextFocus = (nextFocus + items.length) % items.length;
}
} else {
return nextFocus;
}
}
}
/**
* Gets the next item to highlight based on the current highlighted item and the search direction.
*
* @param previouslyHighlightedValue The item from which to start the search for the next candidate.
* @param offset The offset from the previously highlighted item to search for the next candidate or a special named value ('reset', 'start', 'end').
* @param context The list action context.
*
* @returns The next item to highlight or null if no item is valid.
*/
export function moveHighlight(previouslyHighlightedValue, offset, context) {
const {
items,
isItemDisabled,
disableListWrap,
disabledItemsFocusable,
itemComparer,
focusManagement
} = context;
// TODO: make this configurable
// The always should be an item highlighted when focus is managed by the DOM
// so that it's accessible by the `tab` key.
const defaultHighlightedIndex = focusManagement === 'DOM' ? 0 : -1;
const maxIndex = items.length - 1;
const previouslyHighlightedIndex = previouslyHighlightedValue == null ? -1 : items.findIndex(item => itemComparer(item, previouslyHighlightedValue));
let nextIndexCandidate;
let lookupDirection;
let wrapAround = !disableListWrap;
switch (offset) {
case 'reset':
if (defaultHighlightedIndex === -1) {
return null;
}
nextIndexCandidate = 0;
lookupDirection = 'next';
wrapAround = false;
break;
case 'start':
nextIndexCandidate = 0;
lookupDirection = 'next';
wrapAround = false;
break;
case 'end':
nextIndexCandidate = maxIndex;
lookupDirection = 'previous';
wrapAround = false;
break;
default:
{
const newIndex = previouslyHighlightedIndex + offset;
if (newIndex < 0) {
if (!wrapAround && previouslyHighlightedIndex !== -1 || Math.abs(offset) > 1) {
nextIndexCandidate = 0;
lookupDirection = 'next';
} else {
nextIndexCandidate = maxIndex;
lookupDirection = 'previous';
}
} else if (newIndex > maxIndex) {
if (!wrapAround || Math.abs(offset) > 1) {
nextIndexCandidate = maxIndex;
lookupDirection = 'previous';
} else {
nextIndexCandidate = 0;
lookupDirection = 'next';
}
} else {
nextIndexCandidate = newIndex;
lookupDirection = offset >= 0 ? 'next' : 'previous';
}
}
}
const nextIndex = findValidItemToHighlight(nextIndexCandidate, lookupDirection, items, disabledItemsFocusable, isItemDisabled, wrapAround);
// If there are no valid items to highlight, return the previously highlighted item (if it's still valid).
if (nextIndex === -1 && previouslyHighlightedValue !== null && !isItemDisabled(previouslyHighlightedValue, previouslyHighlightedIndex)) {
return previouslyHighlightedValue;
}
return items[nextIndex] ?? null;
}
/**
* Toggles the selection of an item.
*
* @param item Item to toggle.
* @param selectedValues Already selected items.
* @param selectionMode The number of items that can be simultanously selected.
* @param itemComparer A custom item comparer function.
*
* @returns The new array of selected items.
*/
export function toggleSelection(item, selectedValues, selectionMode, itemComparer) {
if (selectionMode === 'none') {
return [];
}
if (selectionMode === 'single') {
// if the item to select has already been selected, return the original array
if (itemComparer(selectedValues[0], item)) {
return selectedValues;
}
return [item];
}
// The toggled item is selected; remove it from the selection.
if (selectedValues.some(sv => itemComparer(sv, item))) {
return selectedValues.filter(sv => !itemComparer(sv, item));
}
// The toggled item is not selected - add it to the selection.
return [...selectedValues, item];
}
/**
* Handles item selection in a list.
*
* @param item - The item to be selected.
* @param state - The current state of the list.
* @param context - The context of the list action.
* @returns The new state of the list after the item has been selected, or the original state if the item is disabled.
*/
export function handleItemSelection(item, state, context) {
const {
itemComparer,
isItemDisabled,
selectionMode,
items
} = context;
const {
selectedValues
} = state;
const itemIndex = items.findIndex(i => itemComparer(item, i));
if (isItemDisabled(item, itemIndex)) {
return state;
}
// if the item is already selected, remove it from the selection, otherwise add it
const newSelectedValues = toggleSelection(item, selectedValues, selectionMode, itemComparer);
return _extends({}, state, {
selectedValues: newSelectedValues,
highlightedValue: item
});
}
function handleKeyDown(key, state, context) {
const previouslySelectedValue = state.highlightedValue;
const {
orientation,
pageSize
} = context;
switch (key) {
case 'Home':
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, 'start', context)
});
case 'End':
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, 'end', context)
});
case 'PageUp':
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, -pageSize, context)
});
case 'PageDown':
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, pageSize, context)
});
case 'ArrowUp':
if (orientation !== 'vertical') {
break;
}
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, -1, context)
});
case 'ArrowDown':
if (orientation !== 'vertical') {
break;
}
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, 1, context)
});
case 'ArrowLeft':
{
if (orientation === 'vertical') {
break;
}
const offset = orientation === 'horizontal-ltr' ? -1 : 1;
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, offset, context)
});
}
case 'ArrowRight':
{
if (orientation === 'vertical') {
break;
}
const offset = orientation === 'horizontal-ltr' ? 1 : -1;
return _extends({}, state, {
highlightedValue: moveHighlight(previouslySelectedValue, offset, context)
});
}
case 'Enter':
case ' ':
if (state.highlightedValue === null) {
return state;
}
return handleItemSelection(state.highlightedValue, state, context);
default:
break;
}
return state;
}
function handleBlur(state, context) {
if (context.focusManagement === 'DOM') {
return state;
}
return _extends({}, state, {
highlightedValue: null
});
}
function textCriteriaMatches(nextFocus, searchString, stringifyItem) {
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(state, searchString, context) {
const {
items,
isItemDisabled,
disabledItemsFocusable,
getItemAsString
} = context;
const startWithCurrentItem = searchString.length > 1;
let nextItem = startWithCurrentItem ? state.highlightedValue : moveHighlight(state.highlightedValue, 1, context);
for (let index = 0; index < items.length; index += 1) {
// Return un-mutated state if looped back to the currently highlighted value
if (!nextItem || !startWithCurrentItem && state.highlightedValue === nextItem) {
return state;
}
if (textCriteriaMatches(nextItem, searchString, getItemAsString) && (!isItemDisabled(nextItem, items.indexOf(nextItem)) || disabledItemsFocusable)) {
// The nextItem is the element to be highlighted
return _extends({}, state, {
highlightedValue: nextItem
});
}
// Move to the next element.
nextItem = moveHighlight(nextItem, 1, context);
}
// No item matches the text search criteria
return state;
}
function handleItemsChange(items, previousItems, state, context) {
const {
itemComparer,
focusManagement
} = context;
let newHighlightedValue = 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 _extends({}, state, {
highlightedValue: newHighlightedValue,
selectedValues: newSelectedValues
});
}
function handleResetHighlight(state, context) {
return _extends({}, state, {
highlightedValue: moveHighlight(null, 'reset', context)
});
}
function handleHighlightLast(state, context) {
return _extends({}, state, {
highlightedValue: moveHighlight(null, 'end', context)
});
}
function handleClearSelection(state, context) {
return _extends({}, state, {
selectedValues: [],
highlightedValue: moveHighlight(null, 'reset', context)
});
}
export function listReducer(state, action) {
const {
type,
context
} = action;
switch (type) {
case ListActionTypes.keyDown:
return handleKeyDown(action.key, state, context);
case ListActionTypes.itemClick:
return handleItemSelection(action.item, state, context);
case ListActionTypes.blur:
return handleBlur(state, context);
case ListActionTypes.textNavigation:
return handleTextNavigation(state, action.searchString, context);
case ListActionTypes.itemsChange:
return handleItemsChange(action.items, action.previousItems, state, context);
case ListActionTypes.resetHighlight:
return handleResetHighlight(state, context);
case ListActionTypes.highlightLast:
return handleHighlightLast(state, context);
case ListActionTypes.clearSelection:
return handleClearSelection(state, context);
default:
return state;
}
}
+235
View File
@@ -0,0 +1,235 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import { ListActionTypes } from './listActions.types';
import { listReducer as defaultReducer } from './listReducer';
import { useControllableReducer } from '../utils/useControllableReducer';
import { areArraysEqual } from '../utils/areArraysEqual';
import { useTextNavigation } from '../utils/useTextNavigation';
import { extractEventHandlers } from '../utils/extractEventHandlers';
const EMPTY_OBJECT = {};
const NOOP = () => {};
const defaultItemComparer = (optionA, optionB) => optionA === optionB;
const defaultIsItemDisabled = () => false;
const defaultItemStringifier = item => typeof item === 'string' ? item : String(item);
const defaultGetInitialState = () => ({
highlightedValue: null,
selectedValues: []
});
/**
* The useList is a lower-level utility that is used to build list-like components.
* It's used to manage the state of the list and its items.
*
* Supports highlighting a single item and selecting an arbitrary number of items.
*
* The state of the list is managed by a controllable reducer - that is a reducer that can have its state
* controlled from outside.
*
* By default, the state consists of `selectedValues` and `highlightedValue` but can be extended by the caller of the hook.
* Also the actions that can be dispatched and the reducer function can be defined externally.
*
* @template ItemValue The type of the item values.
* @template State The type of the list state. This should be a subtype of `ListState<ItemValue>`.
* @template CustomAction The type of the actions that can be dispatched (besides the standard ListAction).
* @template CustomActionContext The shape of additional properties that will be added to actions when dispatched.
*
* @ignore - internal hook.
*/
function useList(params) {
const {
controlledProps = EMPTY_OBJECT,
disabledItemsFocusable = false,
disableListWrap = false,
focusManagement = 'activeDescendant',
getInitialState = defaultGetInitialState,
getItemDomElement,
getItemId,
isItemDisabled = defaultIsItemDisabled,
rootRef: externalListRef,
onStateChange = NOOP,
items,
itemComparer = defaultItemComparer,
getItemAsString = defaultItemStringifier,
onChange,
onHighlightChange,
onItemsChange,
orientation = 'vertical',
pageSize = 5,
reducerActionContext = EMPTY_OBJECT,
selectionMode = 'single',
stateReducer: externalReducer,
componentName = 'useList'
} = params;
if (process.env.NODE_ENV !== 'production') {
if (focusManagement === 'DOM' && getItemDomElement == null) {
throw new Error('useList: The `getItemDomElement` prop is required when using the `DOM` focus management.');
}
if (focusManagement === 'activeDescendant' && getItemId == null) {
throw new Error('useList: The `getItemId` prop is required when using the `activeDescendant` focus management.');
}
}
const listRef = React.useRef(null);
const handleRef = useForkRef(externalListRef, listRef);
const handleHighlightChange = React.useCallback((event, value, reason) => {
onHighlightChange?.(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)
}), [itemComparer]);
// This gets called whenever a reducer changes the state.
const handleStateChange = React.useCallback((event, field, value, reason, state) => {
onStateChange?.(event, field, value, reason, state);
switch (field) {
case 'highlightedValue':
handleHighlightChange(event, value, reason);
break;
case 'selectedValues':
onChange?.(event, value, reason);
break;
default:
break;
}
}, [handleHighlightChange, onChange, onStateChange]);
// The following object is added to each action when it's dispatched.
// It's accessible in the reducer via the `action.context` field.
const listActionContext = React.useMemo(() => {
return {
disabledItemsFocusable,
disableListWrap,
focusManagement,
isItemDisabled,
itemComparer,
items,
getItemAsString,
onHighlightChange: handleHighlightChange,
orientation,
pageSize,
selectionMode,
stateComparers
};
}, [disabledItemsFocusable, disableListWrap, focusManagement, isItemDisabled, itemComparer, items, getItemAsString, handleHighlightChange, orientation, pageSize, selectionMode, stateComparers]);
const initialState = getInitialState();
const reducer = externalReducer ?? defaultReducer;
const actionContext = React.useMemo(() => _extends({}, reducerActionContext, listActionContext), [reducerActionContext, listActionContext]);
const [state, dispatch] = useControllableReducer({
reducer,
actionContext,
initialState: initialState,
controlledProps,
stateComparers,
onStateChange: handleStateChange,
componentName
});
const {
highlightedValue,
selectedValues
} = state;
const handleTextNavigation = useTextNavigation((searchString, event) => dispatch({
type: ListActionTypes.textNavigation,
event,
searchString
}));
const previousItems = React.useRef([]);
React.useEffect(() => {
// Whenever the `items` object changes, we need to determine if the actual items changed.
// If they did, we need to dispatch an `itemsChange` action, so the selected/highlighted state is updated.
if (areArraysEqual(previousItems.current, items, itemComparer)) {
return;
}
dispatch({
type: ListActionTypes.itemsChange,
event: null,
items,
previousItems: previousItems.current
});
previousItems.current = items;
onItemsChange?.(items);
}, [items, itemComparer, dispatch, onItemsChange]);
const createHandleKeyDown = externalHandlers => event => {
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 => event => {
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 = {}) => {
const externalEventHandlers = extractEventHandlers(externalProps);
return _extends({}, externalProps, {
'aria-activedescendant': focusManagement === 'activeDescendant' && highlightedValue != null ? getItemId(highlightedValue) : undefined,
tabIndex: focusManagement === 'DOM' ? -1 : 0,
ref: handleRef
}, externalEventHandlers, {
onBlur: createHandleBlur(externalEventHandlers),
onKeyDown: createHandleKeyDown(externalEventHandlers)
});
};
const getItemState = React.useCallback(item => {
const selected = (selectedValues ?? []).some(value => value != null && itemComparer(item, value));
const highlighted = highlightedValue != null && itemComparer(item, highlightedValue);
const focusable = focusManagement === 'DOM';
return {
focusable,
highlighted,
selected
};
}, [itemComparer, selectedValues, highlightedValue, focusManagement]);
const contextValue = React.useMemo(() => ({
dispatch,
getItemState
}), [dispatch, getItemState]);
React.useDebugValue({
state
});
return {
contextValue,
dispatch,
getRootProps,
rootRef: handleRef,
state
};
}
export { useList };
+1
View File
@@ -0,0 +1 @@
export {};
+83
View File
@@ -0,0 +1,83 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { ListActionTypes } from './listActions.types';
import { ListContext } from './ListContext';
/**
* Contains the logic for an item of a list-like component (for example Select, Menu, etc.).
* It handles the item's mouse events and tab index.
*
* @template ItemValue The type of the item's value. This should be consistent with the type of useList's `items` parameter.
* @ignore - internal hook.
*/
export function useListItem(parameters) {
const {
handlePointerOverEvents = false,
item
} = parameters;
const listContext = React.useContext(ListContext);
if (!listContext) {
throw new Error('useListItem must be used within a ListProvider');
}
const {
dispatch,
getItemState
} = listContext;
const {
highlighted,
selected,
focusable
} = getItemState(item);
const createHandleClick = React.useCallback(externalHandlers => event => {
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 => event => {
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;
if (focusable) {
tabIndex = highlighted ? 0 : -1;
}
const getRootProps = (externalProps = {}) => {
const externalEventHandlers = extractEventHandlers(externalProps);
return _extends({}, externalProps, {
onClick: createHandleClick(externalEventHandlers),
onPointerOver: handlePointerOverEvents ? createHandlePointerOver(externalEventHandlers) : undefined,
tabIndex
});
};
return {
getRootProps,
highlighted,
selected
};
}
+1
View File
@@ -0,0 +1 @@
export {};