xsnippet logotype

xsnippet

#363694, Untitled [ JavaScript ]

by Guest
 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
import React from 'react';
import { Scrollbars } from 'react-custom-scrollbars';
import { connect } from 'react-redux';

import * as actions from '../actions';

class Syntaxes extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = { activeIndex: -1, inputVal: '' };
    this.onClickHandler = this.onClickHandler.bind(this);
    this.onSyntaxSearch = this.onSyntaxSearch.bind(this);
    this.filterSyntaxes = this.filterSyntaxes.bind(this);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch(actions.fetchSyntaxes);
  }

  onClickHandler(e) {
    const { index, syntax } = e.target.dataset;

    this.setState({ activeIndex: Number(index) });
    this.props.onClick(syntax);
  }

  onSyntaxSearch(e) {
    this.setState({ inputVal: e.target.value });
  }

  filterSyntaxes() {
    const filteredSyntaxes = this.props.syntaxes.filter((syntax, index) => syntax.indexOf(this.state.inputVal) !== -1);

    return filteredSyntaxes.map((syntax, index) => {
      const active = this.state.activeIndex === index ? 'active' : '';
      return (
        <li
          className={`new-snippet-lang-item ${active}`}
          data-syntax={syntax}
          data-index={index}
          key={syntax}
        >
          {syntax}
        </li>
        );
      })
  }

  render() {
    return (
      [
        <div className="new-snippet-lang-header" key="Syntax input">
          <input className="input" placeholder="Type to search..." value={this.state.inputVal} onChange={this.onSyntaxSearch} />
        </div>,
        <div className="new-snippet-lang-list-wrapper" key="Syntax list">
          <Scrollbars>
            <ul className="new-snippet-lang-list" onClick={this.onClickHandler} role="presentation">
              {this.filterSyntaxes()}
            </ul>
          </Scrollbars>
        </div>,
      ]
    );
  }
}

export default connect(state => ({
  syntaxes: state.syntaxes,
}))(Syntaxes);