All files / src/hocs/components sort.js

26.32% Statements 5/19
0% Branches 0/12
0% Functions 0/9
26.32% Lines 5/19

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 99 100      4x       4x         4x           4x       4x                                                                                                                                                          
// @flow
import React, {Component} from 'react';
import {Select, Icon} from 'antd';
const Option = Select.Option;
import styled from 'styled-components';
import {FormattedMessage} from 'react-intl';
 
const Selector = styled(Select)`
  width: 150px;
  margin: 0 15px;
`;
 
const OrderSwitch = styled.div`
  cursor: pointer;
  display: flex;
  flex-direction: column;
`;
 
const UpIcon = styled(Icon)`
  color: ${props => props.order > 0 ? '#333' : '#ccc'};
`;
 
const DownIcon = styled(Icon)`
  color: ${props => props.order > 0 ? '#ccc' : '#333'};
`
 
type Props = {
  orderField: ?string,
  items: Object,
  options: Array<{
    field: string,
    label: string,
    defaultOrder: 'ASC' | 'DESC'
  }>,
  orderType: 'ASC' | 'DESC',
  changeOrder: ({
    orderField: string,
    orderType: string
  }) => void,
  defaultField: string
}
 
type State = {
  order: boolean,
  key: string
}
 
export default class Sort extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      order: order(props.orderType || 'ASC'),
      key: props.orderField || '',
    };
  }
 
  onChange = (value: string) => {
    this.setState({
      key: value
    }, this.submit);
  }
 
  changeOrder = () => {
    this.setState({
      order: !this.state.order,
    }, this.submit);
  }
 
  submit = () => {
    const {changeOrder} = this.props;
    const {key, order} = this.state;
    changeOrder({
      orderField: key,
      orderType: order ? 'ASC' : 'DESC'
    });
  }
 
  render() {
    const {options, defaultField} = this.props;
    const {key, order} = this.state;
    return (
      <div style={{display: 'flex'}}>
        <Selector onChange={this.onChange} value={key} defaultValue={defaultField} allowClear
            placeholder={<FormattedMessage id="query.sort.placeholder"/>}
        >
          {(options || []).map((option, i) => <Option key={i} value={option.field}>{option.label}</Option>)}
        </Selector>
        <OrderSwitch onClick={this.changeOrder}>
          <UpIcon order={order} type="caret-up" />
          <DownIcon order={order} type="caret-down" />
        </OrderSwitch>
      </div>
    );
  }
}
 
 
function order(orderType) {
  return orderType === 'ASC';
}