-
Notifications
You must be signed in to change notification settings - Fork 37
/
ExpandAllButton.js
68 lines (60 loc) · 1.95 KB
/
ExpandAllButton.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
import React from 'react';
import { flushSync } from 'react-dom';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import isEqual from 'lodash/isEqual';
import memoizeOne from 'memoize-one';
import expandAll from './expandCollapseAll';
import Button from '../Button';
import { withAccordionStatus } from './AccordionStatusContext';
// returns true if more keys in status are set to false than true;
const majorityCollapsed = memoizeOne((status) => {
const marjority = Object.keys(status).reduce(
(accum, id) => (status[id] ? accum + 1 : accum - 1),
0
);
return marjority < 0;
}, isEqual);
const propTypes = {
accordionStatus: PropTypes.object,
collapseLabel: PropTypes.node,
expandLabel: PropTypes.node,
id: PropTypes.string,
onToggle: PropTypes.func,
setStatus: PropTypes.func,
};
function handleClick({ accordionStatus, func, setStatus, onToggle }) {
const newState = expandAll(accordionStatus, func);
if (setStatus) {
// we want the button change to be snappy, so we go ahead and push
// the state update to immediate mode vs React v18's batching.
flushSync(() => setStatus(newState));
}
if (onToggle) onToggle(newState);
}
const ExpandAllButton = ({
accordionStatus,
collapseLabel: collapseLabelProp,
expandLabel: expandLabelProp,
id,
onToggle,
setStatus,
}) => {
const expandLabel = expandLabelProp ||
<FormattedMessage id="stripes-components.expandAll" />;
const collapseLabel = collapseLabelProp ||
<FormattedMessage id="stripes-components.collapseAll" />;
const func = majorityCollapsed(accordionStatus);
return (
<Button
buttonStyle="link bottomMargin0"
id={id}
onClick={() => { handleClick({ accordionStatus, func, setStatus, onToggle }); }}
data-test-expand-button
>
<strong>{func ? expandLabel : collapseLabel}</strong>
</Button>
);
};
ExpandAllButton.propTypes = propTypes;
export default withAccordionStatus(ExpandAllButton);