1
This commit is contained in:
+9
@@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2019-present afc163
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
# rc-input ⌨️
|
||||
|
||||
[![NPM version][npm-image]][npm-url]
|
||||
[![npm download][download-image]][download-url]
|
||||
[![build status][github-actions-image]][github-actions-url]
|
||||
[![Codecov][codecov-image]][codecov-url]
|
||||
[![bundle size][bundlephobia-image]][bundlephobia-url]
|
||||
[![dumi][dumi-image]][dumi-url]
|
||||
|
||||
[npm-image]: http://img.shields.io/npm/v/rc-input.svg?style=flat-square
|
||||
[npm-url]: http://npmjs.org/package/rc-input
|
||||
[travis-image]: https://img.shields.io/travis/react-component/input/master?style=flat-square
|
||||
[travis-url]: https://travis-ci.com/react-component/input
|
||||
[github-actions-image]: https://github.com/react-component/input/workflows/CI/badge.svg
|
||||
[github-actions-url]: https://github.com/react-component/input/actions
|
||||
[codecov-image]: https://img.shields.io/codecov/c/github/react-component/input/master.svg?style=flat-square
|
||||
[codecov-url]: https://app.codecov.io/gh/react-component/input
|
||||
[david-url]: https://david-dm.org/react-component/input
|
||||
[david-image]: https://david-dm.org/react-component/input/status.svg?style=flat-square
|
||||
[david-dev-url]: https://david-dm.org/react-component/input?type=dev
|
||||
[david-dev-image]: https://david-dm.org/react-component/input/dev-status.svg?style=flat-square
|
||||
[download-image]: https://img.shields.io/npm/dm/rc-input.svg?style=flat-square
|
||||
[download-url]: https://npmjs.org/package/rc-input
|
||||
[bundlephobia-url]: https://bundlephobia.com/package/rc-input
|
||||
[bundlephobia-image]: https://badgen.net/bundlephobia/minzip/rc-input
|
||||
[dumi-url]: https://github.com/umijs/dumi
|
||||
[dumi-image]: https://img.shields.io/badge/docs%20by-dumi-blue?style=flat-square
|
||||
|
||||
## Install
|
||||
|
||||
[](https://npmjs.org/package/rc-input)
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import Input from 'rc-input';
|
||||
import { render } from 'react-dom';
|
||||
|
||||
render(<Input placeholder="input" allowClear />, mountNode);
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
| Property | Type | Default | Description |
|
||||
| --------------------- | ---------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| prefixCls | string | rc-input | |
|
||||
| className | string | '' | additional class name of input |
|
||||
| style | React.CSSProperties | | style properties of input |
|
||||
| affixWrapperClassName | string | - | className with 'rc-input-affix-wrapper' |
|
||||
| groupClassName | string | - | className with 'rc-input-group-wrapper' |
|
||||
| wrapperClassName | string | - | className with 'rc-input-wrapper' |
|
||||
| addonAfter | ReactNode | - | The label text displayed after (on the right side of) the input field |
|
||||
| addonBefore | ReactNode | - | The label text displayed before (on the left side of) the input field |
|
||||
| allowClear | boolean | { clearIcon: ReactNode } | false | If allow to remove input content with clear icon |
|
||||
| bordered | boolean | true | Whether has border style |
|
||||
| defaultValue | string | - | The initial input content |
|
||||
| disabled | boolean | false | Whether the input is disabled |
|
||||
| id | string | - | The ID for input |
|
||||
| maxLength | number | - | The max length |
|
||||
| showCount | boolean | { formatter: ({ value: string, count: number, maxLength?: number }) => ReactNode } | false | Whether show text count |
|
||||
| prefix | ReactNode | - | The prefix icon for the Input |
|
||||
| suffix | ReactNode | - | The suffix icon for the Input |
|
||||
| type | string | `text` | The type of input, see: [MDN](https://developer.mozilla.org/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types)( use `Input.TextArea` instead of `type="textarea"`) |
|
||||
| value | string | - | The input content value |
|
||||
| onChange | function(e) | - | Callback when user input |
|
||||
| onPressEnter | function(e) | - | The callback function that is triggered when Enter key is pressed |
|
||||
|
||||
## inputRef
|
||||
|
||||
```tsx | pure
|
||||
const inputRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current.focus();// the input will get focus
|
||||
inputRef.current.blur();// the input will lose focus
|
||||
console.log(inputRef.current.input);// The origin input element
|
||||
}, []);
|
||||
// ....
|
||||
<Input ref={inputRef} />
|
||||
```
|
||||
|
||||
| Property | Type | Description |
|
||||
| -------- | --------------------------------------- | --------------------------------- |
|
||||
| focus | `(options?: InputFocusOptions) => void` | The input get focus when called |
|
||||
| blur | `() => void` | The input loses focus when called |
|
||||
| input | `HTMLInputElement \| null` | The origin input element |
|
||||
|
||||
|
||||
|
||||
## Development
|
||||
|
||||
```
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
rc-input is released under the MIT license.
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
.rc-input-out-of-range {
|
||||
color: red;
|
||||
}
|
||||
.rc-input-affix-wrapper {
|
||||
padding: 2px 8px;
|
||||
overflow: hidden;
|
||||
border: 1px solid lightgray;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.rc-input-affix-wrapper:hover,
|
||||
.rc-input-affix-wrapper:focus-within {
|
||||
border-color: #000;
|
||||
}
|
||||
.rc-input-affix-wrapper input {
|
||||
padding: 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
}
|
||||
.rc-input-clear-icon {
|
||||
padding: 0;
|
||||
font-size: 12px;
|
||||
background: none;
|
||||
border: none;
|
||||
}
|
||||
.rc-input-clear-icon-hidden {
|
||||
display: none;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
.rc-input {
|
||||
&-out-of-range {
|
||||
color: red;
|
||||
}
|
||||
|
||||
&-affix-wrapper {
|
||||
padding: 2px 8px;
|
||||
overflow: hidden;
|
||||
border: 1px solid lightgray;
|
||||
border-radius: 2px;
|
||||
|
||||
&:hover,
|
||||
&:focus-within {
|
||||
border-color: #000;
|
||||
}
|
||||
|
||||
input {
|
||||
padding: 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
&-clear-icon {
|
||||
padding: 0;
|
||||
font-size: 12px;
|
||||
background: none;
|
||||
border: none;
|
||||
|
||||
&-hidden {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import React from 'react';
|
||||
import type { BaseInputProps } from './interface';
|
||||
export interface HolderRef {
|
||||
/** Provider holder ref. Will return `null` if not wrap anything */
|
||||
nativeElement: HTMLElement | null;
|
||||
}
|
||||
declare const BaseInput: React.ForwardRefExoticComponent<BaseInputProps & React.RefAttributes<HolderRef>>;
|
||||
export default BaseInput;
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
||||
import { clsx } from 'clsx';
|
||||
import React, { cloneElement, useRef } from 'react';
|
||||
import { hasAddon, hasPrefixSuffix } from "./utils/commonUtils";
|
||||
const BaseInput = /*#__PURE__*/React.forwardRef((props, ref) => {
|
||||
const {
|
||||
inputElement: inputEl,
|
||||
children,
|
||||
prefixCls,
|
||||
prefix,
|
||||
suffix,
|
||||
addonBefore,
|
||||
addonAfter,
|
||||
className,
|
||||
style,
|
||||
disabled,
|
||||
readOnly,
|
||||
focused,
|
||||
triggerFocus,
|
||||
allowClear,
|
||||
value,
|
||||
handleReset,
|
||||
hidden,
|
||||
classes,
|
||||
classNames,
|
||||
dataAttrs,
|
||||
styles,
|
||||
components,
|
||||
onClear
|
||||
} = props;
|
||||
const inputElement = children ?? inputEl;
|
||||
const AffixWrapperComponent = components?.affixWrapper || 'span';
|
||||
const GroupWrapperComponent = components?.groupWrapper || 'span';
|
||||
const WrapperComponent = components?.wrapper || 'span';
|
||||
const GroupAddonComponent = components?.groupAddon || 'span';
|
||||
const containerRef = useRef(null);
|
||||
const onInputClick = e => {
|
||||
if (containerRef.current?.contains(e.target)) {
|
||||
triggerFocus?.();
|
||||
}
|
||||
};
|
||||
const hasAffix = hasPrefixSuffix(props);
|
||||
let element = /*#__PURE__*/cloneElement(inputElement, {
|
||||
value,
|
||||
className: clsx(inputElement.props?.className, !hasAffix && classNames?.variant) || null
|
||||
});
|
||||
|
||||
// ======================== Ref ======================== //
|
||||
const groupRef = useRef(null);
|
||||
React.useImperativeHandle(ref, () => ({
|
||||
nativeElement: groupRef.current || containerRef.current
|
||||
}));
|
||||
|
||||
// ================== Prefix & Suffix ================== //
|
||||
if (hasAffix) {
|
||||
// ================== Clear Icon ================== //
|
||||
let clearIcon = null;
|
||||
if (allowClear) {
|
||||
const needClear = !disabled && !readOnly && value;
|
||||
const clearIconCls = `${prefixCls}-clear-icon`;
|
||||
const iconNode = typeof allowClear === 'object' && allowClear?.clearIcon ? allowClear.clearIcon : '✖';
|
||||
clearIcon = /*#__PURE__*/React.createElement("button", {
|
||||
type: "button",
|
||||
tabIndex: -1,
|
||||
onClick: event => {
|
||||
handleReset?.(event);
|
||||
onClear?.();
|
||||
}
|
||||
// Do not trigger onBlur when clear input
|
||||
// https://github.com/ant-design/ant-design/issues/31200
|
||||
,
|
||||
onMouseDown: e => e.preventDefault(),
|
||||
className: clsx(clearIconCls, {
|
||||
[`${clearIconCls}-hidden`]: !needClear,
|
||||
[`${clearIconCls}-has-suffix`]: !!suffix
|
||||
})
|
||||
}, iconNode);
|
||||
}
|
||||
const affixWrapperPrefixCls = `${prefixCls}-affix-wrapper`;
|
||||
const affixWrapperCls = clsx(affixWrapperPrefixCls, {
|
||||
[`${prefixCls}-disabled`]: disabled,
|
||||
[`${affixWrapperPrefixCls}-disabled`]: disabled,
|
||||
// Not used, but keep it
|
||||
[`${affixWrapperPrefixCls}-focused`]: focused,
|
||||
// Not used, but keep it
|
||||
[`${affixWrapperPrefixCls}-readonly`]: readOnly,
|
||||
[`${affixWrapperPrefixCls}-input-with-clear-btn`]: suffix && allowClear && value
|
||||
}, classes?.affixWrapper, classNames?.affixWrapper, classNames?.variant);
|
||||
const suffixNode = (suffix || allowClear) && /*#__PURE__*/React.createElement("span", {
|
||||
className: clsx(`${prefixCls}-suffix`, classNames?.suffix),
|
||||
style: styles?.suffix
|
||||
}, clearIcon, suffix);
|
||||
element = /*#__PURE__*/React.createElement(AffixWrapperComponent, _extends({
|
||||
className: affixWrapperCls,
|
||||
style: styles?.affixWrapper,
|
||||
onClick: onInputClick
|
||||
}, dataAttrs?.affixWrapper, {
|
||||
ref: containerRef
|
||||
}), prefix && /*#__PURE__*/React.createElement("span", {
|
||||
className: clsx(`${prefixCls}-prefix`, classNames?.prefix),
|
||||
style: styles?.prefix
|
||||
}, prefix), element, suffixNode);
|
||||
}
|
||||
|
||||
// ================== Addon ================== //
|
||||
if (hasAddon(props)) {
|
||||
const wrapperCls = `${prefixCls}-group`;
|
||||
const addonCls = `${wrapperCls}-addon`;
|
||||
const groupWrapperCls = `${wrapperCls}-wrapper`;
|
||||
const mergedWrapperClassName = clsx(`${prefixCls}-wrapper`, wrapperCls, classes?.wrapper, classNames?.wrapper);
|
||||
const mergedGroupClassName = clsx(groupWrapperCls, {
|
||||
[`${groupWrapperCls}-disabled`]: disabled
|
||||
}, classes?.group, classNames?.groupWrapper);
|
||||
|
||||
// Need another wrapper for changing display:table to display:inline-block
|
||||
// and put style prop in wrapper
|
||||
element = /*#__PURE__*/React.createElement(GroupWrapperComponent, {
|
||||
className: mergedGroupClassName,
|
||||
ref: groupRef
|
||||
}, /*#__PURE__*/React.createElement(WrapperComponent, {
|
||||
className: mergedWrapperClassName
|
||||
}, addonBefore && /*#__PURE__*/React.createElement(GroupAddonComponent, {
|
||||
className: addonCls
|
||||
}, addonBefore), element, addonAfter && /*#__PURE__*/React.createElement(GroupAddonComponent, {
|
||||
className: addonCls
|
||||
}, addonAfter)));
|
||||
}
|
||||
|
||||
// `className` and `style` are always on the root element
|
||||
return /*#__PURE__*/React.cloneElement(element, {
|
||||
className: clsx(element.props?.className, className) || null,
|
||||
style: {
|
||||
...element.props?.style,
|
||||
...style
|
||||
},
|
||||
hidden
|
||||
});
|
||||
});
|
||||
export default BaseInput;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import React from 'react';
|
||||
import type { InputProps, InputRef } from './interface';
|
||||
declare const Input: React.ForwardRefExoticComponent<InputProps & React.RefAttributes<InputRef>>;
|
||||
export default Input;
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
||||
import { clsx } from 'clsx';
|
||||
import useControlledState from "@rc-component/util/es/hooks/useControlledState";
|
||||
import omit from "@rc-component/util/es/omit";
|
||||
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
|
||||
import BaseInput from "./BaseInput";
|
||||
import useCount from "./hooks/useCount";
|
||||
import { resolveOnChange } from "./utils/commonUtils";
|
||||
import { triggerFocus } from "@rc-component/util/es/Dom/focus";
|
||||
const Input = /*#__PURE__*/forwardRef((props, ref) => {
|
||||
const {
|
||||
autoComplete,
|
||||
onChange,
|
||||
onFocus,
|
||||
onBlur,
|
||||
onPressEnter,
|
||||
onKeyDown,
|
||||
onKeyUp,
|
||||
prefixCls = 'rc-input',
|
||||
disabled,
|
||||
htmlSize,
|
||||
className,
|
||||
maxLength,
|
||||
suffix,
|
||||
showCount,
|
||||
count,
|
||||
type = 'text',
|
||||
classes,
|
||||
classNames,
|
||||
styles,
|
||||
onCompositionStart,
|
||||
onCompositionEnd,
|
||||
...rest
|
||||
} = props;
|
||||
const [focused, setFocused] = useState(false);
|
||||
const compositionRef = useRef(false);
|
||||
const keyLockRef = useRef(false);
|
||||
const inputRef = useRef(null);
|
||||
const holderRef = useRef(null);
|
||||
const focus = option => {
|
||||
if (inputRef.current) {
|
||||
triggerFocus(inputRef.current, option);
|
||||
}
|
||||
};
|
||||
|
||||
// ====================== Value =======================
|
||||
const [value, setValue] = useControlledState(props.defaultValue, props.value);
|
||||
const formatValue = value === undefined || value === null ? '' : String(value);
|
||||
|
||||
// =================== Select Range ===================
|
||||
const [selection, setSelection] = useState(null);
|
||||
|
||||
// ====================== Count =======================
|
||||
const countConfig = useCount(count, showCount);
|
||||
const mergedMax = countConfig.max || maxLength;
|
||||
const valueLength = countConfig.strategy(formatValue);
|
||||
const isOutOfRange = !!mergedMax && valueLength > mergedMax;
|
||||
|
||||
// ======================= Ref ========================
|
||||
useImperativeHandle(ref, () => ({
|
||||
focus,
|
||||
blur: () => {
|
||||
inputRef.current?.blur();
|
||||
},
|
||||
setSelectionRange: (start, end, direction) => {
|
||||
inputRef.current?.setSelectionRange(start, end, direction);
|
||||
},
|
||||
select: () => {
|
||||
inputRef.current?.select();
|
||||
},
|
||||
input: inputRef.current,
|
||||
nativeElement: holderRef.current?.nativeElement || inputRef.current
|
||||
}));
|
||||
useEffect(() => {
|
||||
if (keyLockRef.current) {
|
||||
keyLockRef.current = false;
|
||||
}
|
||||
setFocused(prev => prev && disabled ? false : prev);
|
||||
}, [disabled]);
|
||||
const triggerChange = (e, currentValue, info) => {
|
||||
let cutValue = currentValue;
|
||||
if (!compositionRef.current && countConfig.exceedFormatter && countConfig.max && countConfig.strategy(currentValue) > countConfig.max) {
|
||||
cutValue = countConfig.exceedFormatter(currentValue, {
|
||||
max: countConfig.max
|
||||
});
|
||||
if (currentValue !== cutValue) {
|
||||
setSelection([inputRef.current?.selectionStart || 0, inputRef.current?.selectionEnd || 0]);
|
||||
}
|
||||
} else if (info.source === 'compositionEnd') {
|
||||
// Avoid triggering twice
|
||||
// https://github.com/ant-design/ant-design/issues/46587
|
||||
return;
|
||||
}
|
||||
setValue(cutValue);
|
||||
if (inputRef.current) {
|
||||
resolveOnChange(inputRef.current, e, onChange, cutValue);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
if (selection) {
|
||||
inputRef.current?.setSelectionRange(...selection);
|
||||
}
|
||||
}, [selection]);
|
||||
const onInternalChange = e => {
|
||||
triggerChange(e, e.target.value, {
|
||||
source: 'change'
|
||||
});
|
||||
};
|
||||
const onInternalCompositionEnd = e => {
|
||||
compositionRef.current = false;
|
||||
triggerChange(e, e.currentTarget.value, {
|
||||
source: 'compositionEnd'
|
||||
});
|
||||
onCompositionEnd?.(e);
|
||||
};
|
||||
const handleKeyDown = e => {
|
||||
if (onPressEnter && e.key === 'Enter' && !keyLockRef.current && !e.nativeEvent.isComposing) {
|
||||
keyLockRef.current = true;
|
||||
onPressEnter(e);
|
||||
}
|
||||
onKeyDown?.(e);
|
||||
};
|
||||
const handleKeyUp = e => {
|
||||
if (e.key === 'Enter') {
|
||||
keyLockRef.current = false;
|
||||
}
|
||||
onKeyUp?.(e);
|
||||
};
|
||||
const handleFocus = e => {
|
||||
setFocused(true);
|
||||
onFocus?.(e);
|
||||
};
|
||||
const handleBlur = e => {
|
||||
if (keyLockRef.current) {
|
||||
keyLockRef.current = false;
|
||||
}
|
||||
setFocused(false);
|
||||
onBlur?.(e);
|
||||
};
|
||||
const handleReset = e => {
|
||||
setValue('');
|
||||
focus();
|
||||
if (inputRef.current) {
|
||||
resolveOnChange(inputRef.current, e, onChange);
|
||||
}
|
||||
};
|
||||
|
||||
// ====================== Input =======================
|
||||
const outOfRangeCls = isOutOfRange && `${prefixCls}-out-of-range`;
|
||||
const getInputElement = () => {
|
||||
// Fix https://fb.me/react-unknown-prop
|
||||
const otherProps = omit(props, ['prefixCls', 'onPressEnter', 'addonBefore', 'addonAfter', 'prefix', 'suffix', 'allowClear',
|
||||
// Input elements must be either controlled or uncontrolled,
|
||||
// specify either the value prop, or the defaultValue prop, but not both.
|
||||
'defaultValue', 'showCount', 'count', 'classes', 'htmlSize', 'styles', 'classNames', 'onClear']);
|
||||
return /*#__PURE__*/React.createElement("input", _extends({
|
||||
autoComplete: autoComplete
|
||||
}, otherProps, {
|
||||
onChange: onInternalChange,
|
||||
onFocus: handleFocus,
|
||||
onBlur: handleBlur,
|
||||
onKeyDown: handleKeyDown,
|
||||
onKeyUp: handleKeyUp,
|
||||
className: clsx(prefixCls, {
|
||||
[`${prefixCls}-disabled`]: disabled
|
||||
}, classNames?.input),
|
||||
style: styles?.input,
|
||||
ref: inputRef,
|
||||
size: htmlSize,
|
||||
type: type,
|
||||
onCompositionStart: e => {
|
||||
compositionRef.current = true;
|
||||
onCompositionStart?.(e);
|
||||
},
|
||||
onCompositionEnd: onInternalCompositionEnd
|
||||
}));
|
||||
};
|
||||
const getSuffix = () => {
|
||||
// Max length value
|
||||
const hasMaxLength = Number(mergedMax) > 0;
|
||||
if (suffix || countConfig.show) {
|
||||
const dataCount = countConfig.showFormatter ? countConfig.showFormatter({
|
||||
value: formatValue,
|
||||
count: valueLength,
|
||||
maxLength: mergedMax
|
||||
}) : `${valueLength}${hasMaxLength ? ` / ${mergedMax}` : ''}`;
|
||||
return /*#__PURE__*/React.createElement(React.Fragment, null, countConfig.show && /*#__PURE__*/React.createElement("span", {
|
||||
className: clsx(`${prefixCls}-show-count-suffix`, {
|
||||
[`${prefixCls}-show-count-has-suffix`]: !!suffix
|
||||
}, classNames?.count),
|
||||
style: {
|
||||
...styles?.count
|
||||
}
|
||||
}, dataCount), suffix);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// ====================== Render ======================
|
||||
return /*#__PURE__*/React.createElement(BaseInput, _extends({}, rest, {
|
||||
prefixCls: prefixCls,
|
||||
className: clsx(className, outOfRangeCls),
|
||||
handleReset: handleReset,
|
||||
value: formatValue,
|
||||
focused: focused,
|
||||
triggerFocus: focus,
|
||||
suffix: getSuffix(),
|
||||
disabled: disabled,
|
||||
classes: classes,
|
||||
classNames: classNames,
|
||||
styles: styles,
|
||||
ref: holderRef
|
||||
}), getInputElement());
|
||||
});
|
||||
export default Input;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { InputProps } from '..';
|
||||
import type { CountConfig, ShowCountFormatter } from '../interface';
|
||||
type ForcedCountConfig = Omit<CountConfig, 'show'> & Pick<Required<CountConfig>, 'strategy'> & {
|
||||
show: boolean;
|
||||
showFormatter?: ShowCountFormatter;
|
||||
};
|
||||
/**
|
||||
* Cut `value` by the `count.max` prop.
|
||||
*/
|
||||
export declare function inCountRange(value: string, countConfig: ForcedCountConfig): boolean;
|
||||
export default function useCount(count?: CountConfig, showCount?: InputProps['showCount']): ForcedCountConfig;
|
||||
export {};
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import * as React from 'react';
|
||||
/**
|
||||
* Cut `value` by the `count.max` prop.
|
||||
*/
|
||||
export function inCountRange(value, countConfig) {
|
||||
if (!countConfig.max) {
|
||||
return true;
|
||||
}
|
||||
const count = countConfig.strategy(value);
|
||||
return count <= countConfig.max;
|
||||
}
|
||||
export default function useCount(count, showCount) {
|
||||
return React.useMemo(() => {
|
||||
let mergedConfig = {};
|
||||
if (showCount) {
|
||||
mergedConfig.show = typeof showCount === 'object' && showCount.formatter ? showCount.formatter : !!showCount;
|
||||
}
|
||||
mergedConfig = {
|
||||
...mergedConfig,
|
||||
...count
|
||||
};
|
||||
const {
|
||||
show,
|
||||
...rest
|
||||
} = mergedConfig;
|
||||
return {
|
||||
...rest,
|
||||
show: !!show,
|
||||
showFormatter: typeof show === 'function' ? show : undefined,
|
||||
strategy: rest.strategy || (value => value.length)
|
||||
};
|
||||
}, [count, showCount]);
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import BaseInput from './BaseInput';
|
||||
import Input from './Input';
|
||||
export { BaseInput };
|
||||
export type { InputProps, InputRef } from './interface';
|
||||
export default Input;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import BaseInput from "./BaseInput";
|
||||
import Input from "./Input";
|
||||
export { BaseInput };
|
||||
export default Input;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import type { CSSProperties, InputHTMLAttributes, KeyboardEventHandler, MouseEventHandler, ReactElement, ReactNode } from 'react';
|
||||
import type { LiteralUnion } from './utils/types';
|
||||
import type { InputFocusOptions } from '@rc-component/util/lib/Dom/focus';
|
||||
export interface CommonInputProps {
|
||||
prefix?: ReactNode;
|
||||
suffix?: ReactNode;
|
||||
addonBefore?: ReactNode;
|
||||
addonAfter?: ReactNode;
|
||||
/** @deprecated Use `classNames` instead */
|
||||
classes?: {
|
||||
affixWrapper?: string;
|
||||
group?: string;
|
||||
wrapper?: string;
|
||||
};
|
||||
classNames?: {
|
||||
affixWrapper?: string;
|
||||
prefix?: string;
|
||||
suffix?: string;
|
||||
groupWrapper?: string;
|
||||
wrapper?: string;
|
||||
variant?: string;
|
||||
};
|
||||
styles?: {
|
||||
affixWrapper?: CSSProperties;
|
||||
prefix?: CSSProperties;
|
||||
suffix?: CSSProperties;
|
||||
};
|
||||
allowClear?: boolean | {
|
||||
clearIcon?: ReactNode;
|
||||
};
|
||||
}
|
||||
type DataAttr = Record<`data-${string}`, string>;
|
||||
export type ValueType = InputHTMLAttributes<HTMLInputElement>['value'] | bigint;
|
||||
export interface BaseInputProps extends CommonInputProps {
|
||||
value?: ValueType;
|
||||
/** @deprecated Use `children` instead */
|
||||
inputElement?: ReactElement;
|
||||
prefixCls?: string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
disabled?: boolean;
|
||||
focused?: boolean;
|
||||
triggerFocus?: () => void;
|
||||
readOnly?: boolean;
|
||||
handleReset?: MouseEventHandler;
|
||||
onClear?: () => void;
|
||||
hidden?: boolean;
|
||||
dataAttrs?: {
|
||||
affixWrapper?: DataAttr;
|
||||
};
|
||||
components?: {
|
||||
affixWrapper?: 'span' | 'div';
|
||||
groupWrapper?: 'span' | 'div';
|
||||
wrapper?: 'span' | 'div';
|
||||
groupAddon?: 'span' | 'div';
|
||||
};
|
||||
children: ReactElement;
|
||||
}
|
||||
export type ShowCountFormatter = (args: {
|
||||
value: string;
|
||||
count: number;
|
||||
maxLength?: number;
|
||||
}) => ReactNode;
|
||||
export type ExceedFormatter = (value: string, config: {
|
||||
max: number;
|
||||
}) => string;
|
||||
export interface CountConfig {
|
||||
max?: number;
|
||||
strategy?: (value: string) => number;
|
||||
show?: boolean | ShowCountFormatter;
|
||||
/** Trigger when content larger than the `max` limitation */
|
||||
exceedFormatter?: ExceedFormatter;
|
||||
}
|
||||
export interface InputProps extends CommonInputProps, Omit<InputHTMLAttributes<HTMLInputElement>, 'size' | 'prefix' | 'type' | 'value'> {
|
||||
value?: ValueType;
|
||||
prefixCls?: string;
|
||||
type?: LiteralUnion<'button' | 'checkbox' | 'color' | 'date' | 'datetime-local' | 'email' | 'file' | 'hidden' | 'image' | 'month' | 'number' | 'password' | 'radio' | 'range' | 'reset' | 'search' | 'submit' | 'tel' | 'text' | 'time' | 'url' | 'week', string>;
|
||||
onPressEnter?: KeyboardEventHandler<HTMLInputElement>;
|
||||
/** It's better to use `count.show` instead */
|
||||
showCount?: boolean | {
|
||||
formatter: ShowCountFormatter;
|
||||
};
|
||||
autoComplete?: string;
|
||||
htmlSize?: number;
|
||||
classNames?: CommonInputProps['classNames'] & {
|
||||
input?: string;
|
||||
count?: string;
|
||||
};
|
||||
styles?: CommonInputProps['styles'] & {
|
||||
input?: CSSProperties;
|
||||
count?: CSSProperties;
|
||||
};
|
||||
count?: CountConfig;
|
||||
onClear?: () => void;
|
||||
}
|
||||
export interface InputRef {
|
||||
focus: (options?: InputFocusOptions) => void;
|
||||
blur: () => void;
|
||||
setSelectionRange: (start: number, end: number, direction?: 'forward' | 'backward' | 'none') => void;
|
||||
select: () => void;
|
||||
input: HTMLInputElement | null;
|
||||
nativeElement: HTMLElement | null;
|
||||
}
|
||||
export interface ChangeEventInfo {
|
||||
source: 'compositionEnd' | 'change';
|
||||
}
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type React from 'react';
|
||||
import type { BaseInputProps, InputProps } from '../interface';
|
||||
export declare function hasAddon(props: BaseInputProps | InputProps): boolean;
|
||||
export declare function hasPrefixSuffix(props: BaseInputProps | InputProps): boolean;
|
||||
export declare function resolveOnChange<E extends HTMLInputElement | HTMLTextAreaElement>(target: E, e: React.ChangeEvent<E> | React.MouseEvent<HTMLElement, MouseEvent> | React.CompositionEvent<HTMLElement>, onChange: undefined | ((event: React.ChangeEvent<E>) => void), targetValue?: string): void;
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
export function hasAddon(props) {
|
||||
return !!(props.addonBefore || props.addonAfter);
|
||||
}
|
||||
export function hasPrefixSuffix(props) {
|
||||
return !!(props.prefix || props.suffix || props.allowClear);
|
||||
}
|
||||
|
||||
// TODO: It's better to use `Proxy` replace the `element.value`. But we still need support IE11.
|
||||
function cloneEvent(event, target, value) {
|
||||
// A bug report filed on WebKit's Bugzilla tracker, dating back to 2009, specifically addresses the issue of cloneNode() not copying files of <input type="file"> elements.
|
||||
// As of the last update, this bug was still marked as "NEW," indicating that it might not have been resolved yet.
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=28123
|
||||
const currentTarget = target.cloneNode(true);
|
||||
|
||||
// click clear icon
|
||||
const newEvent = Object.create(event, {
|
||||
target: {
|
||||
value: currentTarget
|
||||
},
|
||||
currentTarget: {
|
||||
value: currentTarget
|
||||
}
|
||||
});
|
||||
|
||||
// Fill data
|
||||
currentTarget.value = value;
|
||||
|
||||
// Fill selection. Some type like `email` not support selection
|
||||
// https://github.com/ant-design/ant-design/issues/47833
|
||||
if (typeof target.selectionStart === 'number' && typeof target.selectionEnd === 'number') {
|
||||
currentTarget.selectionStart = target.selectionStart;
|
||||
currentTarget.selectionEnd = target.selectionEnd;
|
||||
}
|
||||
currentTarget.setSelectionRange = (...args) => {
|
||||
target.setSelectionRange(...args);
|
||||
};
|
||||
return newEvent;
|
||||
}
|
||||
export function resolveOnChange(target, e, onChange, targetValue) {
|
||||
if (!onChange) {
|
||||
return;
|
||||
}
|
||||
let event = e;
|
||||
if (e.type === 'click') {
|
||||
// Clone a new target for event.
|
||||
// Avoid the following usage, the setQuery method gets the original value.
|
||||
//
|
||||
// const [query, setQuery] = React.useState('');
|
||||
// <Input
|
||||
// allowClear
|
||||
// value={query}
|
||||
// onChange={(e)=> {
|
||||
// setQuery((prevStatus) => e.target.value);
|
||||
// }}
|
||||
// />
|
||||
|
||||
event = cloneEvent(e, target, '');
|
||||
onChange(event);
|
||||
return;
|
||||
}
|
||||
|
||||
// Trigger by composition event, this means we need force change the input value
|
||||
// https://github.com/ant-design/ant-design/issues/45737
|
||||
// https://github.com/ant-design/ant-design/issues/46598
|
||||
if (target.type !== 'file' && targetValue !== undefined) {
|
||||
event = cloneEvent(e, target, targetValue);
|
||||
onChange(event);
|
||||
return;
|
||||
}
|
||||
onChange(event);
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
/** https://github.com/Microsoft/TypeScript/issues/29729 */
|
||||
export type LiteralUnion<T extends U, U> = T | (U & Record<never, never>);
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import React from 'react';
|
||||
import type { BaseInputProps } from './interface';
|
||||
export interface HolderRef {
|
||||
/** Provider holder ref. Will return `null` if not wrap anything */
|
||||
nativeElement: HTMLElement | null;
|
||||
}
|
||||
declare const BaseInput: React.ForwardRefExoticComponent<BaseInputProps & React.RefAttributes<HolderRef>>;
|
||||
export default BaseInput;
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = void 0;
|
||||
var _clsx = require("clsx");
|
||||
var _react = _interopRequireWildcard(require("react"));
|
||||
var _commonUtils = require("./utils/commonUtils");
|
||||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
||||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
||||
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
||||
const BaseInput = /*#__PURE__*/_react.default.forwardRef((props, ref) => {
|
||||
const {
|
||||
inputElement: inputEl,
|
||||
children,
|
||||
prefixCls,
|
||||
prefix,
|
||||
suffix,
|
||||
addonBefore,
|
||||
addonAfter,
|
||||
className,
|
||||
style,
|
||||
disabled,
|
||||
readOnly,
|
||||
focused,
|
||||
triggerFocus,
|
||||
allowClear,
|
||||
value,
|
||||
handleReset,
|
||||
hidden,
|
||||
classes,
|
||||
classNames,
|
||||
dataAttrs,
|
||||
styles,
|
||||
components,
|
||||
onClear
|
||||
} = props;
|
||||
const inputElement = children ?? inputEl;
|
||||
const AffixWrapperComponent = components?.affixWrapper || 'span';
|
||||
const GroupWrapperComponent = components?.groupWrapper || 'span';
|
||||
const WrapperComponent = components?.wrapper || 'span';
|
||||
const GroupAddonComponent = components?.groupAddon || 'span';
|
||||
const containerRef = (0, _react.useRef)(null);
|
||||
const onInputClick = e => {
|
||||
if (containerRef.current?.contains(e.target)) {
|
||||
triggerFocus?.();
|
||||
}
|
||||
};
|
||||
const hasAffix = (0, _commonUtils.hasPrefixSuffix)(props);
|
||||
let element = /*#__PURE__*/(0, _react.cloneElement)(inputElement, {
|
||||
value,
|
||||
className: (0, _clsx.clsx)(inputElement.props?.className, !hasAffix && classNames?.variant) || null
|
||||
});
|
||||
|
||||
// ======================== Ref ======================== //
|
||||
const groupRef = (0, _react.useRef)(null);
|
||||
_react.default.useImperativeHandle(ref, () => ({
|
||||
nativeElement: groupRef.current || containerRef.current
|
||||
}));
|
||||
|
||||
// ================== Prefix & Suffix ================== //
|
||||
if (hasAffix) {
|
||||
// ================== Clear Icon ================== //
|
||||
let clearIcon = null;
|
||||
if (allowClear) {
|
||||
const needClear = !disabled && !readOnly && value;
|
||||
const clearIconCls = `${prefixCls}-clear-icon`;
|
||||
const iconNode = typeof allowClear === 'object' && allowClear?.clearIcon ? allowClear.clearIcon : '✖';
|
||||
clearIcon = /*#__PURE__*/_react.default.createElement("button", {
|
||||
type: "button",
|
||||
tabIndex: -1,
|
||||
onClick: event => {
|
||||
handleReset?.(event);
|
||||
onClear?.();
|
||||
}
|
||||
// Do not trigger onBlur when clear input
|
||||
// https://github.com/ant-design/ant-design/issues/31200
|
||||
,
|
||||
onMouseDown: e => e.preventDefault(),
|
||||
className: (0, _clsx.clsx)(clearIconCls, {
|
||||
[`${clearIconCls}-hidden`]: !needClear,
|
||||
[`${clearIconCls}-has-suffix`]: !!suffix
|
||||
})
|
||||
}, iconNode);
|
||||
}
|
||||
const affixWrapperPrefixCls = `${prefixCls}-affix-wrapper`;
|
||||
const affixWrapperCls = (0, _clsx.clsx)(affixWrapperPrefixCls, {
|
||||
[`${prefixCls}-disabled`]: disabled,
|
||||
[`${affixWrapperPrefixCls}-disabled`]: disabled,
|
||||
// Not used, but keep it
|
||||
[`${affixWrapperPrefixCls}-focused`]: focused,
|
||||
// Not used, but keep it
|
||||
[`${affixWrapperPrefixCls}-readonly`]: readOnly,
|
||||
[`${affixWrapperPrefixCls}-input-with-clear-btn`]: suffix && allowClear && value
|
||||
}, classes?.affixWrapper, classNames?.affixWrapper, classNames?.variant);
|
||||
const suffixNode = (suffix || allowClear) && /*#__PURE__*/_react.default.createElement("span", {
|
||||
className: (0, _clsx.clsx)(`${prefixCls}-suffix`, classNames?.suffix),
|
||||
style: styles?.suffix
|
||||
}, clearIcon, suffix);
|
||||
element = /*#__PURE__*/_react.default.createElement(AffixWrapperComponent, _extends({
|
||||
className: affixWrapperCls,
|
||||
style: styles?.affixWrapper,
|
||||
onClick: onInputClick
|
||||
}, dataAttrs?.affixWrapper, {
|
||||
ref: containerRef
|
||||
}), prefix && /*#__PURE__*/_react.default.createElement("span", {
|
||||
className: (0, _clsx.clsx)(`${prefixCls}-prefix`, classNames?.prefix),
|
||||
style: styles?.prefix
|
||||
}, prefix), element, suffixNode);
|
||||
}
|
||||
|
||||
// ================== Addon ================== //
|
||||
if ((0, _commonUtils.hasAddon)(props)) {
|
||||
const wrapperCls = `${prefixCls}-group`;
|
||||
const addonCls = `${wrapperCls}-addon`;
|
||||
const groupWrapperCls = `${wrapperCls}-wrapper`;
|
||||
const mergedWrapperClassName = (0, _clsx.clsx)(`${prefixCls}-wrapper`, wrapperCls, classes?.wrapper, classNames?.wrapper);
|
||||
const mergedGroupClassName = (0, _clsx.clsx)(groupWrapperCls, {
|
||||
[`${groupWrapperCls}-disabled`]: disabled
|
||||
}, classes?.group, classNames?.groupWrapper);
|
||||
|
||||
// Need another wrapper for changing display:table to display:inline-block
|
||||
// and put style prop in wrapper
|
||||
element = /*#__PURE__*/_react.default.createElement(GroupWrapperComponent, {
|
||||
className: mergedGroupClassName,
|
||||
ref: groupRef
|
||||
}, /*#__PURE__*/_react.default.createElement(WrapperComponent, {
|
||||
className: mergedWrapperClassName
|
||||
}, addonBefore && /*#__PURE__*/_react.default.createElement(GroupAddonComponent, {
|
||||
className: addonCls
|
||||
}, addonBefore), element, addonAfter && /*#__PURE__*/_react.default.createElement(GroupAddonComponent, {
|
||||
className: addonCls
|
||||
}, addonAfter)));
|
||||
}
|
||||
|
||||
// `className` and `style` are always on the root element
|
||||
return /*#__PURE__*/_react.default.cloneElement(element, {
|
||||
className: (0, _clsx.clsx)(element.props?.className, className) || null,
|
||||
style: {
|
||||
...element.props?.style,
|
||||
...style
|
||||
},
|
||||
hidden
|
||||
});
|
||||
});
|
||||
var _default = exports.default = BaseInput;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import React from 'react';
|
||||
import type { InputProps, InputRef } from './interface';
|
||||
declare const Input: React.ForwardRefExoticComponent<InputProps & React.RefAttributes<InputRef>>;
|
||||
export default Input;
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = void 0;
|
||||
var _clsx = require("clsx");
|
||||
var _useControlledState = _interopRequireDefault(require("@rc-component/util/lib/hooks/useControlledState"));
|
||||
var _omit = _interopRequireDefault(require("@rc-component/util/lib/omit"));
|
||||
var _react = _interopRequireWildcard(require("react"));
|
||||
var _BaseInput = _interopRequireDefault(require("./BaseInput"));
|
||||
var _useCount = _interopRequireDefault(require("./hooks/useCount"));
|
||||
var _commonUtils = require("./utils/commonUtils");
|
||||
var _focus = require("@rc-component/util/lib/Dom/focus");
|
||||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
||||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
||||
const Input = /*#__PURE__*/(0, _react.forwardRef)((props, ref) => {
|
||||
const {
|
||||
autoComplete,
|
||||
onChange,
|
||||
onFocus,
|
||||
onBlur,
|
||||
onPressEnter,
|
||||
onKeyDown,
|
||||
onKeyUp,
|
||||
prefixCls = 'rc-input',
|
||||
disabled,
|
||||
htmlSize,
|
||||
className,
|
||||
maxLength,
|
||||
suffix,
|
||||
showCount,
|
||||
count,
|
||||
type = 'text',
|
||||
classes,
|
||||
classNames,
|
||||
styles,
|
||||
onCompositionStart,
|
||||
onCompositionEnd,
|
||||
...rest
|
||||
} = props;
|
||||
const [focused, setFocused] = (0, _react.useState)(false);
|
||||
const compositionRef = (0, _react.useRef)(false);
|
||||
const keyLockRef = (0, _react.useRef)(false);
|
||||
const inputRef = (0, _react.useRef)(null);
|
||||
const holderRef = (0, _react.useRef)(null);
|
||||
const focus = option => {
|
||||
if (inputRef.current) {
|
||||
(0, _focus.triggerFocus)(inputRef.current, option);
|
||||
}
|
||||
};
|
||||
|
||||
// ====================== Value =======================
|
||||
const [value, setValue] = (0, _useControlledState.default)(props.defaultValue, props.value);
|
||||
const formatValue = value === undefined || value === null ? '' : String(value);
|
||||
|
||||
// =================== Select Range ===================
|
||||
const [selection, setSelection] = (0, _react.useState)(null);
|
||||
|
||||
// ====================== Count =======================
|
||||
const countConfig = (0, _useCount.default)(count, showCount);
|
||||
const mergedMax = countConfig.max || maxLength;
|
||||
const valueLength = countConfig.strategy(formatValue);
|
||||
const isOutOfRange = !!mergedMax && valueLength > mergedMax;
|
||||
|
||||
// ======================= Ref ========================
|
||||
(0, _react.useImperativeHandle)(ref, () => ({
|
||||
focus,
|
||||
blur: () => {
|
||||
inputRef.current?.blur();
|
||||
},
|
||||
setSelectionRange: (start, end, direction) => {
|
||||
inputRef.current?.setSelectionRange(start, end, direction);
|
||||
},
|
||||
select: () => {
|
||||
inputRef.current?.select();
|
||||
},
|
||||
input: inputRef.current,
|
||||
nativeElement: holderRef.current?.nativeElement || inputRef.current
|
||||
}));
|
||||
(0, _react.useEffect)(() => {
|
||||
if (keyLockRef.current) {
|
||||
keyLockRef.current = false;
|
||||
}
|
||||
setFocused(prev => prev && disabled ? false : prev);
|
||||
}, [disabled]);
|
||||
const triggerChange = (e, currentValue, info) => {
|
||||
let cutValue = currentValue;
|
||||
if (!compositionRef.current && countConfig.exceedFormatter && countConfig.max && countConfig.strategy(currentValue) > countConfig.max) {
|
||||
cutValue = countConfig.exceedFormatter(currentValue, {
|
||||
max: countConfig.max
|
||||
});
|
||||
if (currentValue !== cutValue) {
|
||||
setSelection([inputRef.current?.selectionStart || 0, inputRef.current?.selectionEnd || 0]);
|
||||
}
|
||||
} else if (info.source === 'compositionEnd') {
|
||||
// Avoid triggering twice
|
||||
// https://github.com/ant-design/ant-design/issues/46587
|
||||
return;
|
||||
}
|
||||
setValue(cutValue);
|
||||
if (inputRef.current) {
|
||||
(0, _commonUtils.resolveOnChange)(inputRef.current, e, onChange, cutValue);
|
||||
}
|
||||
};
|
||||
(0, _react.useEffect)(() => {
|
||||
if (selection) {
|
||||
inputRef.current?.setSelectionRange(...selection);
|
||||
}
|
||||
}, [selection]);
|
||||
const onInternalChange = e => {
|
||||
triggerChange(e, e.target.value, {
|
||||
source: 'change'
|
||||
});
|
||||
};
|
||||
const onInternalCompositionEnd = e => {
|
||||
compositionRef.current = false;
|
||||
triggerChange(e, e.currentTarget.value, {
|
||||
source: 'compositionEnd'
|
||||
});
|
||||
onCompositionEnd?.(e);
|
||||
};
|
||||
const handleKeyDown = e => {
|
||||
if (onPressEnter && e.key === 'Enter' && !keyLockRef.current && !e.nativeEvent.isComposing) {
|
||||
keyLockRef.current = true;
|
||||
onPressEnter(e);
|
||||
}
|
||||
onKeyDown?.(e);
|
||||
};
|
||||
const handleKeyUp = e => {
|
||||
if (e.key === 'Enter') {
|
||||
keyLockRef.current = false;
|
||||
}
|
||||
onKeyUp?.(e);
|
||||
};
|
||||
const handleFocus = e => {
|
||||
setFocused(true);
|
||||
onFocus?.(e);
|
||||
};
|
||||
const handleBlur = e => {
|
||||
if (keyLockRef.current) {
|
||||
keyLockRef.current = false;
|
||||
}
|
||||
setFocused(false);
|
||||
onBlur?.(e);
|
||||
};
|
||||
const handleReset = e => {
|
||||
setValue('');
|
||||
focus();
|
||||
if (inputRef.current) {
|
||||
(0, _commonUtils.resolveOnChange)(inputRef.current, e, onChange);
|
||||
}
|
||||
};
|
||||
|
||||
// ====================== Input =======================
|
||||
const outOfRangeCls = isOutOfRange && `${prefixCls}-out-of-range`;
|
||||
const getInputElement = () => {
|
||||
// Fix https://fb.me/react-unknown-prop
|
||||
const otherProps = (0, _omit.default)(props, ['prefixCls', 'onPressEnter', 'addonBefore', 'addonAfter', 'prefix', 'suffix', 'allowClear',
|
||||
// Input elements must be either controlled or uncontrolled,
|
||||
// specify either the value prop, or the defaultValue prop, but not both.
|
||||
'defaultValue', 'showCount', 'count', 'classes', 'htmlSize', 'styles', 'classNames', 'onClear']);
|
||||
return /*#__PURE__*/_react.default.createElement("input", _extends({
|
||||
autoComplete: autoComplete
|
||||
}, otherProps, {
|
||||
onChange: onInternalChange,
|
||||
onFocus: handleFocus,
|
||||
onBlur: handleBlur,
|
||||
onKeyDown: handleKeyDown,
|
||||
onKeyUp: handleKeyUp,
|
||||
className: (0, _clsx.clsx)(prefixCls, {
|
||||
[`${prefixCls}-disabled`]: disabled
|
||||
}, classNames?.input),
|
||||
style: styles?.input,
|
||||
ref: inputRef,
|
||||
size: htmlSize,
|
||||
type: type,
|
||||
onCompositionStart: e => {
|
||||
compositionRef.current = true;
|
||||
onCompositionStart?.(e);
|
||||
},
|
||||
onCompositionEnd: onInternalCompositionEnd
|
||||
}));
|
||||
};
|
||||
const getSuffix = () => {
|
||||
// Max length value
|
||||
const hasMaxLength = Number(mergedMax) > 0;
|
||||
if (suffix || countConfig.show) {
|
||||
const dataCount = countConfig.showFormatter ? countConfig.showFormatter({
|
||||
value: formatValue,
|
||||
count: valueLength,
|
||||
maxLength: mergedMax
|
||||
}) : `${valueLength}${hasMaxLength ? ` / ${mergedMax}` : ''}`;
|
||||
return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, countConfig.show && /*#__PURE__*/_react.default.createElement("span", {
|
||||
className: (0, _clsx.clsx)(`${prefixCls}-show-count-suffix`, {
|
||||
[`${prefixCls}-show-count-has-suffix`]: !!suffix
|
||||
}, classNames?.count),
|
||||
style: {
|
||||
...styles?.count
|
||||
}
|
||||
}, dataCount), suffix);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// ====================== Render ======================
|
||||
return /*#__PURE__*/_react.default.createElement(_BaseInput.default, _extends({}, rest, {
|
||||
prefixCls: prefixCls,
|
||||
className: (0, _clsx.clsx)(className, outOfRangeCls),
|
||||
handleReset: handleReset,
|
||||
value: formatValue,
|
||||
focused: focused,
|
||||
triggerFocus: focus,
|
||||
suffix: getSuffix(),
|
||||
disabled: disabled,
|
||||
classes: classes,
|
||||
classNames: classNames,
|
||||
styles: styles,
|
||||
ref: holderRef
|
||||
}), getInputElement());
|
||||
});
|
||||
var _default = exports.default = Input;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { InputProps } from '..';
|
||||
import type { CountConfig, ShowCountFormatter } from '../interface';
|
||||
type ForcedCountConfig = Omit<CountConfig, 'show'> & Pick<Required<CountConfig>, 'strategy'> & {
|
||||
show: boolean;
|
||||
showFormatter?: ShowCountFormatter;
|
||||
};
|
||||
/**
|
||||
* Cut `value` by the `count.max` prop.
|
||||
*/
|
||||
export declare function inCountRange(value: string, countConfig: ForcedCountConfig): boolean;
|
||||
export default function useCount(count?: CountConfig, showCount?: InputProps['showCount']): ForcedCountConfig;
|
||||
export {};
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = useCount;
|
||||
exports.inCountRange = inCountRange;
|
||||
var React = _interopRequireWildcard(require("react"));
|
||||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
||||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
||||
/**
|
||||
* Cut `value` by the `count.max` prop.
|
||||
*/
|
||||
function inCountRange(value, countConfig) {
|
||||
if (!countConfig.max) {
|
||||
return true;
|
||||
}
|
||||
const count = countConfig.strategy(value);
|
||||
return count <= countConfig.max;
|
||||
}
|
||||
function useCount(count, showCount) {
|
||||
return React.useMemo(() => {
|
||||
let mergedConfig = {};
|
||||
if (showCount) {
|
||||
mergedConfig.show = typeof showCount === 'object' && showCount.formatter ? showCount.formatter : !!showCount;
|
||||
}
|
||||
mergedConfig = {
|
||||
...mergedConfig,
|
||||
...count
|
||||
};
|
||||
const {
|
||||
show,
|
||||
...rest
|
||||
} = mergedConfig;
|
||||
return {
|
||||
...rest,
|
||||
show: !!show,
|
||||
showFormatter: typeof show === 'function' ? show : undefined,
|
||||
strategy: rest.strategy || (value => value.length)
|
||||
};
|
||||
}, [count, showCount]);
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import BaseInput from './BaseInput';
|
||||
import Input from './Input';
|
||||
export { BaseInput };
|
||||
export type { InputProps, InputRef } from './interface';
|
||||
export default Input;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "BaseInput", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _BaseInput.default;
|
||||
}
|
||||
});
|
||||
exports.default = void 0;
|
||||
var _BaseInput = _interopRequireDefault(require("./BaseInput"));
|
||||
var _Input = _interopRequireDefault(require("./Input"));
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
var _default = exports.default = _Input.default;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import type { CSSProperties, InputHTMLAttributes, KeyboardEventHandler, MouseEventHandler, ReactElement, ReactNode } from 'react';
|
||||
import type { LiteralUnion } from './utils/types';
|
||||
import type { InputFocusOptions } from '@rc-component/util/lib/Dom/focus';
|
||||
export interface CommonInputProps {
|
||||
prefix?: ReactNode;
|
||||
suffix?: ReactNode;
|
||||
addonBefore?: ReactNode;
|
||||
addonAfter?: ReactNode;
|
||||
/** @deprecated Use `classNames` instead */
|
||||
classes?: {
|
||||
affixWrapper?: string;
|
||||
group?: string;
|
||||
wrapper?: string;
|
||||
};
|
||||
classNames?: {
|
||||
affixWrapper?: string;
|
||||
prefix?: string;
|
||||
suffix?: string;
|
||||
groupWrapper?: string;
|
||||
wrapper?: string;
|
||||
variant?: string;
|
||||
};
|
||||
styles?: {
|
||||
affixWrapper?: CSSProperties;
|
||||
prefix?: CSSProperties;
|
||||
suffix?: CSSProperties;
|
||||
};
|
||||
allowClear?: boolean | {
|
||||
clearIcon?: ReactNode;
|
||||
};
|
||||
}
|
||||
type DataAttr = Record<`data-${string}`, string>;
|
||||
export type ValueType = InputHTMLAttributes<HTMLInputElement>['value'] | bigint;
|
||||
export interface BaseInputProps extends CommonInputProps {
|
||||
value?: ValueType;
|
||||
/** @deprecated Use `children` instead */
|
||||
inputElement?: ReactElement;
|
||||
prefixCls?: string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
disabled?: boolean;
|
||||
focused?: boolean;
|
||||
triggerFocus?: () => void;
|
||||
readOnly?: boolean;
|
||||
handleReset?: MouseEventHandler;
|
||||
onClear?: () => void;
|
||||
hidden?: boolean;
|
||||
dataAttrs?: {
|
||||
affixWrapper?: DataAttr;
|
||||
};
|
||||
components?: {
|
||||
affixWrapper?: 'span' | 'div';
|
||||
groupWrapper?: 'span' | 'div';
|
||||
wrapper?: 'span' | 'div';
|
||||
groupAddon?: 'span' | 'div';
|
||||
};
|
||||
children: ReactElement;
|
||||
}
|
||||
export type ShowCountFormatter = (args: {
|
||||
value: string;
|
||||
count: number;
|
||||
maxLength?: number;
|
||||
}) => ReactNode;
|
||||
export type ExceedFormatter = (value: string, config: {
|
||||
max: number;
|
||||
}) => string;
|
||||
export interface CountConfig {
|
||||
max?: number;
|
||||
strategy?: (value: string) => number;
|
||||
show?: boolean | ShowCountFormatter;
|
||||
/** Trigger when content larger than the `max` limitation */
|
||||
exceedFormatter?: ExceedFormatter;
|
||||
}
|
||||
export interface InputProps extends CommonInputProps, Omit<InputHTMLAttributes<HTMLInputElement>, 'size' | 'prefix' | 'type' | 'value'> {
|
||||
value?: ValueType;
|
||||
prefixCls?: string;
|
||||
type?: LiteralUnion<'button' | 'checkbox' | 'color' | 'date' | 'datetime-local' | 'email' | 'file' | 'hidden' | 'image' | 'month' | 'number' | 'password' | 'radio' | 'range' | 'reset' | 'search' | 'submit' | 'tel' | 'text' | 'time' | 'url' | 'week', string>;
|
||||
onPressEnter?: KeyboardEventHandler<HTMLInputElement>;
|
||||
/** It's better to use `count.show` instead */
|
||||
showCount?: boolean | {
|
||||
formatter: ShowCountFormatter;
|
||||
};
|
||||
autoComplete?: string;
|
||||
htmlSize?: number;
|
||||
classNames?: CommonInputProps['classNames'] & {
|
||||
input?: string;
|
||||
count?: string;
|
||||
};
|
||||
styles?: CommonInputProps['styles'] & {
|
||||
input?: CSSProperties;
|
||||
count?: CSSProperties;
|
||||
};
|
||||
count?: CountConfig;
|
||||
onClear?: () => void;
|
||||
}
|
||||
export interface InputRef {
|
||||
focus: (options?: InputFocusOptions) => void;
|
||||
blur: () => void;
|
||||
setSelectionRange: (start: number, end: number, direction?: 'forward' | 'backward' | 'none') => void;
|
||||
select: () => void;
|
||||
input: HTMLInputElement | null;
|
||||
nativeElement: HTMLElement | null;
|
||||
}
|
||||
export interface ChangeEventInfo {
|
||||
source: 'compositionEnd' | 'change';
|
||||
}
|
||||
export {};
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type React from 'react';
|
||||
import type { BaseInputProps, InputProps } from '../interface';
|
||||
export declare function hasAddon(props: BaseInputProps | InputProps): boolean;
|
||||
export declare function hasPrefixSuffix(props: BaseInputProps | InputProps): boolean;
|
||||
export declare function resolveOnChange<E extends HTMLInputElement | HTMLTextAreaElement>(target: E, e: React.ChangeEvent<E> | React.MouseEvent<HTMLElement, MouseEvent> | React.CompositionEvent<HTMLElement>, onChange: undefined | ((event: React.ChangeEvent<E>) => void), targetValue?: string): void;
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.hasAddon = hasAddon;
|
||||
exports.hasPrefixSuffix = hasPrefixSuffix;
|
||||
exports.resolveOnChange = resolveOnChange;
|
||||
function hasAddon(props) {
|
||||
return !!(props.addonBefore || props.addonAfter);
|
||||
}
|
||||
function hasPrefixSuffix(props) {
|
||||
return !!(props.prefix || props.suffix || props.allowClear);
|
||||
}
|
||||
|
||||
// TODO: It's better to use `Proxy` replace the `element.value`. But we still need support IE11.
|
||||
function cloneEvent(event, target, value) {
|
||||
// A bug report filed on WebKit's Bugzilla tracker, dating back to 2009, specifically addresses the issue of cloneNode() not copying files of <input type="file"> elements.
|
||||
// As of the last update, this bug was still marked as "NEW," indicating that it might not have been resolved yet.
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=28123
|
||||
const currentTarget = target.cloneNode(true);
|
||||
|
||||
// click clear icon
|
||||
const newEvent = Object.create(event, {
|
||||
target: {
|
||||
value: currentTarget
|
||||
},
|
||||
currentTarget: {
|
||||
value: currentTarget
|
||||
}
|
||||
});
|
||||
|
||||
// Fill data
|
||||
currentTarget.value = value;
|
||||
|
||||
// Fill selection. Some type like `email` not support selection
|
||||
// https://github.com/ant-design/ant-design/issues/47833
|
||||
if (typeof target.selectionStart === 'number' && typeof target.selectionEnd === 'number') {
|
||||
currentTarget.selectionStart = target.selectionStart;
|
||||
currentTarget.selectionEnd = target.selectionEnd;
|
||||
}
|
||||
currentTarget.setSelectionRange = (...args) => {
|
||||
target.setSelectionRange(...args);
|
||||
};
|
||||
return newEvent;
|
||||
}
|
||||
function resolveOnChange(target, e, onChange, targetValue) {
|
||||
if (!onChange) {
|
||||
return;
|
||||
}
|
||||
let event = e;
|
||||
if (e.type === 'click') {
|
||||
// Clone a new target for event.
|
||||
// Avoid the following usage, the setQuery method gets the original value.
|
||||
//
|
||||
// const [query, setQuery] = React.useState('');
|
||||
// <Input
|
||||
// allowClear
|
||||
// value={query}
|
||||
// onChange={(e)=> {
|
||||
// setQuery((prevStatus) => e.target.value);
|
||||
// }}
|
||||
// />
|
||||
|
||||
event = cloneEvent(e, target, '');
|
||||
onChange(event);
|
||||
return;
|
||||
}
|
||||
|
||||
// Trigger by composition event, this means we need force change the input value
|
||||
// https://github.com/ant-design/ant-design/issues/45737
|
||||
// https://github.com/ant-design/ant-design/issues/46598
|
||||
if (target.type !== 'file' && targetValue !== undefined) {
|
||||
event = cloneEvent(e, target, targetValue);
|
||||
onChange(event);
|
||||
return;
|
||||
}
|
||||
onChange(event);
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
/** https://github.com/Microsoft/TypeScript/issues/29729 */
|
||||
export type LiteralUnion<T extends U, U> = T | (U & Record<never, never>);
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
{
|
||||
"name": "@rc-component/input",
|
||||
"version": "1.1.2",
|
||||
"description": "React input component",
|
||||
"keywords": [
|
||||
"react",
|
||||
"react-component",
|
||||
"react-input",
|
||||
"input",
|
||||
"antd",
|
||||
"ant-design"
|
||||
],
|
||||
"main": "./lib/index",
|
||||
"module": "./es/index",
|
||||
"files": [
|
||||
"assets/*.css",
|
||||
"assets/*.less",
|
||||
"es",
|
||||
"lib"
|
||||
],
|
||||
"homepage": "https://github.com/react-component/input",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git@github.com:react-component/input.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "http://github.com/react-component/input/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"start": "dumi dev",
|
||||
"docs:build": "dumi build",
|
||||
"docs:deploy": "gh-pages -d .doc",
|
||||
"compile": "father build && lessc assets/index.less assets/index.css",
|
||||
"gh-pages": "GH_PAGES=1 npm run docs:build && npm run docs:deploy",
|
||||
"prepublishOnly": "npm run compile && rc-np",
|
||||
"postpublish": "npm run gh-pages",
|
||||
"lint": "eslint src/ --ext .ts,.tsx,.jsx,.js,.md",
|
||||
"prettier": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"",
|
||||
"pretty-quick": "pretty-quick",
|
||||
"lint-staged": "lint-staged",
|
||||
"test": "rc-test",
|
||||
"coverage": "rc-test --coverage",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rc-component/util": "^1.4.0",
|
||||
"clsx": "^2.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rc-component/father-plugin": "^2.0.3",
|
||||
"@rc-component/np": "^1.0.3",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.0.1",
|
||||
"@testing-library/user-event": "^14.0.0-beta",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^24.5.2",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.1",
|
||||
"@umijs/fabric": "^4.0.0",
|
||||
"dumi": "^2.1.14",
|
||||
"eslint": "^8.0.0",
|
||||
"father": "^4.3.7",
|
||||
"gh-pages": "^6.2.0",
|
||||
"husky": "^9.1.7",
|
||||
"less": "^4.2.1",
|
||||
"lint-staged": "^16.2.0",
|
||||
"prettier": "^3.4.2",
|
||||
"pretty-quick": "^4.0.0",
|
||||
"rc-test": "^7.0.15",
|
||||
"react": "^18.0.0",
|
||||
"react-dom": "^18.0.0",
|
||||
"typescript": "^5.7.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.0.0",
|
||||
"react-dom": ">=16.0.0"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-commit": "pretty-quick --staged"
|
||||
}
|
||||
},
|
||||
"lint-staged": {
|
||||
"**/*.{js,jsx,tsx,ts,md,json}": [
|
||||
"prettier --write"
|
||||
]
|
||||
},
|
||||
"cnpm": {
|
||||
"mode": "npm"
|
||||
},
|
||||
"tnpm": {
|
||||
"mode": "npm"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user