all files / src/explore/components/ AdhocFilterEditPopoverSimpleTabContent.jsx

79.63% Statements 86/108
63.24% Branches 43/68
65% Functions 13/20
79.44% Lines 85/107
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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294                                                                                                                                                                                                                         104×                                       10×   10×                     10×                         45×       10×     98×                               10×                                                                              
import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup } from 'react-bootstrap';
import VirtualizedSelect from 'react-virtualized-select';
 
import AdhocFilter, { EXPRESSION_TYPES, CLAUSES } from '../AdhocFilter';
import adhocMetricType from '../propTypes/adhocMetricType';
import columnType from '../propTypes/columnType';
import { t } from '../../locales';
import {
  OPERATORS,
  TABLE_ONLY_OPERATORS,
  DRUID_ONLY_OPERATORS,
  HAVING_OPERATORS,
  MULTI_OPERATORS,
} from '../constants';
import FilterDefinitionOption from './FilterDefinitionOption';
import OnPasteSelect from '../../components/OnPasteSelect';
import SelectControl from './controls/SelectControl';
import VirtualizedRendererWrap from '../../components/VirtualizedRendererWrap';
 
const $ = require('jquery');
 
const propTypes = {
  adhocFilter: PropTypes.instanceOf(AdhocFilter).isRequired,
  onChange: PropTypes.func.isRequired,
  options: PropTypes.arrayOf(PropTypes.oneOfType([
    columnType,
    PropTypes.shape({ saved_metric_name: PropTypes.string.isRequired }),
    adhocMetricType,
  ])).isRequired,
  onHeightChange: PropTypes.func.isRequired,
  datasource: PropTypes.object,
};
 
const defaultProps = {
  datasource: {},
};
 
function translateOperator(operator) {
  if (operator === OPERATORS['==']) {
    return 'equals';
  } else if (operator === OPERATORS['!=']) {
    return 'not equal to';
  } else if (operator === OPERATORS.LIKE) {
    return 'like';
  }
  return operator;
}
 
const SINGLE_LINE_SELECT_CONTROL_HEIGHT = 30;
 
export default class AdhocFilterEditPopoverSimpleTabContent extends React.Component {
  constructor(props) {
    super(props);
    this.onSubjectChange = this.onSubjectChange.bind(this);
    this.onOperatorChange = this.onOperatorChange.bind(this);
    this.onComparatorChange = this.onComparatorChange.bind(this);
    this.onInputComparatorChange = this.onInputComparatorChange.bind(this);
    this.isOperatorRelevant = this.isOperatorRelevant.bind(this);
    this.refreshComparatorSuggestions = this.refreshComparatorSuggestions.bind(this);
    this.multiComparatorRef = this.multiComparatorRef.bind(this);
 
    this.state = {
      suggestions: [],
      multiComparatorHeight: SINGLE_LINE_SELECT_CONTROL_HEIGHT,
    };
 
    this.selectProps = {
      multi: false,
      name: 'select-column',
      labelKey: 'label',
      autosize: false,
      clearable: false,
      selectWrap: VirtualizedSelect,
    };
  }
 
  componentWillMount() {
    this.refreshComparatorSuggestions();
  }
 
  componentDidMount() {
    this.handleMultiComparatorInputHeightChange();
  }
 
  componentDidUpdate(prevProps) {
    if (IprevProps.adhocFilter.subject !== this.props.adhocFilter.subject) {
      this.refreshComparatorSuggestions();
    }
    this.handleMultiComparatorInputHeightChange();
  }
 
  onSubjectChange(option) {
    let subject;
    let clause;
    // infer the new clause based on what subject was selected.
    if (option && option.column_name) {
      subject = option.column_name;
      clause = CLAUSES.WHERE;
    } else Eif (option && (option.saved_metric_name || option.label)) {
      subject = option.saved_metric_name || option.label;
      clause = CLAUSES.HAVING;
    }
    this.props.onChange(this.props.adhocFilter.duplicateWith({
      subject,
      clause,
      expressionType: EXPRESSION_TYPES.SIMPLE,
    }));
  }
 
  onOperatorChange(operator) {
    const currentComparator = this.props.adhocFilter.comparator;
    let newComparator;
    // convert between list of comparators and individual comparators
    // (e.g. `in ('North America', 'Africa')` to `== 'North America'`)
    if (MULTI_OPERATORS.indexOf(operator.operator) >= 0) {
      newComparator = Array.isArray(currentComparator) ?
        currentComparator :
        [currentComparator].filter(element => element);
    } else {
      newComparator = Array.isArray(currentComparator) ? currentComparator[0] : currentComparator;
    }
    this.props.onChange(this.props.adhocFilter.duplicateWith({
      operator: operator && operator.operator,
      comparator: newComparator,
      expressionType: EXPRESSION_TYPES.SIMPLE,
    }));
  }
 
  onInputComparatorChange(event) {
    this.onComparatorChange(event.target.value);
  }
 
  onComparatorChange(comparator) {
    this.props.onChange(this.props.adhocFilter.duplicateWith({
      comparator,
      expressionType: EXPRESSION_TYPES.SIMPLE,
    }));
  }
 
