AutocompleteFilter.tsx 11.6 KB
Newer Older
Maxym Borodenko's avatar
Maxym Borodenko committed
1
import * as React from 'react';
Matija Obreza's avatar
Matija Obreza committed
2
import { Fields, Field } from 'redux-form';
Maxym Borodenko's avatar
Maxym Borodenko committed
3 4 5 6 7 8 9 10 11
import { translate } from 'react-i18next';
import * as _ from 'lodash';

import Number from 'ui/common/Number';
import { Properties, PropertiesItem } from 'ui/common/Properties';
import LabelValue from 'model/LabelValue';
import AccessionFilter from 'model/accession/AccessionFilter';
import MaterialAutosuggest from 'ui/common/material-autosuggest';
import { debounce } from 'debounce';
12
import { AddCircle as Add, RemoveCircle as Remove, HighlightOff as Clear} from '@material-ui/icons';
Maxym Borodenko's avatar
Maxym Borodenko committed
13 14 15 16

interface IStringListProps extends React.ClassAttributes<any> {
  input: any;
  notInput: any;
17
  removeByValue: (index: number, isNot: boolean) => void;
Maxym Borodenko's avatar
Maxym Borodenko committed
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
}

class StringList extends React.Component<IStringListProps> {

  public state = {
    renderList: [],
  };

  private addToNotList = (item, index) => {
    const { input, notInput } = this.props;
    const {renderList} = this.state;
    renderList[index] = {value: item.value, state: false};
    this.setState({renderList});

    input.onChange(renderList.filter((renderItem) => renderItem.state).map((renderItem) => renderItem.value));
    notInput.onChange(renderList.filter((renderItem) => !renderItem.state).map((renderItem) => renderItem.value));
  }

  private removeFromNotList = (item, index) => {
    const { input, notInput } = this.props;
    const {renderList} = this.state;
    renderList[index] = {value: item.value, state: true};
    this.setState({renderList});

    input.onChange(renderList.filter((renderItem) => renderItem.state).map((renderItem) => renderItem.value));
    notInput.onChange(renderList.filter((renderItem) => !renderItem.state).map((renderItem) => renderItem.value));
  }

  public componentWillMount() {
    let {input: {value: doList}, notInput: {value: notList}} = this.props;
    doList = doList || [];
    notList = notList || [];
    const {renderList} = this.state;

    doList
      .filter((doItem) => renderList.findIndex((renderItem) => renderItem.value === doItem) === -1)
      .map((doItem) => renderList.push({value: doItem, state: true}));

    notList
      .filter((notItem) => renderList.findIndex((renderItem) => renderItem.value === notItem) === -1)
      .map((notItem) => renderList.push({value: notItem, state: false}));

    this.setState({renderList});
  }

  public componentWillReceiveProps(nextProps) {
    let {input: {value: doList}, notInput: {value: notList}} = nextProps;
    doList = doList || [];
    notList = notList || [];
    const {renderList} = this.state;
    const newRenderList = [];

    renderList.map((renderItem) => {
      if (doList.indexOf(renderItem.value) !== -1 || notList.indexOf(renderItem.value) !== -1) {
        newRenderList.push(renderItem);
      }
    });

    doList
      .filter((doItem) => newRenderList.findIndex((renderItem) => renderItem.value === doItem) === -1)
      .map((doItem) => newRenderList.push({value: doItem, state: true}));

    notList
      .filter((notItem) => newRenderList.findIndex((renderItem) => renderItem.value === notItem) === -1)
      .map((notItem) => newRenderList.push({value: notItem, state: false}));

    this.setState({renderList: newRenderList});
  }

  public render() {
88
    const {removeByValue} = this.props;
Maxym Borodenko's avatar
Maxym Borodenko committed
89 90 91 92
    const {renderList} = this.state;
    return (
      <div>
        { renderList.map((renderItem, index) => (
93 94 95 96 97 98 99 100 101 102
          <div style={ { margin: '.2rem 0', padding: '.2rem 1rem', backgroundColor: '#e8e5e1', color: '#202222', display: 'flex', justifyContent: 'space-between', alignItems: 'center' } } key={ renderItem.value }>
            <span style={ {display: 'flex', alignItems: 'center'} }>
              { renderItem.state ?
                <span className="font-bold float-left mr-5" onClick={ () => this.addToNotList(renderItem, index) }><Add style={ {cursor: 'pointer', color: '#6f6f6f', fontSize: '18px'} }/></span>
                :
                <span className="font-bold float-left mr-5" onClick={ () => this.removeFromNotList(renderItem, index) }><Remove style={ {cursor: 'pointer', color: '#6f6f6f', fontSize: '18px'} }/></span>
              }
              { renderItem.value }
            </span>
            <div className="font-bold float-right" onClick={ () => removeByValue(renderItem.value, !renderItem.state) }><Clear style={ {cursor: 'pointer', color: '#6f6f6f', fontSize: '20px'} }/></div>
Maxym Borodenko's avatar
Maxym Borodenko committed
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
          </div>
        )) }
      </div>

    );
  }
}

