Skip to content

Commit ce01405

Browse files
nikzandaNicolò ZandarinzombieJ
authored
feat: support allowClear (#751)
* feat: support allowClear * fix: isolate clear button keyboard events * fix: harden allowClear behavior and accessibility * fix: preserve allowClear across internal focus changes * refactor: simplify allowClear config * Revert "refactor: simplify allowClear config" This reverts commit eb10dcb. * refactor: simplify clear visibility * refactor: align clear action with input suffix * chore: organize clear section --------- Co-authored-by: Nicolò Zandarin <nicolo.zandarin@atroos.com> Co-authored-by: 二货机器人 <smith3816@gmail.com>
1 parent 8a45b34 commit ce01405

9 files changed

Lines changed: 511 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ Then open `http://localhost:8000`.
6666

6767
| Property | Type | Default | Description |
6868
| --- | --- | --- | --- |
69+
| allowClear | `boolean \| { clearIcon?: ReactNode; disabled?: boolean; label?: string }` | `false` | Show a clear button, optionally with a custom icon, disabled state, or accessible label. |
6970
| autoFocus | `boolean` | `false` | Focus the input when mounted. |
7071
| changeOnBlur | `boolean` | `true` | Commit value changes on blur. |
7172
| changeOnWheel | `boolean` | `false` | Allow value changes from the mouse wheel. |
@@ -95,6 +96,7 @@ Then open `http://localhost:8000`.
9596
| upHandler | `ReactNode` | - | Custom increment control. |
9697
| value | `T \| null` | - | Controlled value. |
9798
| onChange | `(value: T \| null) => void` | - | Triggered when the committed value changes. |
99+
| onClear | `() => void` | - | Triggered when the clear button is clicked. |
98100
| onInput | `(text: string) => void` | - | Triggered when the raw input text changes. |
99101
| onPressEnter | `React.KeyboardEventHandler<HTMLInputElement>` | - | Triggered when Enter is pressed. |
100102
| onStep | `(value: T, info: { offset: number \| string; type: 'up' \| 'down'; emitter: 'handler' \| 'keyboard' \| 'wheel' }) => void` | - | Triggered when the value changes by step. |

‎README.zh-CN.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ npm start
6666

6767
| 参数 | 类型 | 默认值 | 说明 |
6868
| --- | --- | --- | --- |
69+
| allowClear | `boolean \| { clearIcon?: ReactNode; disabled?: boolean; label?: string }` | `false` | 显示清除按钮,可自定义图标、禁用清除操作或设置无障碍标签。 |
6970
| autoFocus | `boolean` | `false` | 安装后聚焦输入。 |
7071
| changeOnBlur | `boolean` | `true` | 提交模糊值的变化。 |
7172
| changeOnWheel | `boolean` | `false` | 允许通过鼠标滚轮更改值。 |
@@ -95,6 +96,7 @@ npm start
9596
| upHandler | `ReactNode` | - | 自定义增量控制。 |
9697
| value | `T \| null` | - | 受控值。 |
9798
| onChange | `(value: T \| null) => void` | - | 当提交的值改变时触发。 |
99+
| onClear | `() => void` | - | 点击清除按钮时触发。 |
98100
| onInput | `(text: string) => void` | - | 当原始输入文本更改时触发。 |
99101
| onPressEnter | `React.KeyboardEventHandler<HTMLInputElement>` | - | 当按下 Enter 时触发。 |
100102
| onStep | `(value: T, info: { offset: number \| string; type: 'up' \| 'down'; emitter: 'handler' \| 'keyboard' \| 'wheel' }) => void` | - | 当值逐步变化时触发。 |

‎assets/index.less‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,30 @@
7676
-moz-appearance: textfield;
7777
}
7878

