All files / boundless/packages/boundless-tokenized-input index.js

94.57% Statements 87/92
87.27% Branches 48/55
96.67% Functions 29/30
94.25% Lines 82/87
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 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 231 232 233 234 235 236 237 238 239 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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329              8x 15x 35x                                                                                                                                                                                 17x 17x   17x 1x     17x           17x   9x   8x 1x 1x               13x 13x 2x 7x 3x 4x     3x       6x 6x     6x       3x       5x       4x 4x   4x 1x     3x 1x   2x   2x         4x 4x   4x       4x 1x 1x   3x   3x         24x       2x   2x 1x         21x   21x 1x         12x   4x 4x     4x 4x     1x 1x 1x     1x     2x 2x   2x 2x     2x   2x       12x 1x           1x   1x 1x   1x           82x 81x               4x     2x 2x 2x     2x 2x 2x 2x         67x     82x                                       67x                                              
import React, {PropTypes} from 'react';
import cx from 'classnames';
 
import Typeahead from 'boundless-typeahead';
import extractChildProps from 'boundless-utils-object-intersection';
import omit from 'boundless-utils-omit-keys';
 
const first = (array) => array[0];
const last = (array) => array[array.length - 1];
const isFunction = (x) => typeof x === 'function';
 
/**
__Distill rich entity data matched via typeahead input into simple visual abstractions.__
 
Basic usage of this component is identical to that of [Typeahead](https://github.com/enigma-io/boundless/master/packages/boundless-typeahead). Additional props are available to take advantage of the tokenization functionality.
 
## Component Instance Methods
 
When using `TokenizedInput` in your project, you may call the following methods on a rendered instance of the component. Use [`refs`](https://facebook.github.io/react/docs/refs-and-the-dom.html) to get the instance.
 
- __`add(index: number)`__
  programmatically creates a token for `props.entities[index]`; `props.handleAddToken` will be called as a hint to persist the change in your controller view or other application state
 
- __`focus()`__
  focuses the browser oon the underlying textual input for immediate text entry
 
- __`getInputNode()`__
  returns the raw underlying textual input DOM node
 
- __`getSelectedEntityText()`__
  returns the `text` property of the currently highlighted entity (from `props.entities`), or returns an empty string
 
- __`getValue()`__
  retrieves the current value of the underlying textual input
 
- __`remove(index: number)`__
  programmatically removes the token for `props.entities[index]`; `props.handleRemoveTokens` will be called as a hint to persist the change in your controller view or other application state
 
- __`select()`__
  programmatically creates a full selection on the underlying textual input such that a press of the Backspace key would fully clear the input
 
- __`setValue(value: string)`__
  sets the underlying textual input to the specified text and updates internal state; do not use this method when using `Typeahead` as a "controlled input"
 */
export default class TokenizedInput extends React.PureComponent {
    static propTypes = {
        ...Typeahead.propTypes,
 
        /**
         * function handler that is called when an entity is selected by the user and a token should be created
         */
        handleAddToken: PropTypes.func,
 
        /**
         * function handler that is called when one or more tokens are removed by the user via clicking the "close" button or pressing the `Backspace` key while tokens are selected
         */
        handleRemoveTokens: PropTypes.func,
 
        /**
         * function handler that is called when one or more tokens are selected by the user via click or keyboard actions; called with what the new selection should be
         */
        handleNewSelection: PropTypes.func,
 
        /**
         * the JSX used for the close button itself
         */
        tokenCloseComponent: PropTypes.element,
 
        /**
         * determines if the `.b-tokenfield-token-close` element should be rendered for each token
         */
        tokenCloseVisible: PropTypes.bool,
 
        /**
         * the indexes of entities that should be rendered as "tokens" in the component UI
         */
        tokens: PropTypes.arrayOf(PropTypes.number),
 
        /**
         * the indexes of tokenized entities that are part of an active selection; the user can press `Backspace` to trigger `handleRemoveTokens`
         */
        tokensSelected: PropTypes.arrayOf(PropTypes.number),
    }
 
    static defaultProps = {
        ...Typeahead.defaultProps,
        handleAddToken: () => {},
        handleRemoveTokens: () => {},
        handleNewSelection: () => {},
        tokenCloseComponent: (<div>X</div>),
        tokenCloseVisible: true,
        tokens: [],
        tokensSelected: [],
    }
 
    static internalKeys = Object.keys(TokenizedInput.defaultProps)
 
    componentDidUpdate(prevProps) {
        const previousSelectedIndexes = prevProps.tokensSelected;
        const currentSelectedIndexes = this.props.tokensSelected;
 
        if (this.props.tokens.length > prevProps.tokens.length) {
            this.setValue('');
        }
 
        Iif (this._suppressNextTokenSelection) {
            this._suppressNextTokenSelection = false;
 
            return;
        }
 
        if (   previousSelectedIndexes !== currentSelectedIndexes
            && currentSelectedIndexes.length !== 0) {
            if (   currentSelectedIndexes.length === 1
                       || currentSelectedIndexes[0] !== previousSelectedIndexes[0] /* multi selection, leftward */) {
                return this.refs[`token_${currentSelectedIndexes[0]}`].focus();
            } else Eif (last(currentSelectedIndexes) !== last(previousSelectedIndexes) /* multi selection, rightward */) {
                return this.refs[`token_${last(currentSelectedIndexes)}`].focus();
            }
 
            this.refs[`token_${currentSelectedIndexes[0]}`].focus();
        } // move focus
    }
 
