all files / src/explore/components/controls/ MetricsControl.jsx

78.01% Statements 110/141
63.1% Branches 53/84
76% Functions 19/25
78.42% Lines 109/139
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                                               18× 16×                                               18× 18× 18× 18× 18× 18× 18× 18×     18×                 18×           18×                                                                               12×         18×   108×       18× 198× 36× 162× 54× 108× 108×                   10×                     21×                                                  
import React from 'react';
import PropTypes from 'prop-types';
import VirtualizedSelect from 'react-virtualized-select';
import ControlHeader from '../ControlHeader';
import { t } from '../../../locales';
import VirtualizedRendererWrap from '../../../components/VirtualizedRendererWrap';
import OnPasteSelect from '../../../components/OnPasteSelect';
import MetricDefinitionOption from '../MetricDefinitionOption';
import MetricDefinitionValue from '../MetricDefinitionValue';
import AdhocMetric from '../../AdhocMetric';
import columnType from '../../propTypes/columnType';
import savedMetricType from '../../propTypes/savedMetricType';
import adhocMetricType from '../../propTypes/adhocMetricType';
import {
  AGGREGATES,
  sqlaAutoGeneratedMetricNameRegex,
  druidAutoGeneratedMetricRegex,
} from '../../constants';
 
const propTypes = {
  name: PropTypes.string.isRequired,
  onChange: PropTypes.func,
  value: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, adhocMetricType])),
    PropTypes.oneOfType([PropTypes.string, adhocMetricType]),
  ]),
  columns: PropTypes.arrayOf(columnType),
  savedMetrics: PropTypes.arrayOf(savedMetricType),
  multi: PropTypes.bool,
  datasourceType: PropTypes.string,
};
 
const defaultProps = {
  onChange: () => {},
};
 
function isDictionaryForAdhocMetric(value) {
  return value && !(value instanceof AdhocMetric) && value.expressionType;
}
 
// adhoc metrics are stored as dictionaries in URL params. We convert them back into the
// AdhocMetric class for typechecking, consistency and instance method access.
function coerceAdhocMetrics(value) {
  if (!value) {
    return [];
  }
  if (I!Array.isArray(value)) {
    if (isDictionaryForAdhocMetric(value)) {
      return [new AdhocMetric(value)];
    }
    return [value];
  }
  return value.map((val) => {
    if (isDictionaryForAdhocMetric(val)) {
      return new AdhocMetric(val);
    }
    return val;
  });
}
 
function getDefaultAggregateForColumn(column) {
  const type = column.type;
  if (Itypeof type !== 'string') {
    return AGGREGATES.COUNT;
  } else Iif (type === '' || type === 'expression') {
    return AGGREGATES.SUM;
  } else Iif (type.match(/.*char.*/i) || type.match(/string.*/i) || type.match(/.*text.*/i)) {
    return AGGREGATES.COUNT_DISTINCT;
  } else Eif (type.match(/.*int.*/i) || type === 'LONG' || type === 'DOUBLE' || type === 'FLOAT') {
    return AGGREGATES.SUM;
  } else if (type.match(/.*bool.*/i)) {
    return AGGREGATES.MAX;
  } else if (type.match(/.*time.*/i)) {
    return AGGREGATES.COUNT;
  } else if (type.match(/unknown/i)) {
    return AGGREGATES.COUNT;
  }
  return null;
}
 
export default class MetricsControl extends React.PureComponent {
  constructor(props) {
    super(props);
    this.onChange = this.onChange.bind(this);
    this.onMetricEdit = this.onMetricEdit.bind(this);
    this.checkIfAggregateInInput = this.checkIfAggregateInInput.bind(this);
    this.optionsForSelect = this.optionsForSelect.bind(this);
    this.selectFilterOption = this.selectFilterOption.bind(this);
    this.isAutoGeneratedMetric = this.isAutoGeneratedMetric.bind(this);
    this.optionRenderer = VirtualizedRendererWrap(option => (
      <MetricDefinitionOption option={option} />
    ), { ignoreAutogeneratedMetrics: true });
    this.valueRenderer = option => (
      <MetricDefinitionValue
        option={option}
        onMetricEdit={this.onMetricEdit}
        columns={this.props.columns}
        multi={this.props.multi}
        datasourceType={this.props.datasourceType}
      />
    );
    this.refFunc = (ref) => {
      if (ref) {
        // eslint-disable-next-line no-underscore-dangle
        this.select = ref._selectRef;
      }
    };
    this.state = {
      aggregateInInput: null,
      options: this.optionsForSelect(this.props),
      value: coerceAdhocMetrics(this.props.value),
    };
  }
 
