all files / src/visualizations/ filter_box.jsx

29.57% Statements 34/115
11.54% Branches 6/52
5.56% Functions 1/18
29.13% Lines 30/103
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 261 262 263 264 265 266 267 268 269 270 271 272                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
EI// JS
import d3 from 'd3';
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import VirtualizedSelect from 'react-virtualized-select';
import { Creatable } from 'react-select';
import { Button } from 'react-bootstrap';
 
import DateFilterControl from '../explore/components/controls/DateFilterControl';
import ControlRow from '../explore/components/ControlRow';
import Control from '../explore/components/Control';
import controls from '../explore/controls';
import OnPasteSelect from '../components/OnPasteSelect';
import VirtualizedRendererWrap from '../components/VirtualizedRendererWrap';
import './filter_box.css';
import { t } from '../locales';
 
// maps control names to their key in extra_filters
const timeFilterMap = {
  since: '__from',
  until: '__to',
  granularity_sqla: '__time_col',
  time_grain_sqla: '__time_grain',
  druid_time_origin: '__time_origin',
  granularity: '__granularity',
};
const propTypes = {
  origSelectedValues: PropTypes.object,
  instantFiltering: PropTypes.bool,
  filtersChoices: PropTypes.object,
  onChange: PropTypes.func,
  showDateFilter: PropTypes.bool,
  showSqlaTimeGrain: PropTypes.bool,
  showSqlaTimeColumn: PropTypes.bool,
  showDruidTimeGrain: PropTypes.bool,
  showDruidTimeOrigin: PropTypes.bool,
  datasource: PropTypes.object.isRequired,
};
const defaultProps = {
  origSelectedValues: {},
  onChange: () => {},
  showDateFilter: false,
  showSqlaTimeGrain: false,
  showSqlaTimeColumn: false,
  showDruidTimeGrain: false,
  showDruidTimeOrigin: false,
  instantFiltering: true,
};
 
class FilterBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedValues: props.origSelectedValues,
      hasChanged: false,
    };
  }
  getControlData(controlName) {
    const control = Object.assign({}, controls[controlName]);
    const controlData = {
      name: controlName,
      key: `control-${controlName}`,
      value: this.state.selectedValues[timeFilterMap[controlName]],
      actions: { setControlValue: this.changeFilter.bind(this) },
    };
    Object.assign(control, controlData);
    const mapFunc = control.mapStateToProps;
    if (mapFunc) {
      return Object.assign({}, control, mapFunc(this.props));
    }
    return control;
  }
  clickApply() {
    const { selectedValues } = this.state;
    Object.keys(selectedValues).forEach((fltr, i, arr) => {
      let refresh = false;
      if (i === arr.length - 1) {
        refresh = true;
      }
      this.props.onChange(fltr, selectedValues[fltr], false, refresh);
    });
    this.setState({ hasChanged: false });
  }
  changeFilter(filter, options) {
    const fltr = timeFilterMap[filter] || filter;
    let vals = null;
    if (options !== null) {
      if (Array.isArray(options)) {
        vals = options.map(opt => opt.value);
      } else if (options.value) {
        vals = options.value;
      } else {
        vals = options;
      }
    }
    const selectedValues = Object.assign({}, this.state.selectedValues);
    selectedValues[fltr] = vals;
    this.setState({ selectedValues, hasChanged: true });
    if (this.props.instantFiltering) {
      this.props.onChange(fltr, vals, false, true);
    }
  }
  render() {
    let dateFilter;
    const since = '__from';
    const until = '__to';
    if (this.props.showDateFilter) {
      dateFilter = (
        <div className="row space-1">
          <div className="col-lg-6 col-xs-12">
            <DateFilterControl
              name={since}
              label={t('Since')}
              description={t('Select starting date')}
              onChange={this.changeFilter.bind(this, since)}
              value={this.state.selectedValues[since]}
            />
          </div>
          <div className="col-lg-6 col-xs-12">
            <DateFilterControl
              name={until}
              label={t('Until')}
              description={t('Select end date')}
              onChange={this.changeFilter.bind(this, until)}
              value={this.state.selectedValues[until]}
            />
          </div>
        </div>
      );
    }
    const datasourceFilters = [];
    const sqlaFilters = [];
    const druidFilters = [];
    if (this.props.showSqlaTimeGrain) sqlaFilters.push('time_grain_sqla');
    if (this.props.showSqlaTimeColumn) sqlaFilters.push('granularity_sqla');
    if (this.props.showDruidTimeGrain) druidFilters.push('granularity');
    if (this.props.showDruidTimeOrigin) druidFilters.push('druid_time_origin');
    if (sqlaFilters.length) {
      datasourceFilters.push(
        <ControlRow
          key="sqla-filters"
          className="control-row"
          controls={sqlaFilters.map(control => (
            <Control {...this.getControlData(control)} />
          ))}
        />,
      );
    }
    if (druidFilters.length) {
      datasourceFilters.push(
        <ControlRow
          key="druid-filters"
          className="control-row"
          controls={druidFilters.map(control => (
            <Control {...this.getControlData(control)} />
          ))}
        />,
      );
    }
    // Add created options to filtersChoices, even though it doesn't exist,
    // or these options will exist in query sql but invisible to end user.
    for (const filterKey in this.state.selectedValues) {
      if (
        !this.state.selectedValues.hasOwnProperty(filterKey) ||
        !(filterKey in this.props.filtersChoices)
      ) {
        continue;
      }
      const existValues = this.props.filtersChoices[filterKey].map(f => f.id);
      for (const v of this.state.selectedValues[filterKey]) {
        if (existValues.indexOf(v) === -1) {
          const addChoice = {
            filter: filterKey,
            id: v,
            text: v,
            metric: 0,
          };
          this.props.filtersChoices[filterKey].unshift(addChoice);
        }
      }
    }
    const filters = Object.keys(this.props.filtersChoices).map((filter) => {
      const data = this.props.filtersChoices[filter];
      const maxes = {};
      maxes[filter] = d3.max(data, function (d) {
        return d.metric;
      });
      return (
        <div key={filter} className="m-b-5">
          {this.props.datasource.verbose_map[filter] || filter}
          <OnPasteSelect
            placeholder={t('Select [%s]', filter)}
            key={filter}
            multi
            value={this.state.selectedValues[filter]}
            options={data.map((opt) => {
              const perc = Math.round((opt.metric / maxes[opt.filter]) * 100);
              const backgroundImage = (
                'linear-gradient(to right, lightgrey, ' +
                `lightgrey ${perc}%, rgba(0,0,0,0) ${perc}%`
              );
              const style = {
                backgroundImage,
                padding: '2px 5px',
              };
              return { value: opt.id, label: opt.id, style };
            })}
            onChange={this.changeFilter.bind(this, filter)}
            selectComponent={Creatable}
            selectWrap={VirtualizedSelect}
            optionRenderer={VirtualizedRendererWrap(opt => opt.label)}
          />
        </div>
      );
    });
    return (
      <div className="scrollbar-container">
        <div className="scrollbar-content">
          {dateFilter}
          {datasourceFilters}
          {filters}
          {!this.props.instantFiltering &&
            <Button
              bsSize="small"
              bsStyle="primary"
              onClick={this.clickApply.bind(this)}
              disabled={!this.state.hasChanged}
            >
              {t('Apply')}
            </Button>
          }
        </div>
      </div>
    );
  }
}
FilterBox.propTypes = propTypes;
FilterBox.defaultProps = defaultProps;
 
function filterBox(slice, payload) {
  const d3token = d3.select(slice.selector);
  d3token.selectAll('*').remove();
 
  // filter box should ignore the dashboard's filters
  // const url = slice.jsonEndpoint({ extraFilters: false });
  const fd = slice.formData;
  const filtersChoices = {};
  // Making sure the ordering of the fields matches the setting in the
  // dropdown as it may have been shuffled while serialized to json
  fd.groupby.forEach((f) => {
    filtersChoices[f] = payload.data[f];
  });
  ReactDOM.render(
    <FilterBox
      filtersChoices={filtersChoices}
      onChange={slice.addFilter}
      showDateFilter={fd.date_filter}
      showSqlaTimeGrain={fd.show_sqla_time_granularity}
      showSqlaTimeColumn={fd.show_sqla_time_column}
      showDruidTimeGrain={fd.show_druid_time_granularity}
      showDruidTimeOrigin={fd.show_druid_time_origin}
      datasource={slice.datasource}
      origSelectedValues={slice.getFilters() || {}}
      instantFiltering={fd.instant_filtering}
    />,
    document.getElementById(slice.containerId),
  );
}
 
module.exports = filterBox;