AutocompleteFilter.tsx 9.85 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
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
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';

interface IStringListProps extends React.ClassAttributes<any> {
  input: any;
  notInput: any;
  removeByIndex: (index: number, isNot: boolean) => void;
}

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() {
    const {removeByIndex} = this.props;
    const {renderList} = this.state;
    return (
      <div>
        { renderList.map((renderItem, index) => (
          <div style={ { margin: '.2rem 0', padding: '.2rem 1rem', backgroundColor: '#e8e5e1', color: '#202222' } } key={ renderItem.value }>
            { renderItem.state ?
              <span className="font-bold float-Left mr-5" onClick={ () => this.addToNotList(renderItem, index) }>+</span>
              :
              <span className="font-bold float-Left mr-5" onClick={ () => this.removeFromNotList(renderItem, index) }>-</span>
            }
            { renderItem.value }
            <div className="font-bold float-right" onClick={ () => removeByIndex(index, !renderItem.state) }>X</div>
          </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 = {
      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({
      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({
      values: [ ...value ],
      notValues: [...notValue],
      text: '',
    });
  }

  private maybeAdd = (...newValues: string[]) => {
    const values = [ ...this.state.values ];

    newValues.forEach((text) => {
      if (text && text.length > 0) {
        if (values.indexOf(text) < 0) {
          values.push(text);
        }
      }
    });

    if (!_.isEqual(values, this.state.values)) {
      this.setState({
        text: '',
        values,
      });
    }
    return values;
  }

  private maybeRemove = (...newValues: string[]) => {
    const values = [ ...this.state.values ];

    newValues.forEach((text) => {
      if (text && text.length > 0) {
        const index: number = values.indexOf(text);
        if (index >= 0) {
          values.splice(index, 1);
        }
      }
    });

    if (!_.isEqual(values, this.state.values)) {
      this.setState({
        text: '',
        values,
      });
    }
    return values;
  }

  private removeByIndex = (index, isNot) => {
    const { input } = _.get(this.props, this.props.names[isNot ? 1 : 0]);
    const newValues = this.maybeRemove(this.state.values[index]);
    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});
              });
          }
        }
      }
    }
  }

  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
231
    const { placeholder, label, t, names, terms, classes } = this.props;
Maxym Borodenko's avatar
Maxym Borodenko committed
232
233
234
235
236
237
238
    const { input } = _.get(this.props, names[0]);
    const { input: notInput } = _.get(this.props, names[1]);
    const { values, notValues } = this.state;

    return (
      <div>
          <Field
Matija Obreza's avatar
Matija Obreza committed
239
            name={ `auto-${names[0]}` }
Maxym Borodenko's avatar
Maxym Borodenko committed
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
295
296
297
298
299
300
301
302
303
304
305
306
            component={ MaterialAutosuggest }
            label={ label }
            placeholder={ placeholder }
            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)) &&
          <StringList input={ input } notInput={ notInput } removeByIndex={ this.removeByIndex } />
        }
        { terms &&
          <Properties>
            <h5 className="pl-10 pt-1rem mb-10">{ t('common:f.suggestedFilters') }</h5>
            { terms && Array.from(terms).slice(0, 10).map(([key, value]) => (
              <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
307
export default translate()(AutocompleteFilter);