79+
&-suffix {
80+
display: flex;
81+
flex: none;
82+
align-items: center;
83+
}
84+
85+
&-clear-icon {
86+
flex: none;
87+
align-self: center;
88+
padding: 0;
89+
line-height: 1;
90+
cursor: pointer;
91+
background: none;
92+
border: 0;
93+
94+
&-hidden {
95+
visibility: hidden;
96+
}
97+
98+
&-has-suffix {
99+
margin-inline-end: 4px;
100+
}
101+
}
102+
79103
&-actions {
80104
width: 20px;
81105
height: 100%;

‎docs/api.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,12 @@ nav:
7676
<td>false</td>
7777
<td>Specifies that an InputNumber should automatically get focus when the page loads</td>
7878
</tr>
79+
<tr>
80+
<td>allowClear</td>
81+
<td>boolean | { clearIcon?: ReactNode; disabled?: boolean; label?: string }</td>
82+
<td>false</td>
83+
<td>Whether to show a clear button, optionally with a custom icon, disabled state, or accessible label</td>
84+
</tr>
7985
<tr>
8086
<td>readOnly</td>
8187
<td>Boolean</td>
@@ -124,6 +130,12 @@ nav:
124130
<td></td>
125131
<td>Called when value of an InputNumber changed</td>
126132
</tr>
133+
<tr>
134+
<td>onClear</td>
135+
<td>Function</td>
136+
<td></td>
137+
<td>Called when the clear button is clicked</td>
138+
</tr>
127139
<tr>
128140
<td>onBlur</td>
129141
<td>Function</td>

‎docs/demo/allow-clear.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import InputNumber from '@rc-component/input-number';
2+
import React from 'react';
3+
import '../../assets/index.less';
4+
5+
export default () => (
6+
<div style={{ display: 'flex', gap: 12, margin: 10 }}>
7+
<InputNumber allowClear defaultValue={100} />
8+
<InputNumber allowClear={{ clearIcon: '⌫', label: 'Clear amount' }} defaultValue={0} />
9+
<InputNumber allowClear={{ disabled: true }} defaultValue={100} />
10+
<InputNumber suffix="RMB" allowClear defaultValue={100} />
11+
</div>
12+
);

‎docs/example.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ nav:
1313

1414
<code src="./demo/prefix-suffix.tsx"></code>
1515

16+
## allow-clear
17+
18+
<code src="./demo/allow-clear.tsx"></code>
19+
1620
## combination-key-format
1721

1822
<code src="./demo/combination-key-format.tsx"></code>

‎src/InputNumber.tsx‎

Lines changed: 85 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,10 @@ const getWheelDeltaY = (event: WheelEvent) => {
7070
}
7171
};
7272

73-
type SemanticName = 'root' | 'actions' | 'input' | 'action' | 'prefix' | 'suffix';
73+
type SemanticName = 'root' | 'actions' | 'input' | 'action' | 'prefix' | 'suffix' | 'clear';
7474
export interface InputNumberProps<T extends ValueType = ValueType>
75-
extends Omit<
75+
extends
76+
Omit<
7677
React.InputHTMLAttributes<HTMLInputElement>,
7778
| 'value'
7879
| 'defaultValue'
@@ -118,6 +119,13 @@ export interface InputNumberProps<T extends ValueType = ValueType>
118119
controls?: boolean;
119120
prefix?: React.ReactNode;
120121
suffix?: React.ReactNode;
122+
allowClear?:
123+
| boolean
124+
| {
125+
clearIcon?: React.ReactNode;
126+
disabled?: boolean;
127+
label?: string;
128+
};
121129
classNames?: Partial<Record<SemanticName, string>>;
122130
styles?: Partial<Record<SemanticName, React.CSSProperties>>;
123131

@@ -138,6 +146,7 @@ export interface InputNumberProps<T extends ValueType = ValueType>
138146

139147
onInput?: (text: string) => void;
140148
onChange?: (value: T | null) => void;
149+
onClear?: () => void;
141150
onPressEnter?: React.KeyboardEventHandler<HTMLInputElement>;
142151

