all files / components/ SDRangeSlider.react.js

78.99% Statements 94/119
68.12% Branches 47/69
75% Functions 15/20
61.82% Lines 34/55
11 statements, 2 functions, 15 branches Ignored     
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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { omit } from 'ramda';
import { Range } from 'rc-slider';
 
import format from 'string-format';
 
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
 
 
const propTypes = {
  /** The ID used to identify this component */
  id: PropTypes.string,
 
  /** The value used to select the slider */
  value: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])),
 
  /**
   * Marks on the slider.
   * The key determines the position,
   * and the value determines what will show.
   * If you want to set the style of a specific mark point,
   * the value should be an object which
   * contains style and label properties.
   */
  marks: PropTypes.shape({
    number: PropTypes.oneOfType([
      /**
       * The label of the mark
       */
      PropTypes.string,
 
      /**
       * The style and label of the mark
       */
      PropTypes.shape({
        style: PropTypes.object,
        label: PropTypes.string
      })
    ])
  }),
 
  /**
   * allowCross could be set as true to allow those handles to cross.
   */
  allowCross: PropTypes.bool,
 
  /** Variable is strictly ascending? */
  ascending: PropTypes.bool,
 
  /** Minimum value for the slider */
  minVal: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
 
  /** Maximum value for the slider */
  maxVal: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
 
  /** Human-readable name of the variable to display */
  humanName: PropTypes.string,
 
  /** Description of the variable to display in the Dialog */
  description: PropTypes.string,
 
  /** Text to display when all values are selected, e.g. 'all ages' */
  allValuesText: PropTypes.string,
 
  /** Formatter to use which takes min and max value */
  rangeFormatter: PropTypes.string,
 
  /** Or higher string formatter */
  orHigherFormatter: PropTypes.string,
 
  /** Or less string formatter */
  orLowerFormatter: PropTypes.string,
 
  /** All values formatter */
  allValuesFormatter: PropTypes.string,
 
  /** Should the range slider try to split the label strings intelligently? */
  splitLabels: PropTypes.bool,
 
  /**
   * Should the range slider apply "{} to {}"-style formatting to the label if a single value
   * is selected?
   */
  singleValueFormatting: PropTypes.bool,
 
  /**
     * Determines when the component should update
     * its value. If `mouseup`, then the slider
     * will only trigger its value when the user has
     * finished dragging the slider. If `drag`, then
     * the slider will update its value continuously
     * as it is being dragged.
     * Only use `drag` if your updates are fast.
     */
    updatemode: PropTypes.oneOf(['mouseup', 'drag']),
 
  /** Class name to apply to the button */
  buttonClassName: PropTypes.string,
 
  /**
   * Dash-assigned callback that should be called whenever any of the
   * properties change
   */
  setProps: PropTypes.func
};
 
const defaultProps = {
  ascending: true,
  updatemode: 'mouseup',
  rangeFormatter: '{} to {}',
  orLowerFormatter: 'Under {}',
  orHigherFormatter: '{} or higher',
  buttonClassName: '',
  splitLabels: true,
  singleValueFormatting: true
};
 
 
/**
 * SDRangeSlider is an example component.
 * It takes a property, `label`, and
 * displays it.
 * It renders an input with the property `value`
 * which is editable by the user.
 */
export default class SDRangeSlider extends Component {
  constructor(props) {
    super(props);
    this.state = {value: props.value, editorOpen: false};
  }
 
  componentWillReceiveProps(newProps) {
    this.setState({value: newProps.value});
  }
 
  splitLabel(label, index) {
    const { splitLabels } = this.props;
 
    Eif (splitLabels) {
      const vals = label.split(' ');
      Eif (index < 0)
        return vals[vals.length + index];
      return vals[index];
    }
 
    return label;
  }
 
  get compressedLabel() {
    const { value } = this.state;
    const lowValSelected = value[0];
    const highValSelected = value[1];
 
    const {
      marks,
      allValuesText,
      orHigherFormatter,
      orLowerFormatter,
      rangeFormatter,
      singleValueFormatting } = this.props;
    const values = Object.keys(marks);
    const minValue = Math.min(...values);
    const maxVal = Math.max(...values);
 
    // Selected the entire range
    Iif (minValue === lowValSelected && maxVal === highValSelected)
      return allValuesText;
    // We don't want to do anything special if only one value is selected
    else Iif (!singleValueFormatting && lowValSelected === highValSelected)
      return marks[lowValSelected].label;
    // This goes from the minimum possible value up to the highest value selected
    else Eif (minValue === lowValSelected)
      return format(orLowerFormatter, this.splitLabel(marks[highValSelected].label, -1));
    // This goes from the highest possible value down to the lowest value selected
    else if (maxVal === highValSelected)
      return format(orHigherFormatter, this.splitLabel(marks[lowValSelected].label, 0));
 
    const highStr = this.splitLabel(marks[highValSelected].label, -1);
    const lowStr = this.splitLabel(marks[lowValSelected].label, 0);
 
    return format(rangeFormatter, lowStr, highStr);
  }
 
  render() {
    const { fireEvent, setProps, updatemode, buttonClassName, humanName, description } = this.props;
    const { value } = this.state;
 
    const actions = [
      <FlatButton
        label="Done editing range"
        primary={true}
        onClick={() => { this.setState({editorOpen: false}); }}
      />
    ];
 
    const compressedLabel = this.compressedLabel;
 
    return (
      <MuiThemeProvider>
        <div className="sd-range-slider">
          <div className="compressed-label">
            <a
              href="#edit-slider"
              onClick={(event) => {
                event.preventDefault();
                this.setState({editorOpen: true});
              }}
              className="edit"
            >
              <span className="label-text">{compressedLabel}</span>
              <span className={buttonClassName} />
              <span className="edit-rarr">&rarr;</span>
            </a>
          </div>
          <Dialog
            title={typeof humanName === 'string'
              ? <h6>Edit range for <strong>{humanName}</strong></h6>
              : <h6>Edit range</h6>}
            actions={actions}
            modal={false}
            open={this.state.editorOpen}
            onRequestClose={() => { this.setState({editorOpen: false}); }}
          >
            <div>
              <p>{description}</p>
              <p>Selected: <strong>{compressedLabel}</strong></p>
              <Range
                onChange={val => {
                  this.setState({value: val});
                  if (updatemode === 'drag') {
                    if (setProps) setProps({value: val});
                    if (fireEvent) fireEvent('change');
                  }
                }}
                style={{width: '82%', marginLeft: '9%', marginBottom: 20}}
                onAfterChange={val => {
                  if (updatemode === 'mouseup') {
                    if (setProps) setProps({value: val});
                    if (fireEvent) fireEvent('change');
                  }
                }}
                value={value}
                {...omit(
                  ['value', 'fireEvent', 'setProps', 'updatemode'],
                  {...this.props, min: this.props.minVal, max: this.props.maxVal})}
              />
            </div>
          </Dialog>
        </div>
        </MuiThemeProvider>);
  }
}
 
SDRangeSlider.propTypes = propTypes;
SDRangeSlider.defaultProps = defaultProps;