forked from webpack-contrib/webpack-bundle-analyzer
/
CheckboxList.jsx
99 lines (82 loc) · 2.64 KB
/
CheckboxList.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
/** @jsx h */
import {h} from 'preact';
import CheckboxListItem from './CheckboxListItem';
import s from './CheckboxList.css';
import PureComponent from '../lib/PureComponent';
const ALL_ITEM = Symbol('ALL_ITEM');
export default class CheckboxList extends PureComponent {
static ALL_ITEM = ALL_ITEM;
constructor(props) {
super(props);
this.state = {
checkedItems: props.checkedItems || props.items
};
}
componentWillReceiveProps(newProps) {
if (newProps.items !== this.props.items) {
if (this.isAllChecked()) {
// Preserving `all checked` state
this.setState({checkedItems: newProps.items});
this.informAboutChange(newProps.items);
} else if (this.state.checkedItems.length) {
// Checking only items that are in the new `items` array
const checkedItems = newProps.items.filter(item =>
this.state.checkedItems.find(checkedItem => checkedItem.label === item.label)
);
this.setState({checkedItems});
this.informAboutChange(checkedItems);
}
} else if (newProps.checkedItems !== this.props.checkedItems) {
this.setState({checkedItems: newProps.checkedItems});
}
}
render() {
const {label, items, renderLabel} = this.props;
return (
<div className={s.container}>
<div className={s.label}>
{label}:
</div>
<div>
<CheckboxListItem item={ALL_ITEM}
checked={this.isAllChecked()}
onChange={this.handleToggleAllCheck}>
{renderLabel}
</CheckboxListItem>
{items.map(item =>
<CheckboxListItem key={item.label}
item={item}
checked={this.isItemChecked(item)}
onChange={this.handleItemCheck}>
{renderLabel}
</CheckboxListItem>
)}
</div>
</div>
);
}
handleToggleAllCheck = () => {
const checkedItems = this.isAllChecked() ? [] : this.props.items;
this.setState({checkedItems});
this.informAboutChange(checkedItems);
};
handleItemCheck = item => {
let checkedItems;
if (this.isItemChecked(item)) {
checkedItems = this.state.checkedItems.filter(checkedItem => checkedItem !== item);
} else {
checkedItems = [...this.state.checkedItems, item];
}
this.setState({checkedItems});
this.informAboutChange(checkedItems);
};
isItemChecked(item) {
return this.state.checkedItems.includes(item);
}
isAllChecked() {
return (this.props.items.length === this.state.checkedItems.length);
}
informAboutChange(checkedItems) {
setTimeout(() => this.props.onChange(checkedItems));
}
}