Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 16x 10x 16x 16x 16x 16x 13x 13x 16x 7x 6x 1x 16x 6x 5x 1x 1x 16x 3x 28x 28x | /*
Copyright (c) 2018-2019 Uber Technologies, Inc.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
import * as React from 'react';
import {MODE, STATE_CHANGE_TYPE} from './constants.js';
import type {StatefulContainerPropsT, StateT} from './types.js';
// handles the case where selected = 0
function isSelectedDefined(selected) {
return Array.isArray(selected) || typeof selected === 'number';
}
function defaultStateReducer(
type: $Values<typeof STATE_CHANGE_TYPE>,
nextState: StateT,
currentState: StateT,
) {
return nextState;
}
export default class StatefulContainer extends React.Component<
StatefulContainerPropsT,
StateT,
> {
static defaultProps = {
initialState: {selected: []},
stateReducer: defaultStateReducer,
};
constructor(props: StatefulContainerPropsT) {
super(props);
const {initialState = {}} = props;
const {selected = []} = initialState;
this.state = {
selected: isSelectedDefined(selected) ? [].concat(selected) : [],
};
}
changeState = (nextState: StateT) => {
Eif (this.props.stateReducer) {
this.setState(
this.props.stateReducer(
STATE_CHANGE_TYPE.change,
nextState,
this.state,
),
);
} else {
this.setState(nextState);
}
};
onClick = (event: SyntheticEvent<HTMLButtonElement>, index: number) => {
if (this.props.mode === MODE.radio) {
if (
this.state.selected.length === 0 ||
this.state.selected[0] !== index
) {
this.changeState({selected: [index]});
} else {
this.changeState({selected: []});
}
}
if (this.props.mode === MODE.checkbox) {
if (!this.state.selected.includes(index)) {
this.changeState({selected: [...this.state.selected, index]});
} else {
this.changeState({
selected: this.state.selected.filter(value => value !== index),
});
}
}
if (this.props.onClick) {
this.props.onClick(event, index);
}
};
render() {
const {initialState, stateReducer, ...props} = this.props;
return this.props.children({
...props,
onClick: this.onClick,
selected: this.state.selected,
});
}
}
|