StringArrFilter.tsx 16 KB
Newer Older
Maxym Borodenko's avatar
Maxym Borodenko committed
1
import * as React from 'react';
2
import { Fields, change } from 'redux-form';
3 4
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
5
import { translate } from 'react-i18next';
6
import * as _ from 'lodash';
Maxym Borodenko's avatar
Maxym Borodenko committed
7

8 9 10
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormLabel from '@material-ui/core/FormLabel';
Matija Obreza's avatar
Matija Obreza committed
11
import FormControl from '@material-ui/core/FormControl';
Maxym Borodenko's avatar
Maxym Borodenko committed
12

13
import Checkbox from '@material-ui/core/Checkbox';
Matija Obreza's avatar
Matija Obreza committed
14 15 16 17 18
import IconButton from '@material-ui/core/IconButton';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import PlusOne from '@material-ui/icons/PlusOne';
19
import Number from 'ui/common/Number';
20
import { Properties, PropertiesItem } from 'ui/common/Properties';
Maxym Borodenko's avatar
Maxym Borodenko committed
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
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>

        );
    }
}


Maxym Borodenko's avatar
Maxym Borodenko committed
119 120 121 122 123 124
interface IStringArrFilterInternal extends React.ClassAttributes<any> {
    name: string;
    input: any;
    placeholder?: string;
    label?: string;
    options?: { [key: string]: any; };
125
    indented?: boolean;
126
    t: any;
127 128
    addToNotList: (item: any) => void;
    notList: any[];
Maxym Borodenko's avatar
Maxym Borodenko committed
129 130 131 132 133 134
}

class InternalStringArrField extends React.Component<IStringArrFilterInternal & any, any> {

    private constructor(props, context) {
        super(props, context);
135 136
        const notValues = _.get(props, `${props.names[0]}.input.value`);
        const values = _.get(props, `${props.names[1]}.input.value`);
Maxym Borodenko's avatar
Maxym Borodenko committed
137 138

        this.state = {
139 140
            values,
            notValues,
Maxym Borodenko's avatar
Maxym Borodenko committed
141 142 143 144
            text: '',
        };
    }

145
    public componentWillMount() {
146 147 148 149 150 151 152 153 154
        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: '',
        });
155 156
    }

