StringArrFilter.tsx 12.9 KB
Newer Older
Maxym Borodenko's avatar
Maxym Borodenko committed
1
import * as React from 'react';
2
import { Fields, change, FieldArray } 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

Matija Obreza's avatar
Matija Obreza committed
8
import FormControl from '@material-ui/core/FormControl';
Maxym Borodenko's avatar
Maxym Borodenko committed
9

Matija Obreza's avatar
Matija Obreza committed
10 11 12 13 14
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';
15 16 17
import CheckboxSelection from '../forms/CheckboxSelection';
import Number from 'ui/common/Number';
import {Properties, PropertiesItem} from 'ui/common/Properties';
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 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
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
116 117 118 119 120 121
interface IStringArrFilterInternal extends React.ClassAttributes<any> {
    name: string;
    input: any;
    placeholder?: string;
    label?: string;
    options?: { [key: string]: any; };
122
    t: any;
123 124
    addToNotList: (item: any) => void;
    notList: any[];
Maxym Borodenko's avatar
Maxym Borodenko committed
125 126 127 128 129 130
}

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

    private constructor(props, context) {
        super(props, context);
131 132
        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
133 134

        this.state = {
135 136
            values,
            notValues,
Maxym Borodenko's avatar
Maxym Borodenko committed
137 138 139 140
            text: '',
        };
    }

141
    public componentWillMount() {
142 143 144 145 146 147 148 149 150
        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: '',
        });
151 152
    }

Maxym Borodenko's avatar
Maxym Borodenko committed
153
    public componentWillReceiveProps(nextProps) {
154 155 156 157
        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
158
        this.setState({
159
            values: [ ...value ],
160
            notValues: [...notValue],
Maxym Borodenko's avatar
Maxym Borodenko committed
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
            text: '',
        });
    }

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

      if (text && text.length > 0) {
        if (values.indexOf(text) < 0) {
          values.push(text);
        }
        this.setState({
          text: '',
          values,
        });
      }
      return values;
    }

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

      if (text && text.length > 0) {
        const index: number = values.indexOf(text);
        if (index >= 0) {
          values.splice(index, 1);
        }
        this.setState({
          text: '',
          values,
        });
      }
      return values;
    }

    private handleKeyPres = (event) => {
197
        const { input } = _.get(this.props, this.props.names[0]);
Maxym Borodenko's avatar
Maxym Borodenko committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211
        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);
          }
        }
    }