interface IAutocompleteFilterInternal extends React.ClassAttributes<any> {
  field: string;
  filterCode: string;
  input: any;
  placeholder?: string;
  label?: string;
  options?: { [key: string]: any; };
  t: any;
  addToNotList: (item: any) => void;
  notList: any[];
  autocomplete: (field: string, term: string, filter: string | AccessionFilter) => Promise<Array<LabelValue<string>>>;
}

class AutocompleteFilterInternal extends React.Component<IAutocompleteFilterInternal & any, any> {

  private constructor(props, context) {
    super(props, context);
    const notValues = _.get(props, `${props.names[0]}.input.value`);
    const values = _.get(props, `${props.names[1]}.input.value`);

    this.state = {
Maxym Borodenko's avatar
Maxym Borodenko committed
132
      excludedValues: [],
Maxym Borodenko's avatar
Maxym Borodenko committed
133 134 135 136 137 138 139 140 141 142 143 144 145
      values,
      notValues,
      text: '',
      autocompleteObj: [],
    };
  }

  public componentWillMount() {
    const input = _.get(this.props, `${this.props.names[0]}.input`);
    const value = typeof input.value[0] === 'number' ? input.value.map((key) => `${key}`) : input.value;
    const notValue = _.get(this.props, `${this.props.names[1]}.input.value`);

    this.setState({
Maxym Borodenko's avatar
Maxym Borodenko committed
146
      excludedValues: [],
Maxym Borodenko's avatar
Maxym Borodenko committed
147 148 149 150 151 152 153 154 155 156 157 158
      values: [ ...value ],
      notValues: [ ...notValue ],
      text: '',
    });
  }

  public componentWillReceiveProps(nextProps) {
    const input = _.get(nextProps, `${nextProps.names[0]}.input`);
    const value = typeof input.value[0] === 'number' ? input.value.map((key) => `${key}`) : input.value;
    const notValue = _.get(nextProps, `${nextProps.names[1]}.input.value`);

    this.setState({
159
      excludedValues: [...value, ...notValue],
Maxym Borodenko's avatar
Maxym Borodenko committed
160 161 162 163 164 165 166 167
      values: [ ...value ],
      notValues: [...notValue],
      text: '',
    });
  }

  private maybeAdd = (...newValues: string[]) => {
    const values = [ ...this.state.values ];
168 169 170 171
    const excludedValues = [ ];
    if (this.state.excludedValues) {
      excludedValues.push(...this.state.excludedValues);
    }
Maxym Borodenko's avatar
Maxym Borodenko committed
172 173 174 175 176 177

    newValues.forEach((text) => {
      if (text && text.length > 0) {
        if (values.indexOf(text) < 0) {
          values.push(text);
        }
178 179 180
        if (excludedValues.indexOf(text) < 0) {
          excludedValues.push(text);
        }
Maxym Borodenko's avatar
Maxym Borodenko committed
181 182 183 184 185 186 187
      }
    });

    if (!_.isEqual(values, this.state.values)) {
      this.setState({
        text: '',
        values,
188
        excludedValues,
Maxym Borodenko's avatar
Maxym Borodenko committed
189 190 191 192 193
      });
    }
    return values;
  }

194 195 196
  private maybeRemove = (isNot?: boolean, ...newValues: string[]) => {
    const values = isNot ? [ ...this.state.notValues ] : [ ...this.state.values ];
    const excludedValues = this.state.excludedValues;
Maxym Borodenko's avatar
Maxym Borodenko committed
197 198 199 200 201 202 203

    newValues.forEach((text) => {
      if (text && text.length > 0) {
        const index: number = values.indexOf(text);
        if (index >= 0) {
          values.splice(index, 1);
        }
204 205 206 207
        const indexExcluded: number = excludedValues.indexOf(text);
        if (indexExcluded >= 0) {
          excludedValues.splice(indexExcluded, 1);
        }
Maxym Borodenko's avatar
Maxym Borodenko committed
208 209 210
      }
    });

211
    if (!_.isEqual(values, isNot ? this.state.notValues : this.state.values)) {
Maxym Borodenko's avatar
Maxym Borodenko committed
212 213
      this.setState({
        text: '',
214 215 216
        values: isNot ? this.state.values : values,
        notValues: !isNot ? this.state.notValues : values,
        excludedValues,
Maxym Borodenko's avatar
Maxym Borodenko committed
217 218 219 220 221
      });
    }
    return values;
  }

222
  private removeByValue = (value, isNot) => {
Maxym Borodenko's avatar
Maxym Borodenko committed
223
    const { input } = _.get(this.props, this.props.names[isNot ? 1 : 0]);
224 225

    const newValues = this.maybeRemove(isNot, value);
Maxym Borodenko's avatar
Maxym Borodenko committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    input.onChange(newValues);
  }

