/
Attributes.js
81 lines (63 loc) · 2.31 KB
/
Attributes.js
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
import React, { useMemo, useState } from "react";
import PropTypes from "prop-types";
import Form from "react-bootstrap/Form";
import AttributeRow from "./AttributeRow";
import { attributesShape } from "lib/shapes";
function attrDiff(a, b) {
const bNames = new Set(b.map(item => item.name));
return a.filter(item => !bNames.has(item.name));
}
function Traits(props) {
const { attributes } = props;
const [inputAttributes, setInputAttributes] = useState([]);
const remainingAttributes = useMemo(() => attrDiff(attributes, inputAttributes), [attributes, inputAttributes]);
const remainingAttributeOptions = remainingAttributes.map(attr => (
<option key={attr.name} value={attr.name}>{attr.name}</option>
));
function addAttribute({name, value}) {
setInputAttributes([...inputAttributes, {name, value}]);
}
function setAttributeName(ii, event) {
const replacement = {name: event.target.value, value: inputAttributes[ii].value};
replaceAttribute(ii, replacement);
}
function setAttributeValue(ii, event) {
const replacement = {name: inputAttributes[ii].name, value: event.target.value};
replaceAttribute(ii, replacement);
}
function replaceAttribute(ii, replacement) {
const newAttributes = inputAttributes.slice();
newAttributes.splice(ii, 1, replacement);
setInputAttributes(newAttributes);
}
return (
<Form.Group controlId="factories.Traits">
<Form.Label>Pickles or onions?</Form.Label>
{inputAttributes.map((attr, ii) => (
<AttributeRow
key={ii}
attribute={attr}
disabled={props.disabled}
onChangeName={event => setAttributeName(ii, event)}
onChangeValue={event => setAttributeValue(ii, event)}
>
{remainingAttributeOptions}
</AttributeRow>
))}
<AttributeRow
key={inputAttributes.length + 1}
attribute={{name: "", value: ""}}
disabled={props.disabled}
onChangeName={event => addAttribute({name: event.target.value, value: ""})}
onChangeValue={event => addAttribute({name: "", value: event.target.value})}
>
{remainingAttributeOptions}
</AttributeRow>
</Form.Group>
);
}
Traits.propTypes = {
disabled: PropTypes.bool,
attributes: PropTypes.arrayOf(attributesShape).isRequired,
};
export default Traits;