143152
onStep?: (
@@ -175,6 +184,7 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
175184

176185
prefix,
177186
suffix,
187+
allowClear,
178188
stringMode,
179189

180190
parser,
@@ -183,6 +193,7 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
183193
decimalSeparator,
184194

185195
onChange,
196+
onClear,
186197
onInput,
187198
onPressEnter,
188199
onStep,
@@ -286,6 +297,7 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
286297

287298
// >>> Formatter
288299
const inputValueRef = React.useRef<string | number>('');
300+
const inputValueUpdateRef = React.useRef(0);
289301
const mergedFormatter = React.useCallback(
290302
(number: string, userTyping: boolean) => {
291303
if (formatter) {
@@ -446,6 +458,8 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
446458

447459
// >>> Collect input value
448460
const collectInputValue = (inputStr: string) => {
461+
const inputValueUpdateId = (inputValueUpdateRef.current += 1);
462+
449463
recordCursor();
450464

451465
// Update inputValue in case input can not parse as number
@@ -468,6 +482,10 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
468482
// optimize for chinese input experience
469483
// https://github.com/ant-design/ant-design/issues/8196
470484
onNextPromise(() => {
485+
if (inputValueUpdateId !== inputValueUpdateRef.current) {
486+
return;
487+
}
488+
471489
let nextInputStr = inputStr;
472490
if (!parser) {
473491
nextInputStr = inputStr.replace(/。/g, '.');
@@ -634,7 +652,12 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
634652
}, [changeOnWheel, focus, onInternalWheel]);
635653

636654
// >>> Focus & Blur
637-
const onBlur = () => {
655+
const onBlur: React.FocusEventHandler<HTMLDivElement> = (event) => {
656+
// Moving focus between internal controls does not blur InputNumber.
657+
if (event.relatedTarget instanceof Node && rootRef.current?.contains(event.relatedTarget)) {
658+
return;
659+
}
660+
638661
if (changeOnBlur) {
639662
flushInputValue(false);
640663
}
@@ -707,6 +730,63 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
707730
</StepHandler>
708731
);
709732

733+
// >>> Clear
734+
const clearConfig =
735+
allowClear && typeof allowClear === 'object' ? allowClear : { disabled: allowClear !== true };
736+
const showClear =
737+
!disabled && !readOnly && clearConfig.disabled !== true && String(inputValue).length > 0;
738+
const hasSuffix = isReactRenderable(suffix);
739+
const clearIconCls = `${prefixCls}-clear-icon`;
740+
741+
const onClearKeyDown: React.KeyboardEventHandler<HTMLButtonElement> = (event) => {
742+
const isStepKey = ['Up', 'ArrowUp', 'Down', 'ArrowDown'].includes(event.key);
743+
if (event.key === 'Enter' || (keyboard !== false && isStepKey)) {
744+
event.stopPropagation();
745+
}
746+
};
747+
748+
const onClearClick = () => {
749+
userTypingRef.current = false;
750+
inputValueRef.current = '';
751+
inputValueUpdateRef.current += 1;
752+
753+
const emptyValue = getMiniDecimal(null);
754+
755+
// `triggerValueUpdate` only refreshes the display when the decimal value changes.
756+
// Clear raw input such as `-`, or restore the source value in controlled mode.
757+
if (value !== undefined) {
758+
setInputValue(decimalValue, false);
759+
} else if (decimalValue.isEmpty()) {
760+
setInputValue(emptyValue, false);
761+
}
762+
763+
inputRef.current?.focus();
764+
triggerValueUpdate(emptyValue, false);
765+
onClear?.();
766+
};
767+
768+
const clearNode = allowClear && (
769+
<button
770+
type="button"
771+
aria-label={clearConfig.label ?? 'Clear'}
772+
disabled={!showClear}
773+
className={clsx(
774+
clearIconCls,
775+
{
776+
[`${clearIconCls}-hidden`]: !showClear,
777+
[`${clearIconCls}-has-suffix`]: hasSuffix,
778+
},
779+
classNames?.clear,
780+
)}
781+
style={styles?.clear}
782+
onMouseDown={(event) => event.preventDefault()}
783+
onKeyDown={onClearKeyDown}
784+
onClick={onClearClick}
785+
>
786+
{clearConfig.clearIcon ?? '✖'}
787+
</button>
788+
);
789+
710790
// >>>>>> Render
711791
return (
712792
<div
@@ -761,8 +841,9 @@ const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, r
761841
{...restProps}
762842
/>
763843

764-
{isReactRenderable(suffix) && (
844+
{(allowClear || hasSuffix) && (
765845
<div className={clsx(`${prefixCls}-suffix`, classNames?.suffix)} style={styles?.suffix}>
846+
{clearNode}
766847
{suffix}
767848
</div>
768849
)}

0 commit comments

Comments
 (0)