  componentWillReceiveProps(nextProps) {
    if (
      this.props.columns !== nextProps.columns ||
      this.props.savedMetrics !== nextProps.savedMetrics
    ) {
      this.setState({ options: this.optionsForSelect(nextProps) });
      this.props.onChange([]);
    }
    if (this.props.value !== nextProps.value) {
      this.setState({ value: coerceAdhocMetrics(nextProps.value) });
    }
  }
 
  onMetricEdit(changedMetric) {
    let newValue = this.state.value.map((value) => {
      if (Evalue.optionName === changedMetric.optionName) {
        return changedMetric;
      }
      return value;
    });
    if (I!this.props.multi) {
      newValue = newValue[0];
    }
    this.props.onChange(newValue);
  }
 
  onChange(opts) {
    let transformedOpts = opts;
    if (I!this.props.multi) {
      transformedOpts = [opts].filter(option => option);
    }
    let optionValues = transformedOpts.map((option) => {
      if (option.metric_name) {
        return option.metric_name;
      } else if (option.column_name) {
        const clearedAggregate = this.clearedAggregateInInput;
        this.clearedAggregateInInput = null;
        return new AdhocMetric({
          column: option,
          aggregate: clearedAggregate || getDefaultAggregateForColumn(option),
        });
      } else if (option instanceof AdhocMetric) {
        return option;
      } else Eif (option.aggregate_name) {
        const newValue = `${option.aggregate_name}()`;
        this.select.setInputValue(newValue);
        this.select.handleInputChange({ target: { value: newValue } });
        // we need to set a timeout here or the selectionWill be overwritten
        // by some browsers (e.g. Chrome)
        setTimeout(() => {
          this.select.input.input.selectionStart = newValue.length - 1;
          this.select.input.input.selectionEnd = newValue.length - 1;
        }, 0);
        return null;
      }
      return null;
    }).filter(option => option);
    if (I!this.props.multi) {
      optionValues = optionValues[0];
    }
    this.props.onChange(optionValues);
  }
 
  checkIfAggregateInInput(input) {
    let nextState = { aggregateInInput: null };
    Object.keys(AGGREGATES).forEach((aggregate) => {
      if (input.toLowerCase().startsWith(aggregate.toLowerCase() + '(')) {
        nextState = { aggregateInInput: aggregate };
      }
    });
    this.clearedAggregateInInput = this.state.aggregateInInput;
    this.setState(nextState);
  }
 
  optionsForSelect(props) {
    const options = [
      ...props.columns,
      ...Object.keys(AGGREGATES).map(aggregate => ({ aggregate_name: aggregate })),
      ...props.savedMetrics,
    ];
 
    return options.map((option) => {
      if (option.metric_name) {
        return { ...option, optionName: option.metric_name };
      } else if (option.column_name) {
        return { ...option, optionName: '_col_' + option.column_name };
      } else Eif (option.aggregate_name) {
        return { ...option, optionName: '_aggregate_' + option.aggregate_name };
      }
      notify.error(`provided invalid option to MetricsControl, ${option}`);
      return null;
    });
  }
 
  isAutoGeneratedMetric(savedMetric) {
    if (this.props.datasourceType === 'druid') {
      return druidAutoGeneratedMetricRegex.test(savedMetric.verbose_name);
    }
    return sqlaAutoGeneratedMetricNameRegex.test(savedMetric.metric_name);
  }
 
  selectFilterOption(option, filterValue) {
    if (this.state.aggregateInInput) {
      let endIndex = filterValue.length;
      if (IfilterValue.endsWith(')')) {
        endIndex = filterValue.length - 1;
      }
      const valueAfterAggregate = filterValue.substring(filterValue.indexOf('(') + 1, endIndex);
      return option.column_name &&
        (option.column_name.toLowerCase().indexOf(valueAfterAggregate.toLowerCase()) >= 0);
    }
    return option.optionName &&
      (!option.metric_name || !this.isAutoGeneratedMetric(option)) &&
      (option.optionName.toLowerCase().indexOf(filterValue.toLowerCase()) >= 0);
  }
 
  render() {
    // TODO figure out why the dropdown isnt appearing as soon as a metric is selected
    return (
      <div className="metrics-select">
        <ControlHeader {...this.props} />
        <OnPasteSelect
          multi={this.props.multi}
          name={`select-${this.props.name}`}
          placeholder={t('choose a column or aggregate function')}
          options={this.state.options}
          value={this.props.multi ? this.state.value : this.state.value[0]}
          labelKey="label"
          valueKey="optionName"
          clearable
          closeOnSelect
          onChange={this.onChange}
          optionRenderer={this.optionRenderer}
          valueRenderer={this.valueRenderer}
          onInputChange={this.checkIfAggregateInInput}
          filterOption={this.selectFilterOption}
          refFunc={this.refFunc}
          selectWrap={VirtualizedSelect}
        />
      </div>
    );
  }
}
 
MetricsControl.propTypes = propTypes;
MetricsControl.defaultProps = defaultProps;