forked from indico/indico
/
EmailListField.jsx
101 lines (87 loc) · 2.74 KB
/
EmailListField.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// This file is part of Indico.
// Copyright (C) 2002 - 2023 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
import _ from 'lodash';
import PropTypes from 'prop-types';
import React, {useState} from 'react';
import {Dropdown} from 'semantic-ui-react';
import {Translate} from 'indico/react/i18n';
import {FinalField} from '../forms';
const isValid = value => /^\S+@\S+\.\S+$/.test(value);
/**
* A field that lets the user enter email addresses
*/
const EmailListField = props => {
const {value, disabled, onChange, onFocus, onBlur} = props;
const [searchQuery, setSearchQuery] = useState('');
const options = value.filter(isValid).map(x => ({text: x, value: x}));
const setValue = newValue => {
newValue = _.uniq(newValue.filter(isValid));
onChange(newValue);
onFocus();
onBlur();
};
const handleChange = (e, {value: newValue}) => {
if (newValue.length && newValue[newValue.length - 1] === searchQuery) {
setSearchQuery('');
}
setValue(newValue);
};
const handleSearchChange = (e, {searchQuery: newSearchQuery}) => {
if (/[,;]/.test(newSearchQuery)) {
const addresses = newSearchQuery.replace(/\s/g, '').split(/[,;]+/);
setValue([...value, ...addresses.filter(isValid)]);
setSearchQuery(addresses.filter(a => a && !isValid(a)).join(', '));
} else {
setSearchQuery(newSearchQuery);
}
};
const handleBlur = () => {
if (isValid(searchQuery)) {
setValue([...value, searchQuery]);
setSearchQuery('');
}
};
return (
<Dropdown
options={options}
value={value}
searchQuery={searchQuery}
disabled={disabled}
searchInput={{onFocus, onBlur, type: 'email'}}
search
selection
multiple
allowAdditions
fluid
open={isValid(searchQuery)}
placeholder={Translate.string('Please enter an email address')}
additionLabel={Translate.string('Add email') + ' '} // eslint-disable-line prefer-template
onChange={handleChange}
onSearchChange={handleSearchChange}
onBlur={handleBlur}
selectedLabel={null}
icon=""
/>
);
};
EmailListField.propTypes = {
value: PropTypes.arrayOf(PropTypes.string).isRequired,
disabled: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
onBlur: PropTypes.func.isRequired,
};
export default React.memo(EmailListField);
/**
* Like `FinalField` but for a `EmailListField`.
*/
export function FinalEmailList({name, ...rest}) {
return <FinalField name={name} component={EmailListField} isEqual={_.isEqual} {...rest} />;
}
FinalEmailList.propTypes = {
name: PropTypes.string.isRequired,
};