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

+24
View File
@@ -0,0 +1,24 @@
import * as React from 'react';
type ClassNameConfiguration = {
/**
* If `true`, the components within the context will not have built-in classes applied.
*/
disableDefaultClasses: boolean;
};
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 declare function useClassNamesOverride(generateUtilityClass: (slot: string) => string): (slot: string) => string;
/**
* Allows to configure the components within to not apply any built-in classes.
*/
export declare function ClassNameConfigurator(props: ClassNameConfiguratorProps): React.JSX.Element;
export {};
+47
View File
@@ -0,0 +1,47 @@
'use client';
import * as React from 'react';
import { jsx as _jsx } from "react/jsx-runtime";
const defaultContextValue = {
disableDefaultClasses: false
};
const ClassNameConfiguratorContext = /*#__PURE__*/React.createContext(defaultContextValue);
if (process.env.NODE_ENV !== 'production') {
ClassNameConfiguratorContext.displayName = 'ClassNameConfiguratorContext';
}
/**
* @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) {
const {
disableDefaultClasses
} = React.useContext(ClassNameConfiguratorContext);
return slot => {
if (disableDefaultClasses) {
return '';
}
return generateUtilityClass(slot);
};
}
/**
* Allows to configure the components within to not apply any built-in classes.
*/
export function ClassNameConfigurator(props) {
const {
disableDefaultClasses,
children
} = props;
const contextValue = React.useMemo(() => ({
disableDefaultClasses: disableDefaultClasses != null ? disableDefaultClasses : false
}), [disableDefaultClasses]);
return /*#__PURE__*/_jsx(ClassNameConfiguratorContext.Provider, {
value: contextValue,
children: children
});
}
+4
View File
@@ -0,0 +1,4 @@
export type MuiCancellableEvent = {
defaultMuiPrevented?: boolean;
};
export type MuiCancellableEventHandler<Event> = (event: Event & MuiCancellableEvent) => void;
+1
View File
@@ -0,0 +1 @@
export {};
+17
View File
@@ -0,0 +1,17 @@
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']>;
+1
View File
@@ -0,0 +1 @@
export {};
+20
View File
@@ -0,0 +1,20 @@
import * as React from 'react';
import { Simplify } from '@mui/types';
/**
* 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 declare function appendOwnerState<ElementType extends React.ElementType, OtherProps extends Record<string, any>, OwnerState>(elementType: ElementType | undefined, otherProps: OtherProps, ownerState: OwnerState): AppendOwnerStateReturnType<ElementType, OtherProps, OwnerState>;
export {};
+24
View File
@@ -0,0 +1,24 @@
import _extends from "@babel/runtime/helpers/esm/extends";
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.
*/
/**
* 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, otherProps, ownerState) {
if (elementType === undefined || isHostComponent(elementType)) {
return otherProps;
}
return _extends({}, otherProps, {
ownerState: _extends({}, otherProps.ownerState, ownerState)
});
}
+3
View File
@@ -0,0 +1,3 @@
type ItemComparer<Item> = (a: Item, b: Item) => boolean;
export declare function areArraysEqual<Item>(array1: ReadonlyArray<Item>, array2: ReadonlyArray<Item>, itemComparer?: ItemComparer<Item>): boolean;
export {};
+3
View File
@@ -0,0 +1,3 @@
export function areArraysEqual(array1, array2, itemComparer = (a, b) => a === b) {
return array1.length === array2.length && array1.every((value, index) => itemComparer(value, array2[index]));
}
+16
View File
@@ -0,0 +1,16 @@
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 declare function combineHooksSlotProps<ExternalHandlers extends EventHandlers, FirstSlotProps extends ExternalHandlers, SecondSlotProps extends ExternalHandlers>(getFirstProps: (external?: ExternalHandlers) => FirstSlotProps, getSecondProps: (external?: ExternalHandlers) => SecondSlotProps): <OtherProps extends ExternalHandlers>(external?: OtherProps) => OtherProps & FirstSlotProps & SecondSlotProps;
+22
View File
@@ -0,0 +1,22 @@
import _extends from "@babel/runtime/helpers/esm/extends";
/**
* 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(getFirstProps, getSecondProps) {
return function getCombinedProps(external = {}) {
const firstResult = _extends({}, external, getFirstProps(external));
const result = _extends({}, firstResult, getSecondProps(firstResult));
return result;
};
}
+9
View File
@@ -0,0 +1,9 @@
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 declare function extractEventHandlers(object: Record<string, any> | undefined, excludeKeys?: string[]): EventHandlers;
+17
View File
@@ -0,0 +1,17 @@
/**
* 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, excludeKeys = []) {
if (object === undefined) {
return {};
}
const result = {};
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;
}
+12
View File
@@ -0,0 +1,12 @@
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 { useRootElementName } from './useRootElementName';
export { useSlotProps } from './useSlotProps';
export { mergeSlotProps } from './mergeSlotProps';
export { prepareForSlot } from './prepareForSlot';
export * from './PolymorphicComponent';
export * from './types';
+14
View File
@@ -0,0 +1,14 @@
'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 { useRootElementName } from './useRootElementName';
export { useSlotProps } from './useSlotProps';
export { mergeSlotProps } from './mergeSlotProps';
export { prepareForSlot } from './prepareForSlot';
export * from './PolymorphicComponent';
export * from './types';
+5
View File
@@ -0,0 +1,5 @@
import * as React from 'react';
/**
* Determines if a given element is a DOM element name (i.e. not a React component).
*/
export declare function isHostComponent(element: React.ElementType): boolean;
+6
View File
@@ -0,0 +1,6 @@
/**
* Determines if a given element is a DOM element name (i.e. not a React component).
*/
export function isHostComponent(element) {
return typeof element === 'string';
}
+55
View File
@@ -0,0 +1,55 @@
import * as React from 'react';
import { ClassValue } from 'clsx';
import { Simplify } from '@mui/types';
import { EventHandlers } from './types';
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 declare 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>;
+69
View File
@@ -0,0 +1,69 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import clsx from 'clsx';
import { extractEventHandlers } from './extractEventHandlers';
import { omitEventHandlers } from './omitEventHandlers';
/**
* 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(parameters) {
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 == null ? void 0 : additionalProps.className, className, externalForwardedProps == null ? void 0 : externalForwardedProps.className, externalSlotProps == null ? void 0 : externalSlotProps.className);
const mergedStyle = _extends({}, additionalProps == null ? void 0 : additionalProps.style, externalForwardedProps == null ? void 0 : externalForwardedProps.style, externalSlotProps == null ? void 0 : externalSlotProps.style);
const props = _extends({}, additionalProps, externalForwardedProps, externalSlotProps);
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(_extends({}, 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 == null ? void 0 : internalSlotProps.className, additionalProps == null ? void 0 : additionalProps.className, className, externalForwardedProps == null ? void 0 : externalForwardedProps.className, externalSlotProps == null ? void 0 : externalSlotProps.className);
const mergedStyle = _extends({}, internalSlotProps == null ? void 0 : internalSlotProps.style, additionalProps == null ? void 0 : additionalProps.style, externalForwardedProps == null ? void 0 : externalForwardedProps.style, externalSlotProps == null ? void 0 : externalSlotProps.style);
const props = _extends({}, internalSlotProps, additionalProps, otherPropsWithoutEventHandlers, componentsPropsWithoutEventHandlers);
if (joinedClasses.length > 0) {
props.className = joinedClasses;
}
if (Object.keys(mergedStyle).length > 0) {
props.style = mergedStyle;
}
return {
props,
internalRef: internalSlotProps.ref
};
}
+8
View File
@@ -0,0 +1,8 @@
/**
* 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 declare function omitEventHandlers<Props extends Record<string, unknown>>(object: Props | undefined): {};
+17
View File
@@ -0,0 +1,17 @@
/**
* 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(object) {
if (object === undefined) {
return {};
}
const result = {};
Object.keys(object).filter(prop => !(prop.match(/^on[A-Z]/) && typeof object[prop] === 'function')).forEach(prop => {
result[prop] = object[prop];
});
return result;
}
+6
View File
@@ -0,0 +1,6 @@
{
"sideEffects": false,
"module": "./index.js",
"main": "../node/utils/index.js",
"types": "./index.d.ts"
}
+2
View File
@@ -0,0 +1,2 @@
import * as React from 'react';
export declare function prepareForSlot<ComponentType extends React.ElementType>(Component: ComponentType): React.ForwardRefExoticComponent<React.PropsWithoutRef<React.ComponentProps<ComponentType>> & React.RefAttributes<HTMLElement>>;
+12
View File
@@ -0,0 +1,12 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["ownerState"];
import * as React from 'react';
export function prepareForSlot(Component) {
return /*#__PURE__*/React.forwardRef(function Slot(props, ref) {
const other = _objectWithoutPropertiesLoose(props, _excluded);
return /*#__PURE__*/React.createElement(Component, _extends({}, other, {
ref
}));
});
}
+5
View File
@@ -0,0 +1,5 @@
/**
* If `componentProps` is a function, calls it with the provided `ownerState`.
* Otherwise, just returns `componentProps`.
*/
export declare function resolveComponentProps<TProps, TOwnerState, TSlotState>(componentProps: TProps | ((ownerState: TOwnerState, slotState?: TSlotState) => TProps) | undefined, ownerState: TOwnerState, slotState?: TSlotState): TProps | undefined;
+10
View File
@@ -0,0 +1,10 @@
/**
* If `componentProps` is a function, calls it with the provided `ownerState`.
* Otherwise, just returns `componentProps`.
*/
export function resolveComponentProps(componentProps, ownerState, slotState) {
if (typeof componentProps === 'function') {
return componentProps(ownerState, slotState);
}
return componentProps;
}
+7
View File
@@ -0,0 +1,7 @@
import * as React from 'react';
export type EventHandlers = Record<string, React.EventHandler<any>>;
export type WithOptionalOwnerState<Props extends {
ownerState: unknown;
}> = Omit<Props, 'ownerState'> & Partial<Pick<Props, 'ownerState'>>;
export type SlotComponentProps<TSlotComponent extends React.ElementType, TOverrides, TOwnerState> = (Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides) | ((ownerState: TOwnerState) => Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides);
export type SlotComponentPropsWithSlotState<TSlotComponent extends React.ElementType, TOverrides, TOwnerState, TSlotState> = (Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides) | ((ownerState: TOwnerState, slotState: TSlotState) => Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides);
+1
View File
@@ -0,0 +1 @@
export {};
+26
View File
@@ -0,0 +1,26 @@
import { ControllableReducerAction, ControllableReducerParameters } from './useControllableReducer.types';
/**
* The alternative to `React.useReducer` that lets you control the state from the outside.
*
* It can be used in an uncontrolled mode, similar to `React.useReducer`, or in a controlled mode, when the state is controlled by the props.
* It also supports partially controlled state, when some state items are controlled and some are not.
*
* The controlled state items are provided via the `controlledProps` parameter.
* When a reducer action is dispatched, the internal state is updated with the new values.
* A change event (`onStateChange`) is then triggered (for each changed state item) if the new state is different from the previous state.
* This event can be used to update the controlled values.
*
* The comparison of the previous and next states is done using the `stateComparers` parameter.
* If a state item has a corresponding comparer, it will be used to determine if the state has changed.
* This is useful when the state item is an object and you want to compare only a subset of its properties or if it's an array and you want to compare its contents.
*
* An additional feature is the `actionContext` parameter. It allows you to add additional properties to every action object,
* similarly to how React context is implicitly available to every component.
*
* @template State - The type of the state calculated by the reducer.
* @template Action - The type of the actions that can be dispatched.
* @template ActionContext - The type of the additional properties that will be added to every action object.
*
* @ignore - internal hook.
*/
export declare function useControllableReducer<State extends {}, Action extends ControllableReducerAction, ActionContext = undefined>(parameters: ControllableReducerParameters<State, Action, ActionContext>): [State, (action: Action) => void];
+135
View File
@@ -0,0 +1,135 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
function areEqual(a, b) {
return a === b;
}
const EMPTY_OBJECT = {};
const NOOP = () => {};
/**
* Gets the current state augmented with controlled values from the outside.
* If a state item has a corresponding controlled value, it will be used instead of the internal state.
*/
function getControlledState(internalState, controlledProps) {
const augmentedState = _extends({}, internalState);
Object.keys(controlledProps).forEach(key => {
if (controlledProps[key] !== undefined) {
augmentedState[key] = controlledProps[key];
}
});
return augmentedState;
}
/**
* Defines an effect that compares the next state with the previous state and calls
* the `onStateChange` callback if the state has changed.
* The comparison is done based on the `stateComparers` parameter.
*/
function useStateChangeDetection(parameters) {
const {
nextState,
initialState,
stateComparers,
onStateChange,
controlledProps,
lastActionRef
} = parameters;
const internalPreviousStateRef = React.useRef(initialState);
React.useEffect(() => {
if (lastActionRef.current === null) {
// Detect changes only if an action has been dispatched.
return;
}
const previousState = getControlledState(internalPreviousStateRef.current, controlledProps);
Object.keys(nextState).forEach(key => {
var _stateComparers$key;
// go through all state keys and compare them with the previous state
const stateComparer = (_stateComparers$key = stateComparers[key]) != null ? _stateComparers$key : areEqual;
const nextStateItem = nextState[key];
const previousStateItem = previousState[key];
if (previousStateItem == null && nextStateItem != null || previousStateItem != null && nextStateItem == null || previousStateItem != null && nextStateItem != null && !stateComparer(nextStateItem, previousStateItem)) {
var _event, _type;
onStateChange == null || onStateChange((_event = lastActionRef.current.event) != null ? _event : null, key, nextStateItem, (_type = lastActionRef.current.type) != null ? _type : '', nextState);
}
});
internalPreviousStateRef.current = nextState;
lastActionRef.current = null;
}, [internalPreviousStateRef, nextState, lastActionRef, onStateChange, stateComparers, controlledProps]);
}
/**
* The alternative to `React.useReducer` that lets you control the state from the outside.
*
* It can be used in an uncontrolled mode, similar to `React.useReducer`, or in a controlled mode, when the state is controlled by the props.
* It also supports partially controlled state, when some state items are controlled and some are not.
*
* The controlled state items are provided via the `controlledProps` parameter.
* When a reducer action is dispatched, the internal state is updated with the new values.
* A change event (`onStateChange`) is then triggered (for each changed state item) if the new state is different from the previous state.
* This event can be used to update the controlled values.
*
* The comparison of the previous and next states is done using the `stateComparers` parameter.
* If a state item has a corresponding comparer, it will be used to determine if the state has changed.
* This is useful when the state item is an object and you want to compare only a subset of its properties or if it's an array and you want to compare its contents.
*
* An additional feature is the `actionContext` parameter. It allows you to add additional properties to every action object,
* similarly to how React context is implicitly available to every component.
*
* @template State - The type of the state calculated by the reducer.
* @template Action - The type of the actions that can be dispatched.
* @template ActionContext - The type of the additional properties that will be added to every action object.
*
* @ignore - internal hook.
*/
export function useControllableReducer(parameters) {
const lastActionRef = React.useRef(null);
const {
reducer,
initialState,
controlledProps = EMPTY_OBJECT,
stateComparers = EMPTY_OBJECT,
onStateChange = NOOP,
actionContext,
componentName = ''
} = parameters;
const controlledPropsRef = React.useRef(controlledProps);
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
Object.keys(controlledProps).forEach(key => {
if (controlledPropsRef.current[key] !== undefined && controlledProps[key] === undefined) {
console.error(`useControllableReducer: ${componentName ? `The ${componentName} component` : 'A component'} is changing a controlled prop to be uncontrolled: ${key}`);
}
if (controlledPropsRef.current[key] === undefined && controlledProps[key] !== undefined) {
console.error(`useControllableReducer: ${componentName ? `The ${componentName} component` : 'A component'} is changing an uncontrolled prop to be controlled: ${key}`);
}
});
}, [controlledProps, componentName]);
}
// The reducer that is passed to React.useReducer is wrapped with a function that augments the state with controlled values.
const reducerWithControlledState = React.useCallback((state, action) => {
lastActionRef.current = action;
const controlledState = getControlledState(state, controlledProps);
const newState = reducer(controlledState, action);
return newState;
}, [controlledProps, reducer]);
const [nextState, dispatch] = React.useReducer(reducerWithControlledState, initialState);
// The action that is passed to dispatch is augmented with the actionContext.
const dispatchWithContext = React.useCallback(action => {
dispatch(_extends({}, action, {
context: actionContext
}));
}, [actionContext]);
useStateChangeDetection({
nextState,
initialState,
stateComparers: stateComparers != null ? stateComparers : EMPTY_OBJECT,
onStateChange: onStateChange != null ? onStateChange : NOOP,
controlledProps,
lastActionRef
});
return [getControlledState(nextState, controlledProps), dispatchWithContext];
}
+61
View File
@@ -0,0 +1,61 @@
/// <reference types="react" />
/**
* Functions that compare fields of a given State object
*/
export type StateComparers<State> = {
[key in keyof State]?: (value1: State[key], value2: State[key]) => boolean;
};
export type StateChangeCallback<State> = <StateKey extends keyof State>(event: React.SyntheticEvent | null, field: StateKey, value: State[StateKey], reason: string, state: State) => void;
export type ActionWithContext<Action, ContextValue> = Action & {
context: ContextValue;
};
/**
* Parameters of the useControllableReducer hook.
*/
export interface ControllableReducerParameters<State, Action extends ControllableReducerAction, ActionContext = undefined> {
/**
* The reducer function.
*
* @param state The previous state. If controlledProps are defined, the state will contain the values of the controlledProps.
* @param action The action to dispatch. The action can be augmented with the `actionContext`.
* @returns The updated state.
*/
reducer: (state: State, action: ActionWithContext<Action, ActionContext>) => State;
/**
* The controlled props that will override the state items.
*/
controlledProps?: Partial<State>;
/**
* The initial state.
*/
initialState: State;
/**
* Comparers for each state item. If a state item has a corresponding comparer, it will be used to determine if the state has changed.
* This is taken into consideration when firing the `onStateChange` event.
* If no comparer is defined, the default equality comparison will be used.
*/
stateComparers?: StateComparers<State>;
/**
* The event handler called whenever a field of the state changes.
*/
onStateChange?: StateChangeCallback<State>;
/**
* Additional properties that will be added to the action.
*/
actionContext?: ActionContext;
/**
* The name of the component using useControllableReducer.
* For debugging purposes.
*/
componentName?: string;
}
export type ControllableReducerAction = {
/**
* The type of the action.
*/
type?: string;
/**
* The event that triggered the action.
*/
event?: React.SyntheticEvent | null;
};
+1
View File
@@ -0,0 +1 @@
export {};
+4
View File
@@ -0,0 +1,4 @@
/**
* @ignore - internal hook.
*/
export declare function useForcedRerendering(): () => void;
+12
View File
@@ -0,0 +1,12 @@
'use client';
import * as React from 'react';
/**
* @ignore - internal hook.
*/
export function useForcedRerendering() {
const [, setState] = React.useState({});
return React.useCallback(() => {
setState({});
}, []);
}
+9
View File
@@ -0,0 +1,9 @@
export interface MessageBus {
subscribe(topic: string, callback: Function): () => void;
publish(topic: string, ...args: unknown[]): void;
}
export declare function createMessageBus(): MessageBus;
/**
* @ignore - internal hook.
*/
export declare function useMessageBus(): MessageBus;
+42
View File
@@ -0,0 +1,42 @@
'use client';
import * as React from 'react';
export function createMessageBus() {
const listeners = new Map();
function subscribe(topic, callback) {
let topicListeners = listeners.get(topic);
if (!topicListeners) {
topicListeners = new Set([callback]);
listeners.set(topic, topicListeners);
} else {
topicListeners.add(callback);
}
return () => {
topicListeners.delete(callback);
if (topicListeners.size === 0) {
listeners.delete(topic);
}
};
}
function publish(topic, ...args) {
const topicListeners = listeners.get(topic);
if (topicListeners) {
topicListeners.forEach(callback => callback(...args));
}
}
return {
subscribe,
publish
};
}
/**
* @ignore - internal hook.
*/
export function useMessageBus() {
const bus = React.useRef();
if (!bus.current) {
bus.current = createMessageBus();
}
return bus.current;
}
+19
View File
@@ -0,0 +1,19 @@
type UseRootElementNameParameters = {
/**
* The HTML element expected to be rendered, for example 'div', 'button' etc
* @default ''
*/
rootElementName?: keyof HTMLElementTagNameMap;
/**
* The name of the component using useRootElementName.
* For debugging purposes.
*/
componentName?: string;
};
/**
* @ignore - do not document.
*
* Use this function determine the host element correctly on the server (in a SSR context, for example Next.js)
*/
export declare function useRootElementName(parameters: UseRootElementNameParameters): [string, (instance: HTMLElement | null) => void];
export {};
+28
View File
@@ -0,0 +1,28 @@
'use client';
import * as React from 'react';
/**
* @ignore - do not document.
*
* Use this function determine the host element correctly on the server (in a SSR context, for example Next.js)
*/
export function useRootElementName(parameters) {
const {
rootElementName: rootElementNameProp = '',
componentName
} = parameters;
const [rootElementName, setRootElementName] = React.useState(rootElementNameProp.toUpperCase());
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (rootElementNameProp && rootElementName !== rootElementNameProp.toUpperCase()) {
console.error(`useRootElementName: the \`rootElementName\` prop of ${componentName ? `the ${componentName} component` : 'a component'} expected the '${rootElementNameProp}' element, but a '${rootElementName.toLowerCase()}' was rendered instead`, 'This may cause hydration issues in an SSR context, for example in a Next.js app');
}
}, [rootElementNameProp, rootElementName, componentName]);
}
const updateRootElementName = React.useCallback(instance => {
var _instance$tagName;
setRootElementName((_instance$tagName = instance == null ? void 0 : instance.tagName) != null ? _instance$tagName : '');
}, []);
return [rootElementName, updateRootElementName];
}
+40
View File
@@ -0,0 +1,40 @@
import * as React from 'react';
import { AppendOwnerStateReturnType } from './appendOwnerState';
import { MergeSlotPropsParameters, MergeSlotPropsResult, WithCommonProps } from './mergeSlotProps';
export type UseSlotPropsParameters<ElementType extends React.ElementType, SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps, OwnerState> = Omit<MergeSlotPropsParameters<SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps>, 'externalSlotProps'> & {
/**
* The type of the component used in the slot.
*/
elementType: ElementType | undefined;
/**
* The `slotProps.*` of the Base UI component.
*/
externalSlotProps: ExternalSlotProps | ((ownerState: OwnerState) => ExternalSlotProps) | undefined;
/**
* The ownerState of the Base UI component.
*/
ownerState: OwnerState;
/**
* Set to true if the slotProps callback should receive more props.
*/
skipResolvingSlotProps?: boolean;
};
export type UseSlotPropsResult<ElementType extends React.ElementType, SlotProps, AdditionalProps, OwnerState> = AppendOwnerStateReturnType<ElementType, MergeSlotPropsResult<SlotProps, object, object, AdditionalProps>['props'] & {
ref: ((instance: any | null) => void) | null;
}, OwnerState>;
/**
* @ignore - do not document.
* Builds the props to be passed into the slot of an unstyled component.
* It merges the internal props of the component with the ones supplied by the user, allowing to customize the behavior.
* If the slot component is not a host component, it also merges in the `ownerState`.
*
* @param parameters.getSlotProps - A function that returns the props to be passed to the slot component.
*/
export declare function useSlotProps<ElementType extends React.ElementType, SlotProps, AdditionalProps, OwnerState>(parameters: UseSlotPropsParameters<ElementType, SlotProps, object, WithCommonProps<Record<string, any>>, AdditionalProps, OwnerState>): import("@mui/types").Simplify<import("@mui/types").Simplify<SlotProps & object & AdditionalProps & {
className?: string | undefined;
style?: React.CSSProperties | undefined;
}> & {
ref: ((instance: any) => void) | null;
} & {
ownerState: ElementType extends React.ComponentType<any> ? OwnerState : ElementType extends keyof JSX.IntrinsicElements ? undefined : OwnerState | undefined;
}>;
+39
View File
@@ -0,0 +1,39 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["elementType", "externalSlotProps", "ownerState", "skipResolvingSlotProps"];
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import { appendOwnerState } from './appendOwnerState';
import { mergeSlotProps } from './mergeSlotProps';
import { resolveComponentProps } from './resolveComponentProps';
/**
* @ignore - do not document.
* Builds the props to be passed into the slot of an unstyled component.
* It merges the internal props of the component with the ones supplied by the user, allowing to customize the behavior.
* If the slot component is not a host component, it also merges in the `ownerState`.
*
* @param parameters.getSlotProps - A function that returns the props to be passed to the slot component.
*/
export function useSlotProps(parameters) {
var _parameters$additiona;
const {
elementType,
externalSlotProps,
ownerState,
skipResolvingSlotProps = false
} = parameters,
rest = _objectWithoutPropertiesLoose(parameters, _excluded);
const resolvedComponentsProps = skipResolvingSlotProps ? {} : resolveComponentProps(externalSlotProps, ownerState);
const {
props: mergedProps,
internalRef
} = mergeSlotProps(_extends({}, rest, {
externalSlotProps: resolvedComponentsProps
}));
const ref = useForkRef(internalRef, resolvedComponentsProps == null ? void 0 : resolvedComponentsProps.ref, (_parameters$additiona = parameters.additionalProps) == null ? void 0 : _parameters$additiona.ref);
const props = appendOwnerState(elementType, _extends({}, mergedProps, {
ref
}), ownerState);
return props;
}
+11
View File
@@ -0,0 +1,11 @@
import * as React from 'react';
/**
* @ignore - internal hook.
*
* Provides a handler for text navigation.
* It's used to navigate a list by typing the first letters of the options.
*
* @param callback A function to be called when the navigation should be performed.
* @returns A function to be used in a keydown event handler.
*/
export declare function useTextNavigation(callback: (searchString: string, event: React.KeyboardEvent) => void): (event: React.KeyboardEvent) => void;
+35
View File
@@ -0,0 +1,35 @@
'use client';
import * as React from 'react';
const TEXT_NAVIGATION_RESET_TIMEOUT = 500; // milliseconds
/**
* @ignore - internal hook.
*
* Provides a handler for text navigation.
* It's used to navigate a list by typing the first letters of the options.
*
* @param callback A function to be called when the navigation should be performed.
* @returns A function to be used in a keydown event handler.
*/
export function useTextNavigation(callback) {
const textCriteriaRef = React.useRef({
searchString: '',
lastTime: null
});
return React.useCallback(event => {
if (event.key.length === 1 && event.key !== ' ') {
const textCriteria = textCriteriaRef.current;
const lowerKey = event.key.toLowerCase();
const currentTime = performance.now();
if (textCriteria.searchString.length > 0 && textCriteria.lastTime && currentTime - textCriteria.lastTime > TEXT_NAVIGATION_RESET_TIMEOUT) {
textCriteria.searchString = lowerKey;
} else if (textCriteria.searchString.length !== 1 || lowerKey !== textCriteria.searchString) {
// If there is just one character in the buffer and the key is the same, do not append
textCriteria.searchString += lowerKey;
}
textCriteria.lastTime = currentTime;
callback(textCriteria.searchString, event);
}
}, [callback]);
}