  private onInputChange = (e) => {
    const { autocomplete, field, filterCode } = this.props;
    if (e.target && typeof e.target.value === 'string') {
      if (e.target && e.target.value) {
        if (e.target.value !== this.state.text) {
          if (e.target.value.length >= 3) {
            this.setState({text: e.target.value});
            autocomplete(field, e.target.value, filterCode)
              .then((autocompleteObj) => {
                this.setState({...this.state, autocompleteObj});
              });
          }
        }
      }
    }
  }

246 247 248 249 250 251 252 253 254 255 256
  private dataPasted = (e) => {
    const data = e.clipboardData.getData('text/plain');
    const dataArr = data.split(/[,\n;]/).map((item) => item.trim());
    if (dataArr && dataArr.length > 1) {
        e.preventDefault();
        const values = this.maybeAdd(...dataArr);
        const { input } = _.get(this.props, this.props.names[0]);
        input.onChange(values);
      }
  }

Maxym Borodenko's avatar
Maxym Borodenko committed
257 258 259 260 261 262 263
  private onSuggestionSelected = (e, data, autocompleteInput, that) => {
    autocompleteInput.onChange.call(that, '');
    const { input } = _.get(this.props, this.props.names[0]);
    input.onChange(this.maybeAdd(data.suggestion.value));
  }

  public render() {
Matija Obreza's avatar
Matija Obreza committed
264
    const { placeholder, label, t, names, terms, classes } = this.props;
Maxym Borodenko's avatar
Maxym Borodenko committed
265 266
    const { input } = _.get(this.props, names[0]);
    const { input: notInput } = _.get(this.props, names[1]);
267
    const {  values, notValues, excludedValues } = this.state;
Maxym Borodenko's avatar
Maxym Borodenko committed
268 269 270 271

    return (
      <div>
          <Field
Matija Obreza's avatar
Matija Obreza committed
272
            name={ `auto-${names[0]}` }
Maxym Borodenko's avatar
Maxym Borodenko committed
273 274 275
            component={ MaterialAutosuggest }
            label={ label }
            placeholder={ placeholder }
276
            onPaste={ this.dataPasted }
Maxym Borodenko's avatar
Maxym Borodenko committed
277 278 279 280 281 282 283
            onChange={ debounce(this.onInputChange, 1000) }
            suggestions={ this.state.autocompleteObj }
            onSuggestionSelected={ this.onSuggestionSelected }
            suggestionLabel="label"
            className="full-width"
           />
        { ((values && values.length > 0) || (notValues && notValues.length > 0)) &&
284
          <StringList input={ input } notInput={ notInput } removeByValue={ this.removeByValue } />
Maxym Borodenko's avatar
Maxym Borodenko committed
285 286 287 288
        }
        { terms &&
          <Properties>
            <h5 className="pl-10 pt-1rem mb-10">{ t('common:f.suggestedFilters') }</h5>
Maxym Borodenko's avatar
Maxym Borodenko committed
289
            { terms && Array.from(terms).slice(0, 10).filter(([key, value]) => excludedValues.length === 0 || !excludedValues.includes(key)).map(([key, value]) => (
Maxym Borodenko's avatar
Maxym Borodenko committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
              <PropertiesItem key={ key } title={ key }  onClick={ () => input.onChange(this.maybeAdd(key)) } classes={ {...classes, propertiesRow: 'cursor-pointer'} }>
                  <span className="float-right">
                    <Number value={ value }/>
                  </span>
              </PropertiesItem>
            )) }
          </Properties>
        }
      </div>
    );
  }
}

interface IAutocompleteFilter extends React.ClassAttributes<any> {
  name: string;
  placeholder?: string;
  label?: string;
  options?: { [key: string]: any; };
  terms?: { [key: string]: any; };
  byKey?: boolean;
  autocomplete: (field: string, term: string, filter: string | AccessionFilter) => Promise<Array<LabelValue<string>>>;
  filterCode: string;
  classes: any;
  t: any;
}

class AutocompleteFilter extends React.Component<IAutocompleteFilter, any> {

  public render() {
    const { name, label, placeholder, options, terms, byKey, autocomplete, filterCode, classes, t } = this.props;
    return (
      <div>
        <Fields
          names={ [`${name}`, `NOT.${name}`] }
          field={ name }
          component={ AutocompleteFilterInternal }
          label={ t(label) }
          placeholder={ placeholder }
          options={ options }
          terms={ terms }
          autocomplete={ autocomplete }
          filterCode={ filterCode }
          byKey={ byKey }
          classes={ classes }
          t={ t }
        />
      </div>
    );
  }
}

Matija Obreza's avatar
Matija Obreza committed
341
export default translate()(AutocompleteFilter);