Maxym Borodenko's avatar
Maxym Borodenko committed
157
    public componentWillReceiveProps(nextProps) {
158 159 160 161
        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`);

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

169
    private maybeAdd = (...newValues: string[]) => {
Maxym Borodenko's avatar
Maxym Borodenko committed
170 171
      const values = [ ...this.state.values ];

172 173 174 175 176
      newValues.forEach((text) => {
        if (text && text.length > 0) {
          if (values.indexOf(text) < 0) {
            values.push(text);
          }
Maxym Borodenko's avatar
Maxym Borodenko committed
177
        }
178 179 180
      });

      if (!_.isEqual(values, this.state.values)) {
Maxym Borodenko's avatar
Maxym Borodenko committed
181 182 183 184 185 186 187 188
        this.setState({
          text: '',
          values,
        });
      }
      return values;
    }

189
    private maybeRemove = (...newValues: string[]) => {
Maxym Borodenko's avatar
Maxym Borodenko committed
190 191
      const values = [ ...this.state.values ];

192 193 194 195 196 197
      newValues.forEach((text) => {
        if (text && text.length > 0) {
          const index: number = values.indexOf(text);
          if (index >= 0) {
            values.splice(index, 1);
          }
Maxym Borodenko's avatar
Maxym Borodenko committed
198
        }
199 200 201
      });

      if (!_.isEqual(values, this.state.values)) {
Maxym Borodenko's avatar
Maxym Borodenko committed
202 203 204 205 206 207 208 209 210
        this.setState({
          text: '',
          values,
        });
      }
      return values;
    }

    private handleKeyPres = (event) => {
211
        const { input } = _.get(this.props, this.props.names[0]);
Maxym Borodenko's avatar
Maxym Borodenko committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225
        const { text } = this.state;

        if (event.key === 'Enter') {
          if (text && text.length > 0) {
            event.preventDefault();
            const values = this.maybeAdd(text);
            input.onChange(values);
          } else {
            // on blank, submit it
            // input.onChange(values);
          }
        }
    }

226 227
    private removeByIndex = (index, isNot) => {
        const { input } = _.get(this.props, this.props.names[isNot ? 1 : 0]);
Maxym Borodenko's avatar
Maxym Borodenko committed
228 229 230 231 232 233 234 235 236 237 238

        const newValues = this.maybeRemove(this.state.values[index]);
        input.onChange(newValues);
    }

    // only for the textbox
    private handleChange = (event) => {
        this.setState({ ...this.state, text: event.target.value });
    }

    private handleAddCurrent = (event) => {
239
        const { input } = _.get(this.props, this.props.names[0]);
Maxym Borodenko's avatar
Maxym Borodenko committed
240 241 242 243 244 245 246
        const { text } = this.state;

        event.preventDefault();
        const values = this.maybeAdd(text);
        input.onChange(values);
    }

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 307
    private handleCheckbox = (event) => {
      const { input } = _.get(this.props, this.props.names[0]);
      const value = event.target.value;

      if (this.props.indented) {
        const subCategories = this.getSubcategories(value);
        const values = event.target.checked ? this.maybeAdd(value, ...subCategories) : this.maybeRemove(value);
        input.onChange(values);
      } else {
        const values = event.target.checked ? this.maybeAdd(value) : this.maybeRemove(value);
        input.onChange(values);
      }
    }

    private getSubcategories = (value) => {
      const myRegexp = /^([1-9]+)(0+)$/;
      const match = myRegexp.exec(value);
      const category = match ? match[1] : null;
      const subCategories = [];
      const filteredOptions = this.getFilteredOptions();
      Object.keys(this.props.options).forEach((option) => {
        if (category && option !== value && filteredOptions.indexOf(option) > 0 && option.startsWith(category)) {
          subCategories.push(option);
        }
      });
      return subCategories;
    }

    private getFilteredOptions = () => {
      const { options, byKey, terms, valueField } = this.props;
      const fieldOptions = options && (byKey ? Object.keys(options) : options);
      return terms ? (fieldOptions && fieldOptions.filter((opt) => terms.get(valueField ? opt[valueField] : `${opt}`) > 0)) : fieldOptions;
    }

    private buildMapOfCategories = (map: Map<string, number>, options: string[], level: number) => {
      options.forEach((option) => {
        const subCategories = this.getSubcategories(option);
        if (subCategories.length === 0) {
          if (map.has(option)) {
            const oldLevel = map.get(option);
            if (oldLevel <= level) {
              map.set(option, level);
            }
          } else {
            map.set(option, level);
          }
        } else {
          if (map.has(option)) {
            const oldLevel = map.get(option);
            if (oldLevel <= level) {
              map.set(option, level);
              this.buildMapOfCategories(map, subCategories, level + 1);
            }
          } else {
            map.set(option, level);
            this.buildMapOfCategories(map, subCategories, level + 1);
          }
        }
      });
    }

Maxym Borodenko's avatar
Maxym Borodenko committed
308
    public render() {
309
        const { placeholder, label, options, indented, t, names, terms, valueField, labelField, classes } = this.props;
310 311 312 313
        const { input } = _.get(this.props, names[0]);
        const { input: notInput } = _.get(this.props, names[1]);

        const { text, values, notValues } = this.state;
Maxym Borodenko's avatar
Maxym Borodenko committed
314 315

        const withOptions: boolean = options !== undefined && typeof options === 'object';
316
        const filteredOptions = this.getFilteredOptions();
317

318 319 320 321 322
        let tree;
        if (indented && options) {
          tree = new Map<string, number>();
          this.buildMapOfCategories(tree, Object.keys(options), 0);
        }
Maxym Borodenko's avatar
Maxym Borodenko committed
323 324

        return (
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
          <div>
            { withOptions ?
              (!filteredOptions || filteredOptions.length === 0 ?
                  (<div className="pl-15">{ t('common:f.noFilters') }</div>)
                  : <FormControl fullWidth component={ 'fieldset' as 'div' } className="full-width">
                    { label && <FormLabel component="label">{ label }</FormLabel> }
                    <FormGroup>
                      { filteredOptions.map((key) => (
                        <FormControlLabel
                          key={ `${ key }` } style={ { paddingLeft: `${tree ? (tree.get(key) * 20) : 0}px`, marginRight: 0 } }
                          classes={ {label: 'full-width', root: 'mr-0'} }
                          label={
                            <span className="full-width" style={ {display: 'flex', justifyContent: 'space-between'} }>
                              { `${ t(options[key]) || (labelField ? key[labelField] : key) }` }
                              { terms &&
                              <span className="float-right">
                                <Number value={ terms.get(valueField ? `${ key[valueField] }` : `${ key }`) }/>
                              </span>
                              }
                              </span>
                          }
                          control={
                            <Checkbox
                              value={ valueField ? `${ key[valueField] }` :  key }
                              checked={ values.indexOf(valueField ? `${ key[valueField] }` :  key) >= 0 }
                              onChange={ this.handleCheckbox }
                            />
                          }
                        />
                      )) }
                      </FormGroup>
                  </FormControl>
              ) :
Maxym Borodenko's avatar
Maxym Borodenko committed
358
                  <FormControl fullWidth className="full-width">
359
                    <InputLabel>{ t(`${label}`) }</InputLabel>
Maxym Borodenko's avatar
Maxym Borodenko committed
360 361 362 363
                    <Input
                      className="full-width"
                      value={ text }
                      onChange={ this.handleChange }
364
                      placeholder={ placeholder ? t(`${placeholder}`) : '' }
Maxym Borodenko's avatar
Maxym Borodenko committed
365 366 367 368 369
                      onKeyPress={ this.handleKeyPres }
                      onBlur={ this.handleAddCurrent }
                      endAdornment={
                        <InputAdornment position="end">
                          <IconButton type="button" onClick={ this.handleAddCurrent }>
Maxym Borodenko's avatar
Maxym Borodenko committed
370
                            <PlusOne style={ { fontSize: '1.5rem' } } />
Maxym Borodenko's avatar
Maxym Borodenko committed
371 372 373 374 375 376
                          </IconButton>
                        </InputAdornment>
                      }
                    />
                  </FormControl>
                }
377 378 379
                { (! withOptions && ((values && values.length > 0) || (notValues && notValues.length > 0))) &&
                <StringList input={ input } notInput={ notInput } removeByIndex={ this.removeByIndex } />
                }
380 381 382 383
                { !withOptions && 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]) => (
384
                        <PropertiesItem key={ key } title={ key }  onClick={ () => input.onChange(this.maybeAdd(key)) } classes={ {...classes, propertiesRow: 'cursor-pointer'} }>
385 386 387 388 389 390 391 392
                            <span className="float-right">
                                <Number value={ value }/>
                            </span>
                        </PropertiesItem>
                    )) }
                </Properties>
                }

Maxym Borodenko's avatar
Maxym Borodenko committed
393 394 395 396 397 398 399 400 401 402
            </div>
        );
    }
}

interface IStringArrFilter extends React.ClassAttributes<any> {
    name: string;
    placeholder?: string;
    label?: string;
    options?: { [key: string]: any; };
403 404 405 406
    terms?: { [key: string]: any; };
    valueField?: string;
    labelField?: string;
    byKey?: boolean;
407
    classes: any;
408
    indented?: boolean;
409
    t: any;
Maxym Borodenko's avatar
Maxym Borodenko committed
410 411 412 413 414 415
}

class StringArrFilter extends React.Component<IStringArrFilter, any> {


    public render() {
416
        const { name, label, placeholder, options, indented, terms, valueField, labelField, byKey, classes, t } = this.props;
Maxym Borodenko's avatar
Maxym Borodenko committed
417 418
        return (
            <div>
419 420
                <Fields
                    names={ [`${name}`, `NOT.${name}`] }
Maxym Borodenko's avatar
Maxym Borodenko committed
421
                    component={ InternalStringArrField }
Viacheslav Pavlov's avatar
i18n  
Viacheslav Pavlov committed
422
                    label={ t(label) }
Maxym Borodenko's avatar
Maxym Borodenko committed
423 424
                    placeholder={ placeholder }
                    options={ options }
425 426 427 428
                    terms={ terms }
                    valueField={ valueField }
                    labelField={ labelField }
                    byKey={ byKey }
429
                    classes={ classes }
430
                    indented={ indented }
431
                    t={ t }
Maxym Borodenko's avatar
Maxym Borodenko committed
432 433 434 435 436 437
                />
            </div>
        );
    }
}

438 439 440 441 442 443 444

const mapDispatchToProps = (dispatch) => bindActionCreators({
  change,
}, dispatch);


export default connect(null, mapDispatchToProps)(translate()(StringArrFilter));