Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[InputUnstyled] Define ownerState and slot props' types #32491

Merged
merged 4 commits into from
May 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/data/base/components/input/UseInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const StyledInputElement = styled('input')(
);

const CustomInput = React.forwardRef(function CustomInput(props, ref) {
const { getRootProps, getInputProps } = useInput(props, ref);
const { getRootProps, getInputProps } = useInput({ ...props, inputRef: ref });

return (
<div {...getRootProps()}>
Expand Down
2 changes: 1 addition & 1 deletion docs/data/base/components/input/UseInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const CustomInput = React.forwardRef(function CustomInput(
props: React.InputHTMLAttributes<HTMLInputElement>,
ref: React.ForwardedRef<HTMLInputElement>,
) {
const { getRootProps, getInputProps } = useInput(props, ref);
const { getRootProps, getInputProps } = useInput({ ...props, inputRef: ref });

return (
<div {...getRootProps()}>
Expand Down
8 changes: 7 additions & 1 deletion docs/pages/base/api/input-unstyled.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@
"required": { "type": { "name": "bool" } },
"rows": { "type": { "name": "number" } },
"startAdornment": { "type": { "name": "node" } },
"type": { "type": { "name": "string" }, "default": "'text'" },
"type": {
"type": {
"name": "enum",
"description": "'button'<br>&#124;&nbsp;'checkbox'<br>&#124;&nbsp;'color'<br>&#124;&nbsp;'date'<br>&#124;&nbsp;'datetime-local'<br>&#124;&nbsp;'email'<br>&#124;&nbsp;'file'<br>&#124;&nbsp;'hidden'<br>&#124;&nbsp;'image'<br>&#124;&nbsp;'month'<br>&#124;&nbsp;'number'<br>&#124;&nbsp;'password'<br>&#124;&nbsp;'radio'<br>&#124;&nbsp;'range'<br>&#124;&nbsp;'reset'<br>&#124;&nbsp;'search'<br>&#124;&nbsp;'submit'<br>&#124;&nbsp;'tel'<br>&#124;&nbsp;'text'<br>&#124;&nbsp;'time'<br>&#124;&nbsp;'url'<br>&#124;&nbsp;'week'"
},
"default": "'text'"
},
"value": { "type": { "name": "any" } }
},
"name": "InputUnstyled",
Expand Down
23 changes: 23 additions & 0 deletions packages/mui-base/src/InputUnstyled/InputUnstyled.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as React from 'react';
import InputUnstyled, {
InputUnstyledInputSlotProps,
InputUnstyledRootSlotProps,
} from '@mui/base/InputUnstyled';

const InputRoot = React.forwardRef(function InputRoot(
props: InputUnstyledRootSlotProps,
ref: React.Ref<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-focused={ownerState.focused} {...other} ref={ref} />;
});

const InputInput = React.forwardRef(function InputInput(
props: InputUnstyledInputSlotProps,
ref: React.Ref<HTMLInputElement>,
) {
const { ownerState, ...other } = props;
return <input data-focused={ownerState.focused} {...other} ref={ref} />;
});

const styledInput = <InputUnstyled components={{ Root: InputRoot, Input: InputInput }} />;
70 changes: 49 additions & 21 deletions packages/mui-base/src/InputUnstyled/InputUnstyled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,16 @@ import PropTypes from 'prop-types';
import appendOwnerState from '../utils/appendOwnerState';
import isHostComponent from '../utils/isHostComponent';
import classes from './inputUnstyledClasses';
import InputUnstyledProps, { InputUnstyledTypeMap } from './InputUnstyledProps';
import {
InputUnstyledInputSlotProps,
InputUnstyledOwnerState,
InputUnstyledProps,
InputUnstyledRootSlotProps,
InputUnstyledTypeMap,
} from './InputUnstyled.types';
import useInput from './useInput';
import { WithOptionalOwnerState } from '../utils';

/**
*
* Demos:
Expand Down Expand Up @@ -63,22 +71,20 @@ const InputUnstyled = React.forwardRef(function InputUnstyled(
formControlContext,
error: errorState,
disabled: disabledState,
} = useInput(
{
disabled,
defaultValue,
error,
onBlur,
onClick,
onChange,
onFocus,
required,
value,
},
componentsProps.input?.ref,
);
} = useInput({
disabled,
defaultValue,
error,
inputRef: componentsProps.input?.ref,
onBlur,
onClick,
onChange,
onFocus,
required,
value,
});

const ownerState = {
const ownerState: InputUnstyledOwnerState = {
...props,
disabled: disabledState,
error: errorState,
Expand Down Expand Up @@ -119,7 +125,7 @@ const InputUnstyled = React.forwardRef(function InputUnstyled(
};

const Root = component ?? components.Root ?? 'div';
const rootProps = appendOwnerState(
const rootProps: WithOptionalOwnerState<InputUnstyledRootSlotProps> = appendOwnerState(
Root,
{
...getRootProps({ ...other, ...componentsProps.root }),
Expand All @@ -130,8 +136,7 @@ const InputUnstyled = React.forwardRef(function InputUnstyled(

let Input = components.Input ?? 'input';

// TODO: type this properly
let inputProps: Record<string, any> = appendOwnerState(
let inputProps: WithOptionalOwnerState<InputUnstyledInputSlotProps> = appendOwnerState(
Input,
{
...getInputProps({ ...componentsProps.input, ...propsToForward }),
Expand All @@ -156,9 +161,9 @@ const InputUnstyled = React.forwardRef(function InputUnstyled(
}

inputProps = {
type: undefined,
...(!hasHostTextarea && { minRows: rows || minRows, maxRows: rows || maxRows }),
...(hasHostTextarea ? inputPropsWithoutOwnerState : inputProps),
type: undefined,
};

Input = components.Textarea ?? 'textarea';
Expand Down Expand Up @@ -320,7 +325,30 @@ InputUnstyled.propTypes /* remove-proptypes */ = {
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
* @default 'text'
*/
type: PropTypes.string,
type: PropTypes /* @typescript-to-proptypes-ignore */.oneOf([
'button',
'checkbox',
'color',
'date',
'datetime-local',
'email',
'file',
'hidden',
'image',
'month',
'number',
'password',
'radio',
'range',
'reset',
'search',
'submit',
'tel',
'text',
'time',
'url',
'week',
]),
/**
* The value of the `input` element, required for a controlled component.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,9 @@
import React from 'react';
import { OverrideProps } from '@mui/types';
import { OverrideProps, Simplify } from '@mui/types';
import { FormControlUnstyledState } from '../FormControlUnstyled';
import { UseInputParameters, UseInputRootSlotProps } from './useInput.types';

export interface InputOwnerState
extends Omit<InputUnstyledProps, 'component' | 'components' | 'componentsProps'> {
formControl: FormControlUnstyledState;
focused: boolean;
}

export interface UseInputProps {
/**
* 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.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
error?: boolean;
onBlur?: React.FocusEventHandler;
onClick?: React.MouseEventHandler;
onChange?: React.ChangeEventHandler<HTMLInputElement>;
onFocus?: React.FocusEventHandler;
/**
* 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 InputUnstyledOwnProps extends UseInputProps {
export interface InputUnstyledOwnProps extends UseInputParameters {
'aria-describedby'?: string;
'aria-label'?: string;
'aria-labelledby'?: string;
Expand Down Expand Up @@ -68,8 +36,8 @@ export interface InputUnstyledOwnProps extends UseInputProps {
* @default {}
*/
componentsProps?: {
root?: React.ComponentPropsWithRef<'div'> & { ownerState: InputOwnerState };
input?: React.ComponentPropsWithRef<'input'> & { ownerState: InputOwnerState };
root?: React.ComponentPropsWithRef<'div'>;
input?: React.ComponentPropsWithRef<'input'>;
};
/**
* Trailing adornment for this input.
Expand Down Expand Up @@ -119,7 +87,7 @@ export interface InputUnstyledOwnProps extends UseInputProps {
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
* @default 'text'
*/
type?: string;
type?: React.HTMLInputTypeAttribute;
/**
* The value of the `input` element, required for a controlled component.
*/
Expand All @@ -131,7 +99,7 @@ export interface InputUnstyledTypeMap<P = {}, D extends React.ElementType = 'div
defaultComponent: D;
}

type InputUnstyledProps<
export type InputUnstyledProps<
D extends React.ElementType = InputUnstyledTypeMap['defaultComponent'],
P = {},
> = OverrideProps<InputUnstyledTypeMap<P, D>, D> & {
Expand All @@ -143,4 +111,36 @@ type InputUnstyledProps<
component?: D;
};

export default InputUnstyledProps;
export type InputUnstyledOwnerState = Simplify<
Omit<InputUnstyledProps, 'component' | 'components' | 'componentsProps'> & {
formControlContext: FormControlUnstyledState | undefined;
focused: boolean;
}
>;

export type InputUnstyledRootSlotProps = Simplify<
UseInputRootSlotProps & {
ownerState: InputUnstyledOwnerState;
className: string;
children?: React.ReactNode;
}
>;

export type InputUnstyledInputSlotProps = Simplify<
Omit<UseInputRootSlotProps, 'onClick'> & {
'aria-describedby': React.AriaAttributes['aria-describedby'];
'aria-label': React.AriaAttributes['aria-label'];
'aria-labelledby': React.AriaAttributes['aria-labelledby'];
autoComplete: string | undefined;
autoFocus: boolean | undefined;
className: string;
id: string | undefined;
name: string | undefined;
onKeyDown: React.KeyboardEventHandler<HTMLInputElement> | undefined;
onKeyUp: React.KeyboardEventHandler<HTMLInputElement> | undefined;
ownerState: InputUnstyledOwnerState;
placeholder: string | undefined;
readOnly: boolean | undefined;
type: React.HTMLInputTypeAttribute | undefined;
}
>;
5 changes: 3 additions & 2 deletions packages/mui-base/src/InputUnstyled/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
export { default } from './InputUnstyled';

export type { default as InputUnstyledProps } from './InputUnstyledProps';
export * from './InputUnstyledProps';
export * from './InputUnstyled.types';

export { default as useInput } from './useInput';

export * from './useInput.types';

export { default as inputUnstyledClasses } from './inputUnstyledClasses';
export * from './inputUnstyledClasses';
29 changes: 19 additions & 10 deletions packages/mui-base/src/InputUnstyled/useInput.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
import * as React from 'react';
import MuiError from '@mui/utils/macros/MuiError.macro';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import { useFormControlUnstyledContext } from '../FormControlUnstyled';
import { FormControlUnstyledState, useFormControlUnstyledContext } from '../FormControlUnstyled';
import extractEventHandlers from '../utils/extractEventHandlers';
import { UseInputProps } from './InputUnstyledProps';
import {
UseInputInputSlotProps,
UseInputParameters,
UseInputRootSlotProps,
} from './useInput.types';

export default function useInput(props: UseInputProps, inputRef?: React.Ref<HTMLInputElement>) {
export default function useInput(parameters: UseInputParameters) {
const {
defaultValue: defaultValueProp,
disabled: disabledProp = false,
error: errorProp = false,
onBlur,
onChange,
onFocus,
inputRef,
required: requiredProp = false,
value: valueProp,
} = props;
} = parameters;

const formControlContext = useFormControlUnstyledContext();
const formControlContext: FormControlUnstyledState | undefined = useFormControlUnstyledContext();

let defaultValue: unknown;
let disabled: boolean;
Expand All @@ -35,7 +40,7 @@ export default function useInput(props: UseInputProps, inputRef?: React.Ref<HTML
if (process.env.NODE_ENV !== 'production') {
const definedLocalProps = (
['defaultValue', 'disabled', 'error', 'required', 'value'] as const
).filter((prop) => props[prop] !== undefined);
).filter((prop) => parameters[prop] !== undefined);

if (definedLocalProps.length > 0) {
console.warn(
Expand Down Expand Up @@ -149,9 +154,11 @@ export default function useInput(props: UseInputProps, inputRef?: React.Ref<HTML
otherHandlers.onClick?.(event);
};

const getRootProps = (externalProps?: Record<string, unknown>) => {
const getRootProps = <TOther extends Record<string, any> = {}>(
externalProps: TOther = {} as TOther,
): UseInputRootSlotProps<TOther> => {
// onBlur, onChange and onFocus are forwarded to the input slot.
const propsEventHandlers = extractEventHandlers(props, ['onBlur', 'onChange', 'onFocus']);
const propsEventHandlers = extractEventHandlers(parameters, ['onBlur', 'onChange', 'onFocus']);
const externalEventHandlers = { ...propsEventHandlers, ...extractEventHandlers(externalProps) };

return {
Expand All @@ -161,7 +168,9 @@ export default function useInput(props: UseInputProps, inputRef?: React.Ref<HTML
};
};

const getInputProps = (externalProps?: Record<string, unknown>) => {
const getInputProps = <TOther extends Record<string, any> = {}>(
externalProps: TOther = {} as TOther,
): UseInputInputSlotProps<TOther> => {
const propsEventHandlers: Record<string, React.EventHandler<any> | undefined> = {
onBlur,
onChange,
Expand All @@ -170,7 +179,7 @@ export default function useInput(props: UseInputProps, inputRef?: React.Ref<HTML

const externalEventHandlers = { ...propsEventHandlers, ...extractEventHandlers(externalProps) };

const mergedEventHandlers: Record<string, React.EventHandler<any>> = {
const mergedEventHandlers = {
...externalProps,
...externalEventHandlers,
onBlur: handleBlur(externalEventHandlers),
Expand Down
Loading