    // passthroughs to Typeahead instance methods
    focus = () => this.refs.typeahead.focus()
    getInputNode = () => this.refs.typeahead.getInputNode()
    getSelectedEntityText = () => this.refs.typeahead.getSelectedEntityText()
    getValue = () => this.refs.typeahead.getValue()
    select = () => this.refs.typeahead.select()
    setValue = (value) => this.refs.typeahead.setValue(value)
 
    add = (index) => {
        if (this.props.tokens.indexOf(index) === -1) { this.props.handleAddToken(index); }
    }
 
    remove(index) {
        const indexes = (Array.isArray(index) ? index : [index]).filter((idx) => {
            return this.props.tokens.indexOf(idx) !== -1;
        });
 
        if (indexes.length) { this.props.handleRemoveTokens(indexes); }
    }
 
    selectToken(index) {
        this.props.handleNewSelection([index]);
    }
 
    selectTokens(indexes) {
        this.props.handleNewSelection(indexes);
    }
 
    selectPreviousToken(append) {
        const selected = this.props.tokensSelected;
        const indexes = this.props.tokens;
 
        if (selected.length === 1 && first(selected) === first(indexes)) {
            return; // already at leftmost bound
        }
 
        if (selected.length === 0) { // pick the rightmost
            this.selectToken(last(indexes));
        } else { // add the next leftmost to a reconstructed "selected" array
            const previousToken = indexes[indexes.indexOf(first(selected)) - 1];
 
            this.selectTokens(append ? [previousToken].concat(selected) : [previousToken]);
        }
    }
 
    selectNextToken(append) {
        const selected = this.props.tokensSelected;
        const indexes = this.props.tokens;
 
        Iif (selected.length === 0) {
            return;
        }
 
        if (last(selected) === last(indexes)) {
            this.clearSelection();
            this.focus();
        } else {
            const nextToken = indexes[indexes.indexOf(last(selected)) + 1];
 
            this.selectTokens(append ? selected.concat(nextToken) : [nextToken]);
        }
    }
 
    clearSelection() {
        this.props.handleNewSelection([]);
    }
 
    handleInputClick = (event) => {
        this.clearSelection();
 
        if (isFunction(this.props.inputProps.onClick)) {
            this.props.inputProps.onClick(event);
        }
    }
 
    handleInputFocus = (event) => {
        this.clearSelection();
 
        if (isFunction(this.props.inputProps.onFocus)) {
            this.props.inputProps.onFocus(event);
        }
    }
 
    handleKeyDown = (event) => {
        switch (event.which) {
        case 37:    // left arrow
            this.selectPreviousToken(event.shiftKey);
            break;
 
        case 39:    // right arrow
            this.selectNextToken(event.shiftKey);
            break;
 
        case 8:     // backspace
            Eif (this.props.tokensSelected.length) {
                this.remove(this.props.tokensSelected);
                this.focus();
            }
 
            break;
 
        case 65:    // letter "a"
            Eif (event.metaKey) {
                event.preventDefault();
 
                this.focus();
                this.select();
 
                // hacky, but the only way unless we move selection management internal again
                this._suppressNextTokenSelection = true;
 
                this.props.handleNewSelection(this.props.tokens);
            } // "cmd"
        }
 
        if (isFunction(this.props.onKeyDown)) {
            this.props.onKeyDown(event);
        }
    }
 
    handleTokenCloseClick(index, event) {
        // if we don't stop propagation, the event bubbles and results in a failed token selection
        event.stopPropagation();
 
        this.remove(index);
        this.focus();
 
        Iif (this.props.tokenCloseComponent.props.onClick) {
            this.props.tokenCloseComponent.props.onClick(event);
        }
    }
 
    renderTokenClose(index) {
        if (this.props.tokenCloseVisible) {
            return React.cloneElement(this.props.tokenCloseComponent, {
                className: cx('b-tokenfield-token-close', this.props.tokenCloseComponent.props.className),
                onClick: this.handleTokenCloseClick.bind(this, index),
            });
        }
    }
 
    handleTokenKeyDown(index, event) {
        switch (event.which) {
        case 13: // enter
        case 32: // space
            this.selectToken(index);
            event.preventDefault();
            break;
 
        case 8: // backspace
            this.remove(index);
            this.focus();
            event.preventDefault();
            break;
        }
    }
 
    renderTokens() {
        return (
            <div className='b-tokenfield-tokens'>
                {this.props.tokens.map((index) => {
                    return (
                        <div
                            ref={`token_${index}`}
                            key={index}
                            className={cx('b-tokenfield-token', {
                               'b-tokenfield-token-selected': this.props.tokensSelected.indexOf(index) !== -1,
                            })}
                            onClick={this.selectToken.bind(this, index)}
                            onKeyDown={this.handleTokenKeyDown.bind(this, index)}
                            tabIndex='0'>
                            {this.props.entities[index].text}
                            {this.renderTokenClose(index)}
                        </div>
                    );
                })}
            </div>
        );
    }
 
    render() {
        return (
            <div
                {...omit(this.props, TokenizedInput.internalKeys)}
                ref='wrapper'
                className={cx('b-tokenfield-wrapper', this.props.className)}
                onKeyDown={this.handleKeyDown}>
                {this.renderTokens()}
 
                <Typeahead
                    {...extractChildProps(this.props, Typeahead.defaultProps)}
                    ref='typeahead'
                    className='b-tokenfield'
                    clearOnSelection={true}
                    inputProps={{
                        ...this.props.inputProps,
                        onClick: this.handleInputClick,
                        onFocus: this.handleInputFocus,
                    }}
                    onEntitySelected={this.add} />
            </div>
        );
    }
}