Added custom pasteSelect to handle paste events (#3562)

This commit is contained in:
Jeff Niu 2017-10-03 15:58:18 -07:00 committed by Maxime Beauchemin
parent fdbc936dc9
commit 076f9cd095

View File

@ -37,6 +37,55 @@ const defaultProps = {
valueKey: 'value',
};
// Handle `onPaste` so that users may paste in
// options as comma-delimited, slightly modified from
// https://github.com/JedWatson/react-select/issues/1672
function pasteSelect(props) {
let pasteInput;
return (
<Select
{...props}
ref={(ref) => {
// Creatable requires a reference to its Select child
if (props.ref) {
props.ref(ref);
}
pasteInput = ref;
}}
inputProps={{
onPaste: (evt) => {
if (!props.multi) {
return;
}
evt.preventDefault();
// pull text from the clipboard and split by comma
const clipboard = evt.clipboardData.getData('Text');
if (!clipboard) {
return;
}
const values = clipboard.split(/[,]+/).map(v => v.trim());
const options = values
.filter(value =>
// Creatable validates options
props.isValidNewOption ? props.isValidNewOption({ label: value }) : !!value,
)
.map(value => ({
[props.labelKey]: value,
[props.valueKey]: value,
}));
if (options.length) {
pasteInput.selectValue(options);
}
},
}}
/>
);
}
pasteSelect.propTypes = {
multi: PropTypes.bool,
ref: PropTypes.func,
};
export default class SelectControl extends React.PureComponent {
constructor(props) {
super(props);
@ -106,6 +155,7 @@ export default class SelectControl extends React.PureComponent {
placeholder: t('Select %s', this.state.options.length),
options: this.state.options,
value: this.props.value,
labelKey: 'label',
valueKey: this.props.valueKey,
autosize: false,
clearable: this.props.clearable,
@ -115,8 +165,13 @@ export default class SelectControl extends React.PureComponent {
valueRenderer: this.props.valueRenderer,
};
// Tab, comma or Enter will trigger a new option created for FreeFormSelect
const selectWrap = this.props.freeForm ?
(<Creatable {...selectProps} />) : (<Select {...selectProps} />);
const selectWrap = this.props.freeForm ? (
<Creatable {...selectProps}>
{pasteSelect}
</Creatable>
) : (
pasteSelect(selectProps)
);
return (
<div>
{this.props.showHeader &&