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

+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 ?? false
}), [disableDefaultClasses]);
return /*#__PURE__*/_jsx(ClassNameConfiguratorContext.Provider, {
value: contextValue,
children: children
});
}
+1
View File
@@ -0,0 +1 @@
export {};
+1
View File
@@ -0,0 +1 @@
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 @@
export function areArraysEqual(array1, array2, itemComparer = (a, b) => a === b) {
return array1.length === array2.length && array1.every((value, index) => itemComparer(value, array2[index]));
}
+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;
};
}
+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;
}
+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';
+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';
}
+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?.className, className, externalForwardedProps?.className, externalSlotProps?.className);
const mergedStyle = _extends({}, additionalProps?.style, externalForwardedProps?.style, 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?.className, additionalProps?.className, className, externalForwardedProps?.className, externalSlotProps?.className);
const mergedStyle = _extends({}, internalSlotProps?.style, additionalProps?.style, externalForwardedProps?.style, 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
};
}
+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;
}
+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
}));
});
}
+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;
}
+1
View File
@@ -0,0 +1 @@
export {};
+133
View File
@@ -0,0 +1,133 @@
'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 => {
// go through all state keys and compare them with the previous state
const stateComparer = 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)) {
onStateChange?.(lastActionRef.current.event ?? null, key, nextStateItem, lastActionRef.current.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 ?? EMPTY_OBJECT,
onStateChange: onStateChange ?? NOOP,
controlledProps,
lastActionRef
});
return [getControlledState(nextState, controlledProps), dispatchWithContext];
}
+1
View File
@@ -0,0 +1 @@
export {};
+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({});
}, []);
}
+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;
}
+27
View File
@@ -0,0 +1,27 @@
'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 => {
setRootElementName(instance?.tagName ?? '');
}, []);
return [rootElementName, updateRootElementName];
}
+38
View File
@@ -0,0 +1,38 @@
'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) {
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?.ref, parameters.additionalProps?.ref);
const props = appendOwnerState(elementType, _extends({}, mergedProps, {
ref
}), ownerState);
return props;
}
+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]);
}