  handleMultiComparatorInputHeightChange() {
    if (Ethis.multiComparatorComponent) {
      /* eslint-disable no-underscore-dangle */
      const multiComparatorDOMNode = this.multiComparatorComponent._selectRef &&
        this.multiComparatorComponent._selectRef.select &&
        this.multiComparatorComponent._selectRef.select.control;
      if (EmultiComparatorDOMNode) {
        if (multiComparatorDOMNode.clientHeight !== this.state.multiComparatorHeight) {
          this.props.onHeightChange((
            multiComparatorDOMNode.clientHeight - this.state.multiComparatorHeight
          ));
          this.setState({ multiComparatorHeight: multiComparatorDOMNode.clientHeight });
        }
      }
    }
  }
 
  refreshComparatorSuggestions() {
    const datasource = this.props.datasource;
    const col = this.props.adhocFilter.subject;
    const having = this.props.adhocFilter.clause === CLAUSES.HAVING;
 
    if (Icol && datasource && datasource.filter_select && !having) {
      if (this.state.activeRequest) {
        this.state.activeRequest.abort();
      }
      this.setState({
        activeRequest: $.ajax({
          type: 'GET',
          url: `/superset/filter/${datasource.type}/${datasource.id}/${col}/`,
          success: data => this.setState({ suggestions: data, activeRequest: null }),
        }),
      });
    }
  }
 
  isOperatorRelevant(operator) {
    return !(
      (this.props.datasource.type === 'druid' && TABLE_ONLY_OPERATORS.indexOf(operator) >= 0) ||
      (this.props.datasource.type === 'table' && DRUID_ONLY_OPERATORS.indexOf(operator) >= 0) ||
      (
        this.props.adhocFilter.clause === CLAUSES.HAVING &&
        HAVING_OPERATORS.indexOf(operator) === -1
      )
    );
  }
 
  focusComparator(ref) {
    if (ref) {
      ref.focus();
    }
  }
 
  multiComparatorRef(ref) {
    if (ref) {
      this.multiComparatorComponent = ref;
    }
  }
 
  render() {
    const { adhocFilter, options, datasource } = this.props;
 
    let subjectSelectProps = {
      value: adhocFilter.subject ? { value: adhocFilter.subject } : undefined,
      onChange: this.onSubjectChange,
      optionRenderer: VirtualizedRendererWrap(option => (
        <FilterDefinitionOption option={option} />
      )),
      valueRenderer: option => <span>{option.value}</span>,
      valueKey: 'filterOptionName',
      noResultsText: t('No such column found. To filter on a metric, try the Custom SQL tab.'),
    };
 
    if (datasource.type === 'druid') {
      subjectSelectProps = {
        ...subjectSelectProps,
        placeholder: t('%s column(s) and metric(s)', options.length),
        options,
      };
    } else {
      // we cannot support simple ad-hoc filters for metrics because we don't know what type
      // the value should be cast to (without knowing the output type of the aggregate, which
      // becomes a rather complicated problem)
      subjectSelectProps = {
        ...subjectSelectProps,
        placeholder: adhocFilter.clause === CLAUSES.WHERE ?
          t('%s column(s)', options.length) :
          t('To filter on a metric, use Custom SQL tab.'),
        options: options.filter(option => option.column_name),
      };
    }
 
    const operatorSelectProps = {
      placeholder: t('%s operators(s)', Object.keys(OPERATORS).length),
      options: Object.keys(OPERATORS).filter(this.isOperatorRelevant).map((
        operator => ({ operator })
      )),
      value: adhocFilter.operator,
      onChange: this.onOperatorChange,
      optionRenderer: VirtualizedRendererWrap((
        operator => translateOperator(operator.operator)
      )),
      valueRenderer: operator => (
        <span>
          {translateOperator(operator.operator)}
        </span>
      ),
      valueKey: 'operator',
    };
 
    return (
      <span>
        <FormGroup className="adhoc-filter-simple-column-dropdown">
          <OnPasteSelect {...this.selectProps} {...subjectSelectProps} />
        </FormGroup>
        <FormGroup>
          <OnPasteSelect {...this.selectProps} {...operatorSelectProps} />
        </FormGroup>
        <FormGroup>
          {
            (
              MULTI_OPERATORS.indexOf(adhocFilter.operator) >= 0 ||
              this.state.suggestions.length > 0
            ) ?
              <SelectControl
                multi={MULTI_OPERATORS.indexOf(adhocFilter.operator) >= 0}
                freeForm
                name="filter-comparator-value"
                value={adhocFilter.comparator}
                isLoading={false}
                choices={this.state.suggestions}
                onChange={this.onComparatorChange}
                showHeader={false}
                noResultsText={t('type a value here')}
                refFunc={this.multiComparatorRef}
              /> :
              <input
                ref={this.focusComparator}
                type="text"
                onChange={this.onInputComparatorChange}
                value={adhocFilter.comparator || ''}
                className="form-control input-sm"
                placeholder={t('Filter value')}
              />
          }
        </FormGroup>
      </span>
    );
  }
}
AdhocFilterEditPopoverSimpleTabContent.propTypes = propTypes;
AdhocFilterEditPopoverSimpleTabContent.defaultProps = defaultProps;