212 213
    private removeByIndex = (index, isNot) => {
        const { input } = _.get(this.props, this.props.names[isNot ? 1 : 0]);
Maxym Borodenko's avatar
Maxym Borodenko committed
214 215 216 217 218 219 220 221 222 223 224

        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) => {
225
        const { input } = _.get(this.props, this.props.names[0]);
Maxym Borodenko's avatar
Maxym Borodenko committed
226 227 228 229 230 231 232 233
        const { text } = this.state;

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

    public render() {
234
        const { placeholder, label, options, t, names, terms, valueField, labelField, byKey, classes } = this.props;
235 236 237 238
        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
239 240

        const withOptions: boolean = options !== undefined && typeof options === 'object';
241 242 243 244
        const fieldOptions = options &&  (byKey ? Object.keys(options).map((val) => +val) : options);

        const filteredOptions  = terms ? (fieldOptions && fieldOptions.filter((opt) => terms.get(valueField ? opt[valueField] : `${opt}`) > 0)) : fieldOptions;

Maxym Borodenko's avatar
Maxym Borodenko committed
245 246 247 248

        return (
            <div>
                { withOptions ?
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
                    (!filteredOptions || filteredOptions.length === 0 ?
                        (<div className="pl-15">{ t('common:f.noFilters') }</div>)
                        :
                        (<FieldArray
                            formLabel={ label }
                            name={ names[0] }
                            singleColumn
                            component={ CheckboxSelection }
                            valueField={ valueField }
                            options={ filteredOptions }
                            classes={ {label: 'full-width'} }
                            renderOptionLabel={ (opt) =>
                                <span className="full-width" style={ {display: 'flex', justifyContent: 'space-between'} }>
                                    { `${t(options[opt]) || (labelField ? opt[labelField] : opt)}` }
                                    { terms &&
                                        <span className="float-right">
                                            <Number value={ terms.get(valueField ? `${opt[valueField]}` : `${opt}`) }/>
                                        </span>
                                    }
                                </span>
                            }
                        />)
                    )
Maxym Borodenko's avatar
Maxym Borodenko committed
272 273
                  :
                  <FormControl fullWidth className="full-width">
274
                    <InputLabel>{ t(`${label}`) }</InputLabel>
Maxym Borodenko's avatar
Maxym Borodenko committed
275 276 277 278
                    <Input
                      className="full-width"
                      value={ text }
                      onChange={ this.handleChange }
279
                      placeholder={ placeholder ? t(`${placeholder}`) : '' }
Maxym Borodenko's avatar
Maxym Borodenko committed
280 281 282 283 284
                      onKeyPress={ this.handleKeyPres }
                      onBlur={ this.handleAddCurrent }
                      endAdornment={
                        <InputAdornment position="end">
                          <IconButton type="button" onClick={ this.handleAddCurrent }>
Maxym Borodenko's avatar
Maxym Borodenko committed
285
                            <PlusOne style={ { fontSize: '1.5rem' } } />
Maxym Borodenko's avatar
Maxym Borodenko committed
286 287 288 289 290 291
                          </IconButton>
                        </InputAdornment>
                      }
                    />
                  </FormControl>
                }
292 293 294
                { (! withOptions && ((values && values.length > 0) || (notValues && notValues.length > 0))) &&
                <StringList input={ input } notInput={ notInput } removeByIndex={ this.removeByIndex } />
                }
295 296 297 298
                { !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]) => (
299
                        <PropertiesItem key={ key } title={ key }  onClick={ () => input.onChange(this.maybeAdd(key)) } classes={ {...classes, propertiesRow: 'cursor-pointer'} }>
300 301 302 303 304 305 306 307
                            <span className="float-right">
                                <Number value={ value }/>
                            </span>
                        </PropertiesItem>
                    )) }
                </Properties>
                }

Maxym Borodenko's avatar
Maxym Borodenko committed
308 309 310 311 312 313 314 315 316 317
            </div>
        );
    }
}

interface IStringArrFilter extends React.ClassAttributes<any> {
    name: string;
    placeholder?: string;
    label?: string;
    options?: { [key: string]: any; };
318 319 320 321
    terms?: { [key: string]: any; };
    valueField?: string;
    labelField?: string;
    byKey?: boolean;
322
    classes: any;
323
    t: any;
Maxym Borodenko's avatar
Maxym Borodenko committed
324 325 326 327 328 329
}

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


    public render() {
330
        const { name, label, placeholder, options, terms, valueField, labelField, byKey, classes, t } = this.props;
Maxym Borodenko's avatar
Maxym Borodenko committed
331 332
        return (
            <div>
333 334
                <Fields
                    names={ [`${name}`, `NOT.${name}`] }
Maxym Borodenko's avatar
Maxym Borodenko committed
335
                    component={ InternalStringArrField }
Viacheslav Pavlov's avatar
i18n  
Viacheslav Pavlov committed
336
                    label={ t(label) }
Maxym Borodenko's avatar
Maxym Borodenko committed
337 338
                    placeholder={ placeholder }
                    options={ options }
339 340 341 342
                    terms={ terms }
                    valueField={ valueField }
                    labelField={ labelField }
                    byKey={ byKey }
343
                    classes={ classes }
344
                    t={ t }
Maxym Borodenko's avatar
Maxym Borodenko committed
345 346 347 348 349 350
                />
            </div>
        );
    }
}

351 352 353 354 355 356 357

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


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