| 1 |
import React, { useState } from "react"; |
| 2 |
import PropTypes from "prop-types"; |
| 3 |
import { Button } from "react-bootstrap"; |
| 4 |
import "./group-select.css"; |
| 5 |
|
| 6 |
const GroupSelect = (props) => { |
| 7 |
var { onChange, validateUser, users } = props; |
| 8 |
|
| 9 |
var [selected, setSelected] = useState(users); |
| 10 |
var [username, setUsername] = useState(""); |
| 11 |
var [error, setError] = useState(null); |
| 12 |
|
| 13 |
if (!users) return null; |
| 14 |
|
| 15 |
return ( |
| 16 |
<> |
| 17 |
{error != null ? ( |
| 18 |
<div className="alert alert-danger">{error}</div> |
| 19 |
) : ( |
| 20 |
<></> |
| 21 |
)} |
| 22 |
<div className="input-group"> |
| 23 |
<input |
| 24 |
id="username-input" |
| 25 |
data-testid="username-input" |
| 26 |
type="text" |
| 27 |
className="form-control" |
| 28 |
placeholder="Add by username" |
| 29 |
value={username} |
| 30 |
onChange={(e) => { |
| 31 |
setUsername(e.target.value); |
| 32 |
}} |
| 33 |
/> |
| 34 |
<Button |
| 35 |
id="validate-user" |
| 36 |
data-testid="validate-user" |
| 37 |
onClick={() => { |
| 38 |
validateUser(username).then((exists) => { |
| 39 |
if (exists && !selected.includes(username)) { |
| 40 |
let updated_selection = selected.concat([username]); |
| 41 |
onChange(updated_selection, users); |
| 42 |
setUsername(""); |
| 43 |
setSelected(updated_selection); |
| 44 |
if (error != null) setError(null); |
| 45 |
} else if (!exists) { |
| 46 |
setError(`"${username}" is not a valid JupyterHub user.`); |
| 47 |
} |
| 48 |
}); |
| 49 |
}} |
| 50 |
> |
| 51 |
Add user |
| 52 |
</Button> |
| 53 |
</div> |
| 54 |
<div className="users-container"> |
| 55 |
<hr></hr> |
| 56 |
<div> |
| 57 |
{selected.map((e, i) => ( |
| 58 |
<div |
| 59 |
key={"selected" + i} |
| 60 |
className="item selected" |
| 61 |
onClick={() => { |
| 62 |
let updated_selection = selected |
| 63 |
.slice(0, i) |
| 64 |
.concat(selected.slice(i + 1)); |
| 65 |
onChange(updated_selection, users); |
| 66 |
setSelected(updated_selection); |
| 67 |
}} |
| 68 |
> |
| 69 |
{e} |
| 70 |
</div> |
| 71 |
))} |
| 72 |
{users.map((e, i) => |
| 73 |
selected.includes(e) ? undefined : ( |
| 74 |
<div |
| 75 |
key={"unselected" + i} |
| 76 |
className="item unselected" |
| 77 |
onClick={() => { |
| 78 |
let updated_selection = selected.concat([e]); |
| 79 |
onChange(updated_selection, users); |
| 80 |
setSelected(updated_selection); |
| 81 |
}} |
| 82 |
> |
| 83 |
{e} |
| 84 |
</div> |
| 85 |
), |
| 86 |
)} |
| 87 |
</div> |
| 88 |
</div> |
| 89 |
</> |
| 90 |
); |
| 91 |
}; |
| 92 |
|
| 93 |
GroupSelect.propTypes = { |
| 94 |
onChange: PropTypes.func, |
| 95 |
validateUser: PropTypes.func, |
| 96 |
users: PropTypes.array, |
| 97 |
}; |
| 98 |
|
| 99 |
export default GroupSelect; |