ant-design/components/input/Password.tsx

106 lines
2.3 KiB
TypeScript
Raw Normal View History

2018-11-29 10:03:16 +08:00
import * as React from 'react';
import classNames from 'classnames';
2019-08-05 18:38:10 +08:00
import omit from 'omit.js';
2018-11-29 10:03:16 +08:00
import Input, { InputProps } from './Input';
import Icon from '../icon';
export interface PasswordProps extends InputProps {
readonly inputPrefixCls?: string;
readonly action?: string;
2018-12-07 20:02:01 +08:00
visibilityToggle?: boolean;
2018-11-29 10:03:16 +08:00
}
export interface PasswordState {
2018-12-07 20:02:01 +08:00
visible: boolean;
2018-11-29 10:03:16 +08:00
}
const ActionMap: Record<string, string> = {
click: 'onClick',
hover: 'onMouseOver',
2018-12-07 20:02:01 +08:00
};
2018-11-29 10:03:16 +08:00
2018-12-02 18:11:19 +08:00
export default class Password extends React.Component<PasswordProps, PasswordState> {
input: HTMLInputElement;
2018-11-29 10:03:16 +08:00
static defaultProps = {
inputPrefixCls: 'ant-input',
prefixCls: 'ant-input-password',
action: 'click',
visibilityToggle: true,
2018-11-29 10:03:16 +08:00
};
state: PasswordState = {
visible: false,
};
onChange = () => {
const { disabled } = this.props;
if (disabled) {
return;
}
2019-08-05 18:38:10 +08:00
this.setState(({ visible }) => ({ visible: !visible }));
2018-12-07 20:02:01 +08:00
};
2018-11-29 10:03:16 +08:00
getIcon() {
const { prefixCls, action } = this.props;
const iconTrigger = ActionMap[action!] || '';
const iconProps = {
[iconTrigger]: this.onChange,
className: `${prefixCls}-icon`,
type: this.state.visible ? 'eye' : 'eye-invisible',
key: 'passwordIcon',
onMouseDown: (e: MouseEvent) => {
// Prevent focused state lost
// https://github.com/ant-design/ant-design/issues/15173
e.preventDefault();
},
};
return <Icon {...iconProps} />;
2018-11-29 10:03:16 +08:00
}
saveInput = (instance: Input) => {
if (instance && instance.input) {
this.input = instance.input;
}
};
focus() {
this.input.focus();
}
blur() {
this.input.blur();
}
select() {
this.input.select();
}
2018-11-29 10:03:16 +08:00
render() {
const {
className,
prefixCls,
inputPrefixCls,
size,
visibilityToggle,
...restProps
} = this.props;
const suffixIcon = visibilityToggle && this.getIcon();
2018-11-29 10:03:16 +08:00
const inputClassName = classNames(prefixCls, className, {
[`${prefixCls}-${size}`]: !!size,
});
return (
<Input
2019-08-05 18:38:10 +08:00
{...omit(restProps, ['suffix'])}
2018-11-29 10:03:16 +08:00
type={this.state.visible ? 'text' : 'password'}
size={size}
className={inputClassName}
prefixCls={inputPrefixCls}
suffix={suffixIcon}
ref={this.saveInput}
2018-11-29 10:03:16 +08:00
/>
);
}
}