Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-customize-token-input

Package Overview
Dependencies
Maintainers
1
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-customize-token-input - npm Package Compare versions

Comparing version 0.5.2 to 1.2.1

lib/index.js.LICENSE.txt

1163

lib/index.js

@@ -1,1162 +0,3 @@

/*! react-customize-token-input v0.5.2 | (c) 2018 Mark Lin. | MIT | https://github.com/seawind543/react-token-input */
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 6);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("react");
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = require("prop-types");
/***/ }),
/* 2 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
module.exports = {"container":"customize-token-input---container---32eEd","focused":"customize-token-input---focused---2EN4q","errors":"customize-token-input---errors---1qMJA","token-list":"customize-token-input---token-list---5WBoW","tokenList":"customize-token-input---token-list---5WBoW","token":"customize-token-input---token---2ASwp","active":"customize-token-input---active---30GFu","error":"customize-token-input---error---1c3qq","read-only":"customize-token-input---read-only---2A6-P","readOnly":"customize-token-input---read-only---2A6-P","label-wrapper":"customize-token-input---label-wrapper---2CrTg","labelWrapper":"customize-token-input---label-wrapper---2CrTg","delete-button":"customize-token-input---delete-button---3A_UK","deleteButton":"customize-token-input---delete-button---3A_UK","autosized-wrapper":"customize-token-input---autosized-wrapper---33t7e","autosizedWrapper":"customize-token-input---autosized-wrapper---33t7e"};
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("classnames");
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("react-input-autosize");
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Default function for TokenInput to build user input value into default data structure
* buildDataFromValue(value)
*
* @ value
* Type: string
* Description: user input value // (value are the input string separate by separators)
*
* @ return
* Type: string
* Description: default data structure
*/
var buildDataFromValue = exports.buildDataFromValue = function buildDataFromValue(value) {
return value.trim();
};
/**
* Default function for TokenInput to get value from customize data structure for user to perform "edit"
* dataValue(data)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ return
* Type: string
* Description: The value for user to edit
*/
var getDataValue = exports.getDataValue = function getDataValue(value) {
return value;
};
/**
* Function for TokenInput to build default token data with user's customize data
* dataItemToTokenData(userData, index)
*
* @ userData
* Type: object || string || number
* Description: user's customize data
*
* @ index
* Type: number
* Description: array index for this customize data in data array
*
* @ return
* Type: object
* Description: token data
*/
var dataItemToTokenData = exports.dataItemToTokenData = function dataItemToTokenData(item, index) {
return {
value: item,
meta: {
key: JSON.stringify(item) + "-" + Date.now() + "-" + index,
activated: false,
error: null
}
};
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _TokenInput = __webpack_require__(7);
var _TokenInput2 = _interopRequireDefault(_TokenInput);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _TokenInput2.default;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(1);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _TokenCreator = __webpack_require__(8);
var _TokenCreator2 = _interopRequireDefault(_TokenCreator);
var _Token = __webpack_require__(9);
var _Token2 = _interopRequireDefault(_Token);
var _utils = __webpack_require__(5);
var _styles = __webpack_require__(2);
var _styles2 = _interopRequireDefault(_styles);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TokenInput = function (_PureComponent) {
_inherits(TokenInput, _PureComponent);
function TokenInput(props) {
_classCallCheck(this, TokenInput);
var _this = _possibleConstructorReturn(this, (TokenInput.__proto__ || Object.getPrototypeOf(TokenInput)).call(this, props));
_this.actions = {
keepFocus: function keepFocus() {
_this.tokenCreator && _this.tokenCreator.focus();
},
onFocus: function onFocus(e) {
_this.setState({ focused: true });
},
onBlur: function onBlur(e) {
_this.setState({ focused: false });
},
updateTokens: function updateTokens(tokens) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _options$keepFocus = options.keepFocus,
keepFocus = _options$keepFocus === undefined ? false : _options$keepFocus;
var hasInvalid = false;
var values = tokens.map(function (token) {
return token.value;
});
var newTokens = tokens.map(function (token, index, tokens) {
var newToken = _extends({}, token);
newToken.meta.error = _this.props.validator(token.value, index, values);
if (newToken.meta.error && !newToken.meta.activated) {
hasInvalid = true;
}
return newToken;
});
_this.setState({
tokens: newTokens,
error: hasInvalid
}, function () {
if (keepFocus === true) {
_this.actions.keepFocus();
}
// TODO: Fix me.
// onDataUpdate?
_this.props.onTokensUpdate(newTokens);
});
},
onStartEditToken: function onStartEditToken(index) {
return function () {
var tokens = [].concat(_toConsumableArray(_this.state.tokens));
tokens[index].meta.activated = true;
_this.actions.updateTokens(tokens);
};
},
onEndEditToken: function onEndEditToken(index) {
return function (data) {
var tokens = [].concat(_toConsumableArray(_this.state.tokens));
tokens[index].meta.activated = false;
if (typeof data !== 'undefined') {
tokens[index].value = data;
}
_this.actions.updateTokens(tokens);
};
},
onDeleteToken: function onDeleteToken(index) {
return function () {
_this.actions.deleteToken(index);
};
},
onDeleteLastToken: function onDeleteLastToken() {
_this.actions.deleteToken(-1);
},
deleteToken: function deleteToken(index) {
var tokens = [].concat(_toConsumableArray(_this.state.tokens));
tokens.splice(index, 1);
_this.actions.updateTokens(tokens, { keepFocus: true });
},
onAddTokens: function onAddTokens() {
var newTokens = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
if (newTokens.length > 0) {
// avoid meaningless update
var tokens = [].concat(_toConsumableArray(_this.state.tokens), _toConsumableArray(newTokens));
_this.actions.updateTokens(tokens, { keepFocus: true });
}
},
tokenCreatePreprocessor: function tokenCreatePreprocessor(inputValues) {
var preprocessor = _this.props.preprocessor;
if (typeof preprocessor === 'function') {
var values = preprocessor(inputValues);
if (Array.isArray(values) !== true) {
throw new Error('prop preprocessor should return array of values');
}
return values;
}
return inputValues;
}
};
_this.state = {
focused: false,
error: false,
tokens: []
};
return _this;
}
_createClass(TokenInput, [{
key: 'componentDidMount',
value: function componentDidMount() {
var tokens = this.props.defaultData.map(_utils.dataItemToTokenData);
this.actions.updateTokens(tokens);
}
}, {
key: 'render',
value: function render() {
var _classNames,
_this2 = this;
var _props = this.props,
className = _props.className,
readOnly = _props.readOnly,
placeholder = _props.placeholder,
autoFocus = _props.autoFocus,
separators = _props.separators,
buildDataFromValue = _props.buildDataFromValue,
dataValue = _props.dataValue,
tokenClassName = _props.tokenClassName,
tokenLabelRender = _props.tokenLabelRender,
tokenErrorMessage = _props.tokenErrorMessage,
tokenRender = _props.tokenRender,
onInputValueChange = _props.onInputValueChange,
props = _objectWithoutProperties(_props, ['className', 'readOnly', 'placeholder', 'autoFocus', 'separators', 'buildDataFromValue', 'dataValue', 'tokenClassName', 'tokenLabelRender', 'tokenErrorMessage', 'tokenRender', 'onInputValueChange']);
var _state = this.state,
focused = _state.focused,
error = _state.error,
tokens = _state.tokens;
// Remove un-render-able props
delete props.defaultData;
delete props.preprocessor;
delete props.validator;
delete props.onTokensUpdate;
var customizeToken = typeof tokenRender === 'function';
return _react2.default.createElement(
'div',
_extends({}, props, {
className: (0, _classnames2.default)(className, _styles2.default.container, (_classNames = {}, _defineProperty(_classNames, _styles2.default.focused, focused), _defineProperty(_classNames, _styles2.default.errors, error), _classNames)),
onClick: this.actions.keepFocus,
role: 'presentation'
}),
_react2.default.createElement(
'div',
{ className: _styles2.default['token-list'] },
customizeToken && tokens.map(function (token, index) {
var key = token.meta.key;
return tokenRender({
key: key,
readOnly: readOnly,
data: token.value,
meta: token.meta,
onStartEdit: _this2.actions.onStartEditToken(index),
onEndEdit: _this2.actions.onEndEditToken(index),
onDelete: _this2.actions.onDeleteToken(index)
});
}),
!customizeToken && tokens.map(function (token, index) {
var key = token.meta.key;
return _react2.default.createElement(_Token2.default, {
key: key,
readOnly: readOnly,
buildDataFromValue: buildDataFromValue,
dataValue: dataValue,
tokenClassName: tokenClassName,
tokenLabelRender: tokenLabelRender,
tokenErrorMessage: tokenErrorMessage,
data: token,
onStartEdit: _this2.actions.onStartEditToken(index),
onEndEdit: _this2.actions.onEndEditToken(index),
onDelete: _this2.actions.onDeleteToken(index)
});
})
),
!readOnly && _react2.default.createElement(_TokenCreator2.default, {
ref: function ref(node) {
_this2.tokenCreator = node;
},
placeholder: placeholder,
autoFocus: autoFocus,
onFocus: this.actions.onFocus,
onBlur: this.actions.onBlur,
onInputValueChange: onInputValueChange,
preprocessor: this.actions.tokenCreatePreprocessor,
separators: separators
// reproduceValue={reproduceValue}
, buildDataFromValue: buildDataFromValue,
addTokens: this.actions.onAddTokens,
onDeleteLastToken: this.actions.onDeleteLastToken
})
);
}
}]);
return TokenInput;
}(_react.PureComponent);
TokenInput.propTypes = {
// style: PropTypes.object,
className: _propTypes2.default.string,
// Specific TokenInput is readOnly or not
readOnly: _propTypes2.default.bool,
// placeholder of TokenInput
placeholder: _propTypes2.default.string,
// Specific TokenInput should be autoFocus or not
autoFocus: _propTypes2.default.bool,
// data for TokenInput to build pre-set tokens. Default is empty array
defaultData: _propTypes2.default.array,
/**
* Array of characters for separate user input string.
* For example, separate user input string 'abc;def' into [abc, def] by separators [';']
*/
separators: _propTypes2.default.array,
/**
* function for pre-process user input values.
*
* Case 1:
* Make your normalize process in this function, such as trim.
*
* Case 2:
* Sometimes, we will want to auto-fit user input, this function could help on it.
* For example, user input is 'www.google.com',
* and we want to auto fit it into 'http://www.google.com' and 'https://www.google.com'
*
* preprocessor(values)
*
* @ values
* Type: array of string values
* Description: user input values // (values that input string separate by separators)
*
* @ return
* Type: array of string values
* Description: values after pre-process
*/
preprocessor: _propTypes2.default.func,
/**
* function for TokenInput to build user input value into customize data structure.
* You could make your normalize process in this function too.
* buildDataFromValue(value)
*
* @ value
* Type: string
* Description: user input value // (value are the input string separate by separators)
*
* @ return
* Type: object || string || number
* Description: customize data
*/
buildDataFromValue: _propTypes2.default.func,
/**
* function for TokenInput to get value from customize data structure for user to perform "edit"
* dataValue(data)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ return
* Type: string
* Description: The value for user to edit
*/
dataValue: _propTypes2.default.func,
/**
* function for TokenInput to get className for a token
* tokenClassName(data, meta)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ meta
* Description: token's meta data
* {
* key, // private key for render
* activated, // Boolean; Specific the token is activated for edit or not
* error // null or ERROR object. Specific the token's validate status
* }
*
*
* @ return
* Type: string
* Description: The className
*/
tokenClassName: _propTypes2.default.func,
/**
* A token label renderer for TokenInput to rendering a token's content part (label)
* Apply this to customize token's content. For example render token with "icon and text".
* tokenLabelRender(data)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ return
* Type: string || node
* Description: The token's content. By default, will apply dataValue()
*/
tokenLabelRender: _propTypes2.default.func,
/**
* function for TokenInput to get error message from customize error
* The "customize error" is generate by "validator" function
* tokenErrorMessage(error)
*
* @ error
* Type: customize error
* Description: customize error
*
* @ return
* Type: string
* Description: The error message to describe an invalidte token
*/
tokenErrorMessage: _propTypes2.default.func,
/**
* A token renderer for TokenInput to rendering a token
* Apply this to customize all token.
* tokenRender(props)
*
* @ props.key
* Type: string
* Description: Each child in an array or iterator should have a unique "key" prop.
*
* @ props.data
* Type: object || string || number
* Description: customize data onject
*
* @ props.meta
* Description: token's meta data
* {
* key, // private key for render
* activated, // Boolean; Specific the token is activated for edit or not
* error // null or ERROR object. Specific the token's validate status
* }
*
* @ props.readOnly
* Type: boolean
* Description: Is readOnly or not
*
* @ props.onStartEdit
* Type: function
* Description: Callback function invoked when user start edit the token
*
* @ props.onEndEdit(data)
* Type: function
* Description: Callback function invoked when user end edit the token
* parameter:
* data => customize data onject for update result of edit.
* Make no change, in case do not provide data.
*
* @ props.onDelete
* Type: function
* Description: Callback function invoked when user delete the token
*
*
* @ return
* Type: node
* Description: The token's content.
*/
tokenRender: _propTypes2.default.func,
/**
* function for validate data
* validator(data, index, allData)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ index
* Type: number
* Description: data's array index in allData
*
* @ allData
* Type: array
* Description: array of allData
*
* @ return
* Type: null || customize error
* Description: The error.
* Could be error message to display or error object
* return null means "validate"
*/
validator: _propTypes2.default.func,
/**
* Callback function invoked when user typing but not become token yet
* onInputValueChange(value)
*
* @ value
* Type: string
* Description: user input string
*/
onInputValueChange: _propTypes2.default.func,
/**
* Callback function invoked data updated
* onTokensUpdate(tokens)
*
* @ tokens
* Type: Array
* Description: Array of token data
*
* token data
* {
* value, // customize data
* meta: {
* key, // private key for render
* activated, // Boolean; Specific the token is activated for edit or not
* error // null or ERROR object. Specific the token's validate status
* }
* }
*/
onTokensUpdate: _propTypes2.default.func
};
TokenInput.defaultProps = {
className: '',
readOnly: false,
placeholder: '',
autoFocus: false,
defaultData: [],
separators: [',', ';', '\n', // for copy past
'\r', // for copy past
'\r\n' // for copy past
],
// reproduceValue: reproduceValue,
buildDataFromValue: _utils.buildDataFromValue,
dataValue: _utils.getDataValue,
tokenClassName: function tokenClassName() {
return '';
},
tokenLabelRender: _utils.getDataValue,
validator: function validator() {
return null;
},
tokenErrorMessage: function tokenErrorMessage(errorMsg) {
return errorMsg;
},
onInputValueChange: function onInputValueChange(value) {
return value;
},
onTokensUpdate: function onTokensUpdate() {} // dummy function
};
exports.default = TokenInput;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(1);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactInputAutosize = __webpack_require__(4);
var _reactInputAutosize2 = _interopRequireDefault(_reactInputAutosize);
var _utils = __webpack_require__(5);
var _styles = __webpack_require__(2);
var _styles2 = _interopRequireDefault(_styles);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TokenCreator = function (_PureComponent) {
_inherits(TokenCreator, _PureComponent);
function TokenCreator(props) {
_classCallCheck(this, TokenCreator);
var _this = _possibleConstructorReturn(this, (TokenCreator.__proto__ || Object.getPrototypeOf(TokenCreator)).call(this, props));
_this.actions = {
updateValue: function updateValue() {
var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
_this.setState({ value: value }, function () {
_this.props.onInputValueChange(value);
});
},
// event handler
handleChangeValue: function handleChangeValue(e) {
var value = e.target.value;
var lastChar = value.substr(-1);
var pattens = new RegExp(_this.props.separators.join('|'));
if (pattens.test(lastChar) === true) {
_this.actions.createTokens();
return;
}
_this.actions.updateValue(value);
},
createTokens: function createTokens() {
var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.state.value;
var _this$props = _this.props,
separators = _this$props.separators,
preprocessor = _this$props.preprocessor,
buildDataFromValue = _this$props.buildDataFromValue,
addTokens = _this$props.addTokens;
var trimmedValue = value.trim();
// Skip empty
if (trimmedValue === '') {
return;
}
var inputValues = trimmedValue.split(new RegExp(separators.join('|')));
var values = preprocessor(inputValues);
var tokens = values.map(function (value, index) {
var data = buildDataFromValue(value);
return (0, _utils.dataItemToTokenData)(data, index);
});
addTokens(tokens);
_this.actions.updateValue(''); // clear value
},
handleKeyDown: function handleKeyDown(e) {
// const { value } = e.target;
var value = _this.state.value;
var eventKey = void 0;
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
var eventKeys = ['Backspace', 'Enter', 'Escape'];
var keyIndex = eventKeys.indexOf(e.key);
eventKey = eventKeys[keyIndex];
// backward compatibility for browser not support event.key, such as safari
// https://www.w3schools.com/jsref/event_key_key.asp
if (eventKey === undefined) {
eventKey = {
8: 'Backspace',
13: 'Enter',
27: 'Escape'
}[e.keyCode];
}
// TODO: Fix me. check functional
if (value.length === 0 && eventKey === 'Backspace') {
_this.props.onDeleteLastToken();
}
if (eventKey === 'Escape') {
_this.actions.updateValue(''); // clear value
return;
}
if (eventKey === 'Enter') {
_this.actions.createTokens();
return;
}
},
handleFocus: function handleFocus(e) {
_this.props.onFocus(e);
},
handleBlur: function handleBlur(e) {
_this.actions.createTokens();
_this.props.onBlur(e);
},
handlePaste: function handlePaste(e) {
e.preventDefault();
var pastedText = e.clipboardData.getData('text');
_this.actions.createTokens(pastedText);
}
};
_this.focus = function () {
_this.tokenCreator.input && _this.tokenCreator.input.focus();
};
_this.state = {
value: ''
};
return _this;
}
_createClass(TokenCreator, [{
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
placeholder = _props.placeholder,
autoFocus = _props.autoFocus;
var value = this.state.value;
return _react2.default.createElement(
'div',
{ className: _styles2.default['autosized-wrapper'] },
_react2.default.createElement(_reactInputAutosize2.default, {
ref: function ref(node) {
_this2.tokenCreator = node;
},
placeholder: placeholder,
value: value,
autoFocus: autoFocus,
onFocus: this.actions.handleFocus,
onBlur: this.actions.handleBlur,
onChange: this.actions.handleChangeValue,
onKeyDown: this.actions.handleKeyDown,
onPaste: this.actions.handlePaste
})
);
}
}]);
return TokenCreator;
}(_react.PureComponent);
TokenCreator.propTypes = {
separators: _propTypes2.default.array.isRequired,
placeholder: _propTypes2.default.string.isRequired,
autoFocus: _propTypes2.default.bool.isRequired,
onFocus: _propTypes2.default.func.isRequired,
onBlur: _propTypes2.default.func.isRequired,
addTokens: _propTypes2.default.func.isRequired,
onDeleteLastToken: _propTypes2.default.func.isRequired,
buildDataFromValue: _propTypes2.default.func.isRequired,
onInputValueChange: _propTypes2.default.func.isRequired,
preprocessor: _propTypes2.default.func.isRequired
};
exports.default = TokenCreator;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(1);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _reactInputAutosize = __webpack_require__(4);
var _reactInputAutosize2 = _interopRequireDefault(_reactInputAutosize);
var _styles = __webpack_require__(2);
var _styles2 = _interopRequireDefault(_styles);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DeleteButton = function DeleteButton(props) {
return _react2.default.createElement('i', {
className: _styles2.default['delete-button'],
'aria-hidden': 'true'
});
};
var Token = function (_PureComponent) {
_inherits(Token, _PureComponent);
function Token(props) {
_classCallCheck(this, Token);
var _this = _possibleConstructorReturn(this, (Token.__proto__ || Object.getPrototypeOf(Token)).call(this, props));
_this.actions = {
onStartEdit: function onStartEdit() {
var _this$props = _this.props,
data = _this$props.data,
onStartEdit = _this$props.onStartEdit,
dataValue = _this$props.dataValue;
_this.setState({
value: dataValue(data.value, data.meta)
}, function () {
onStartEdit();
});
},
onEndEdit: function onEndEdit() {
var rollback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var buildDataFromValue = _this.props.buildDataFromValue;
var value = _this.state.value;
// handle input value length === 0 case: Rollback token
if (rollback === true || value.length === 0) {
_this.props.onEndEdit();
return;
}
_this.props.onEndEdit(buildDataFromValue(value));
},
// event handler
handleClick: function handleClick(e) {
e.stopPropagation();
var _e$target$className = e.target.className,
className = _e$target$className === undefined ? '' : _e$target$className;
var isDeleteButton = className.indexOf(_styles2.default['delete-button']) !== -1;
var _this$props2 = _this.props,
readOnly = _this$props2.readOnly,
onDelete = _this$props2.onDelete;
if (readOnly === true) {
return;
}
if (isDeleteButton) {
onDelete();
return;
}
_this.actions.onStartEdit();
},
handleChangeValue: function handleChangeValue(e) {
var value = e.target.value;
_this.setState({ value: value });
},
handleKeyDown: function handleKeyDown(e) {
var eventKey = void 0;
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
var eventKeys = ['Enter', 'Escape'];
var keyIndex = eventKeys.indexOf(e.key);
eventKey = eventKeys[keyIndex];
// backward compatibility for browser not support event.key, such as safari
// https://www.w3schools.com/jsref/event_key_key.asp
if (eventKey === undefined) {
eventKey = {
13: 'Enter',
27: 'Escape'
}[e.keyCode];
}
if (eventKey === 'Escape') {
// End editing with Rollback token
_this.actions.onEndEdit(true);
return;
}
if (eventKey === 'Enter') {
_this.actions.onEndEdit();
return;
}
},
handleBlur: function handleBlur(e) {
_this.actions.onEndEdit();
}
};
_this.state = {
value: ''
};
return _this;
}
_createClass(Token, [{
key: 'render',
value: function render() {
var _classNames;
var _props = this.props,
readOnly = _props.readOnly,
data = _props.data,
tokenClassName = _props.tokenClassName,
tokenLabelRender = _props.tokenLabelRender,
tokenErrorMessage = _props.tokenErrorMessage;
var value = this.state.value;
var _data$meta = data.meta,
activated = _data$meta.activated,
error = _data$meta.error;
var title = error === null ? null : tokenErrorMessage(error);
return _react2.default.createElement(
'div',
{
className: (0, _classnames2.default)(tokenClassName(data.value, data.meta), _styles2.default.token, (_classNames = {}, _defineProperty(_classNames, _styles2.default.active, activated), _defineProperty(_classNames, _styles2.default.error, error && !activated), _defineProperty(_classNames, _styles2.default['read-only'], readOnly), _classNames)),
onClick: this.actions.handleClick,
role: 'presentation',
title: title
},
!activated && _react2.default.createElement(
'div',
{ className: _styles2.default['label-wrapper'] },
tokenLabelRender(data.value)
),
!activated && !readOnly && _react2.default.createElement(DeleteButton, null),
activated && _react2.default.createElement(
'div',
{ className: _styles2.default['autosized-wrapper'] },
_react2.default.createElement(_reactInputAutosize2.default, {
ref: function ref(input) {
return input && input.focus();
},
value: value,
onChange: this.actions.handleChangeValue,
onKeyDown: this.actions.handleKeyDown,
onBlur: this.actions.handleBlur
})
)
);
}
}]);
return Token;
}(_react.PureComponent);
Token.propTypes = {
readOnly: _propTypes2.default.bool.isRequired,
tokenClassName: _propTypes2.default.func.isRequired,
tokenLabelRender: _propTypes2.default.func.isRequired,
tokenErrorMessage: _propTypes2.default.func.isRequired,
dataValue: _propTypes2.default.func.isRequired,
buildDataFromValue: _propTypes2.default.func.isRequired,
data: _propTypes2.default.object.isRequired,
onStartEdit: _propTypes2.default.func.isRequired,
onEndEdit: _propTypes2.default.func.isRequired,
onDelete: _propTypes2.default.func.isRequired
};
exports.default = Token;
/***/ })
/******/ ]);
/*! For license information please see index.js.LICENSE.txt */
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("react"));else if("function"==typeof define&&define.amd)define(["react"],t);else{var n="object"==typeof exports?t(require("react")):t(e.React);for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(self,(function(e){return(()=>{var t={184:(e,t)=>{var n;!function(){"use strict";var r={}.hasOwnProperty;function o(){for(var e=[],t=0;t<arguments.length;t++){var n=arguments[t];if(n){var a=typeof n;if("string"===a||"number"===a)e.push(n);else if(Array.isArray(n)){if(n.length){var u=o.apply(null,n);u&&e.push(u)}}else if("object"===a)if(n.toString===Object.prototype.toString)for(var i in n)r.call(n,i)&&n[i]&&e.push(i);else e.push(n.toString())}}return e.join(" ")}e.exports?(o.default=o,e.exports=o):void 0===(n=function(){return o}.apply(t,[]))||(e.exports=n)}()},703:(e,t,n)=>{"use strict";var r=n(414);function o(){}function a(){}a.resetWarningCache=o,e.exports=function(){function e(e,t,n,o,a,u){if(u!==r){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:a,resetWarningCache:o};return n.PropTypes=n,n}},697:(e,t,n)=>{e.exports=n(703)()},414:e=>{"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},639:(e,t,n)=>{"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=n(698),u=l(a),i=l(n(697));function l(e){return e&&e.__esModule?e:{default:e}}var s={position:"absolute",top:0,left:0,visibility:"hidden",height:0,overflow:"scroll",whiteSpace:"pre"},c=["extraWidth","injectStyles","inputClassName","inputRef","inputStyle","minWidth","onAutosize","placeholderIsMinWidth"],f=function(e,t){t.style.fontSize=e.fontSize,t.style.fontFamily=e.fontFamily,t.style.fontWeight=e.fontWeight,t.style.fontStyle=e.fontStyle,t.style.letterSpacing=e.letterSpacing,t.style.textTransform=e.textTransform},p=!("undefined"==typeof window||!window.navigator)&&/MSIE |Trident\/|Edge\//.test(window.navigator.userAgent),d=function(){return p?"_"+Math.random().toString(36).substr(2,12):void 0},y=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.inputRef=function(e){n.input=e,"function"==typeof n.props.inputRef&&n.props.inputRef(e)},n.placeHolderSizerRef=function(e){n.placeHolderSizer=e},n.sizerRef=function(e){n.sizer=e},n.state={inputWidth:e.minWidth,inputId:e.id||d(),prevId:e.id},n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),o(t,null,[{key:"getDerivedStateFromProps",value:function(e,t){var n=e.id;return n!==t.prevId?{inputId:n||d(),prevId:n}:null}}]),o(t,[{key:"componentDidMount",value:function(){this.mounted=!0,this.copyInputStyles(),this.updateInputWidth()}},{key:"componentDidUpdate",value:function(e,t){t.inputWidth!==this.state.inputWidth&&"function"==typeof this.props.onAutosize&&this.props.onAutosize(this.state.inputWidth),this.updateInputWidth()}},{key:"componentWillUnmount",value:function(){this.mounted=!1}},{key:"copyInputStyles",value:function(){if(this.mounted&&window.getComputedStyle){var e=this.input&&window.getComputedStyle(this.input);e&&(f(e,this.sizer),this.placeHolderSizer&&f(e,this.placeHolderSizer))}}},{key:"updateInputWidth",value:function(){if(this.mounted&&this.sizer&&void 0!==this.sizer.scrollWidth){var e=void 0;e=this.props.placeholder&&(!this.props.value||this.props.value&&this.props.placeholderIsMinWidth)?Math.max(this.sizer.scrollWidth,this.placeHolderSizer.scrollWidth)+2:this.sizer.scrollWidth+2,(e+="number"===this.props.type&&void 0===this.props.extraWidth?16:parseInt(this.props.extraWidth)||0)<this.props.minWidth&&(e=this.props.minWidth),e!==this.state.inputWidth&&this.setState({inputWidth:e})}}},{key:"getInput",value:function(){return this.input}},{key:"focus",value:function(){this.input.focus()}},{key:"blur",value:function(){this.input.blur()}},{key:"select",value:function(){this.input.select()}},{key:"renderStyles",value:function(){var e=this.props.injectStyles;return p&&e?u.default.createElement("style",{dangerouslySetInnerHTML:{__html:"input#"+this.state.inputId+"::-ms-clear {display: none;}"}}):null}},{key:"render",value:function(){var e=[this.props.defaultValue,this.props.value,""].reduce((function(e,t){return null!=e?e:t})),t=r({},this.props.style);t.display||(t.display="inline-block");var n=r({boxSizing:"content-box",width:this.state.inputWidth+"px"},this.props.inputStyle),o=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}(this.props,[]);return function(e){c.forEach((function(t){return delete e[t]}))}(o),o.className=this.props.inputClassName,o.id=this.state.inputId,o.style=n,u.default.createElement("div",{className:this.props.className,style:t},this.renderStyles(),u.default.createElement("input",r({},o,{ref:this.inputRef})),u.default.createElement("div",{ref:this.sizerRef,style:s},e),this.props.placeholder?u.default.createElement("div",{ref:this.placeHolderSizerRef,style:s},this.props.placeholder):null)}}]),t}(a.Component);y.propTypes={className:i.default.string,defaultValue:i.default.any,extraWidth:i.default.oneOfType([i.default.number,i.default.string]),id:i.default.string,injectStyles:i.default.bool,inputClassName:i.default.string,inputRef:i.default.func,inputStyle:i.default.object,minWidth:i.default.oneOfType([i.default.number,i.default.string]),onAutosize:i.default.func,onChange:i.default.func,placeholder:i.default.string,placeholderIsMinWidth:i.default.bool,style:i.default.object,value:i.default.any},y.defaultProps={minWidth:1,injectStyles:!0},t.Z=y},698:t=>{"use strict";t.exports=e}},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};return(()=>{"use strict";r.r(o),r.d(o,{default:()=>q});var e=r(698),t=r.n(e),n=r(697),a=r.n(n),u=r(184),i=r.n(u),l=r(639);const s=function(e,t){var n,r=t.onBackspace,o=void 0===r?function(){}:r,a=t.onEnter,u=void 0===a?function(){}:a,i=t.onEscape,l=void 0===i?function(){}:i,s=["Backspace","Enter","Escape"],c=s.indexOf(e.key);switch(void 0===(n=s[c])&&(n={8:"Backspace",13:"Enter",27:"Escape"}[e.keyCode]),n){case"Backspace":o();break;case"Enter":u();break;case"Escape":l()}},c="customize-token-input---delete-button---RxqGs",f="customize-token-input---autosized-wrapper---TXzhr";function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var d=(0,e.forwardRef)((function(n,r){var o,a,u=n.separators,i=n.onPreprocess,c=n.onBuildTokenValue,d=n.onNewTokenValuesAppend,y=n.onLastTokenDelete,h=n.placeholder,m=n.autoFocus,b=n.onFocus,v=n.onBlur,k=n.onInputValueChange,g=(o=(0,e.useState)(""),a=2,function(e){if(Array.isArray(e))return e}(o)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,a=[],u=!0,i=!1;try{for(n=n.call(e);!(u=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);u=!0);}catch(e){i=!0,o=e}finally{try{u||null==n.return||n.return()}finally{if(i)throw o}}return a}}(o,a)||function(e,t){if(e){if("string"==typeof e)return p(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p(e,t):void 0}}(o,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),T=g[0],S=g[1],E=(0,e.useMemo)((function(){return new RegExp(u.join("|"))}),[u]),C=(0,e.useCallback)((function(e){S(e),k(e,T)}),[k,T,S]),w=(0,e.useCallback)((function(e){if(0!==e.length){var t=e.split(E),n=i(t).map((function(e){return c(e)}));d(n),C("")}}),[E,i,c,d,C]),A=(0,e.useCallback)((function(e){var t=e.target.value,n=t.substr(-1);!0!==E.test(n)?C(t):w(T)}),[E,w,T,C]),I=(0,e.useCallback)((function(e){s(e,{onBackspace:function(){0===T.length&&y()},onEscape:function(){return C("")},onEnter:function(){return w(T)}})}),[T,y,C,w]),O=(0,e.useCallback)((function(e){w(T),v(e)}),[w,T,v]),j=(0,e.useCallback)((function(e){e.preventDefault();var t=e.clipboardData.getData("text");w(t)}),[w]);return t().createElement("div",{className:f},t().createElement(l.Z,{ref:r,autoFocus:m,placeholder:h,value:T,onChange:A,onKeyDown:I,onPaste:j,onFocus:b,onBlur:O}))}));d.displayName="TokenCreator",d.propTypes={placeholder:a().string.isRequired,autoFocus:a().bool.isRequired,onFocus:a().func.isRequired,onBlur:a().func.isRequired,separators:a().array.isRequired,onInputValueChange:a().func.isRequired,onPreprocess:a().func.isRequired,onBuildTokenValue:a().func.isRequired,onNewTokenValuesAppend:a().func.isRequired,onLastTokenDelete:a().func.isRequired};const y=d,h=function(){return t().createElement("span",{role:"button",className:c,"aria-hidden":"true","data-component-name":"DeleteButton"})};function m(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function b(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var v=function(e){e.stopPropagation()},k=function(n){var r,o,a=n.readOnly,u=n.tokenValue,p=n.tokenMeta,d=n.onGetClassName,y=n.onGetDisplayLabel,k=n.onGetEditableValue,g=n.onGetErrorMessage,T=n.onBuildTokenValue,S=n.onEditStart,E=n.onEditEnd,C=n.onDelete,w=(0,e.useRef)(null),A=(r=(0,e.useState)(""),o=2,function(e){if(Array.isArray(e))return e}(r)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,a=[],u=!0,i=!1;try{for(n=n.call(e);!(u=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);u=!0);}catch(e){i=!0,o=e}finally{try{u||null==n.return||n.return()}finally{if(i)throw o}}return a}}(r,o)||function(e,t){if(e){if("string"==typeof e)return b(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?b(e,t):void 0}}(r,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),I=A[0],O=A[1],j=p.activated,V=p.error,R=(0,e.useCallback)((function(){var e=k(u,p);O(e),S()}),[O,u,p,k,S]);(0,e.useEffect)((function(){j&&w.current&&w.current.focus()}),[j]);var x=(0,e.useCallback)((function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.reset,n=void 0!==t&&t,r=0===I.length;if(n||r)E();else{var o=T(I);E(o)}}),[I,T,E]),M=(0,e.useCallback)((function(e){if(e.stopPropagation(),!a){var t=e.target.className;-1!==(void 0===t?"":t).indexOf(c)?C():R()}}),[a,C,R]),z=(0,e.useCallback)((function(e){var t=e.target.value;O(t)}),[O]),P=(0,e.useCallback)((function(e){s(e,{onEscape:function(){return x({reset:!0})},onEnter:function(){return x()}})}),[x]),N=(0,e.useCallback)((function(){x()}),[x]),W=(0,e.useMemo)((function(){var e;return i()(d(u,p),"customize-token-input---token---gTkkf",(m(e={},"customize-token-input---active---jZZPP",j),m(e,"customize-token-input---error---eNFRx",V&&!j),m(e,"customize-token-input---read-only---_IB6t",a),e))}),[a,V,j,d,u,p]),D=(0,e.useMemo)((function(){return g(u,p)}),[g,u,p]);return j?t().createElement("div",{role:"presentation",className:W,onClick:v},t().createElement("div",{className:f},t().createElement(l.Z,{ref:w,value:I,onChange:z,onKeyDown:P,onBlur:N}))):t().createElement("div",{role:"presentation",className:W,onClick:M,title:D,"data-component-name":"Token"},t().createElement("div",{className:"customize-token-input---label-wrapper---RRpXn"},y(u,p)),!a&&t().createElement(h,null))};k.propTypes={readOnly:a().bool.isRequired,tokenValue:a().any.isRequired,tokenMeta:a().object.isRequired,onGetClassName:a().func.isRequired,onGetDisplayLabel:a().func.isRequired,onGetEditableValue:a().func.isRequired,onGetErrorMessage:a().func.isRequired,onBuildTokenValue:a().func.isRequired,onEditStart:a().func.isRequired,onEditEnd:a().func.isRequired,onDelete:a().func.isRequired};const g=k;function T(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}const S=function(){var t,n,r=(t=(0,e.useState)(!1),n=2,function(e){if(Array.isArray(e))return e}(t)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,a=[],u=!0,i=!1;try{for(n=n.call(e);!(u=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);u=!0);}catch(e){i=!0,o=e}finally{try{u||null==n.return||n.return()}finally{if(i)throw o}}return a}}(t,n)||function(e,t){if(e){if("string"==typeof e)return T(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?T(e,t):void 0}}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=r[0],a=r[1];return{isTokenInputFocused:o,handleTokenInputFocus:(0,e.useCallback)((function(){a(!0)}),[]),handleTokenInputBlur:(0,e.useCallback)((function(){a(!1)}),[])}},E=function(e,t,n){return{key:"".concat(JSON.stringify(t),"-").concat(Date.now(),"-").concat(n),activated:!1,error:e}};function C(e,t){if(e){if("string"==typeof e)return w(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?w(e,t):void 0}}function w(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}const A=function(){var t,n,r=(t=(0,e.useState)([]),n=2,function(e){if(Array.isArray(e))return e}(t)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,a=[],u=!0,i=!1;try{for(n=n.call(e);!(u=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);u=!0);}catch(e){i=!0,o=e}finally{try{u||null==n.return||n.return()}finally{if(i)throw o}}return a}}(t,n)||C(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=r[0],a=r[1],u=(0,e.useCallback)((function(e,t){if(e>=o.length)throw new Error("setTokenActivated out of tokenMetas scope; targetIndex ".concat(e,"; tokenMetas.length ").concat(o.length));var n=function(e){return function(e){if(Array.isArray(e))return w(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||C(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(o);n[e].activated=t,a(n)}),[o]);return{buildTokenMeta:E,tokenMetas:o,setTokenMetas:a,setTokenActivated:u}};function I(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,a=[],u=!0,i=!1;try{for(n=n.call(e);!(u=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);u=!0);}catch(e){i=!0,o=e}finally{try{u||null==n.return||n.return()}finally{if(i)throw o}}return a}}(e,t)||O(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function O(e,t){if(e){if("string"==typeof e)return j(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?j(e,t):void 0}}function j(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}const V=function(t){var n=t.tokenValues,r=t.onTokenValueValidate,o=A(),a=o.buildTokenMeta,u=o.tokenMetas,i=o.setTokenMetas,l=o.setTokenActivated,s=I((0,e.useState)(!1),2),c=s[0],f=s[1],p=I((0,e.useState)([]),2),d=p[0],y=p[1];return(0,e.useLayoutEffect)((function(){var e,t=!1,o=n.map((function(e,o){var u=r(e,o,n),i=a(u,e,o);return i.error&&!i.activated&&(t=!0),i}));y(function(e){if(Array.isArray(e))return j(e)}(e=n)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||O(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i(o),f(t)}),[n,r,i,a]),{hasInvalidToken:c,internalTokenValues:d,tokenMetas:u,setTokenActivated:l}};function R(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}const x=function(t){var n=t.tokenValues,r=t.onTokenValuesChange,o=t.setTokenActivated,a=t.handleTokenInputFocus,u=t.handleTokenInputBlur,i=t.focusTokenCreator;return{handleTokenEditStart:(0,e.useCallback)((function(e){return function(){o(e,!0),a()}}),[o,a]),handleTokenEditEnd:(0,e.useCallback)((function(e){return function(t){if(o(e,!1),u(),i(),void 0!==t){var a=function(e){if(Array.isArray(e))return R(e)}(l=n)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(l)||function(e,t){if(e){if("string"==typeof e)return R(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?R(e,t):void 0}}(l)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}();a[e]=t,r(a)}var l}}),[n,r,o,u,i])}};function M(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}const z=function(t){var n=t.tokenValues,r=t.onTokenValuesChange,o=t.focusTokenCreator,a=(0,e.useCallback)((function(e){var t,a=function(e){if(Array.isArray(e))return M(e)}(t=n)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||function(e,t){if(e){if("string"==typeof e)return M(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?M(e,t):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}();a.splice(e,1),r(a),o()}),[n,r,o]);return{handleTokenDelete:(0,e.useCallback)((function(e){return function(){a(e)}}),[a]),handleLastTokenDelete:(0,e.useCallback)((function(){a(-1)}),[a])}},P=function(e,t){return e};var N=["className","readOnly","autoFocus","placeholder","tokenValues","onTokenValuesChange","onBuildTokenValue","customizeTokenComponent","onGetTokenClassName","onGetTokenDisplayLabel","onGetTokenEditableValue","onGetTokenErrorMessage","separators","onPreprocess","onInputValueChange","onTokenValueValidate"];function W(){return(W=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function D(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function G(e){return function(e){if(Array.isArray(e))return _(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return _(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var B=function(n){var r,o=n.className,a=n.readOnly,u=n.autoFocus,l=n.placeholder,s=n.tokenValues,c=n.onTokenValuesChange,f=n.onBuildTokenValue,p=n.customizeTokenComponent,d=n.onGetTokenClassName,h=n.onGetTokenDisplayLabel,m=n.onGetTokenEditableValue,b=n.onGetTokenErrorMessage,v=n.separators,k=n.onPreprocess,T=n.onInputValueChange,E=n.onTokenValueValidate,C=function(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}(n,N),w=S(),A=w.isTokenInputFocused,I=w.handleTokenInputFocus,O=w.handleTokenInputBlur,j=function(){var t=(0,e.useRef)(null),n=(0,e.useCallback)((function(){t&&t.current&&t.current.focus()}),[]);return{tokenCreatorRef:t,focusTokenCreator:n}}(),R=j.tokenCreatorRef,M=j.focusTokenCreator,P=V({tokenValues:s,onTokenValueValidate:E}),_=P.hasInvalidToken,B=P.internalTokenValues,q=P.tokenMetas,F=P.setTokenActivated,L=x({tokenValues:s,onTokenValuesChange:c,setTokenActivated:F,handleTokenInputFocus:I,handleTokenInputBlur:O,focusTokenCreator:M}),U=L.handleTokenEditStart,H=L.handleTokenEditEnd,$=z({tokenValues:s,onTokenValuesChange:c,focusTokenCreator:M}),Z=$.handleTokenDelete,X=$.handleLastTokenDelete,K=(0,e.useCallback)((function(e){if(0!==e.length){var t=[].concat(G(s),G(e));c(t)}}),[s,c]),Y=(0,e.useCallback)((function(e){if("function"!=typeof k)return e;var t=k(e);if(!0!==Array.isArray(t))throw new Error("onPreprocess should return an array of values");return t}),[k]),J=p||g;return t().createElement("div",W({},C,{className:i()(o,"customize-token-input---container---F6cN_",(r={},D(r,"customize-token-input---focused---k4Zch",A),D(r,"customize-token-input---errors---QXs7u",_),r)),onClick:M,role:"presentation","data-component-name":"TokenInput"}),t().createElement("div",{className:"customize-token-input---token-list---mZYkR"},B.map((function(e,n){var r=q[n],o=r.key;return t().createElement(J,{key:o,readOnly:a,tokenValue:e,tokenMeta:r,onGetClassName:d,onGetDisplayLabel:h,onGetEditableValue:m,onGetErrorMessage:b,onBuildTokenValue:f,onEditStart:U(n),onEditEnd:H(n),onDelete:Z(n)})}))),!a&&t().createElement(y,{ref:R,placeholder:l,autoFocus:u,onFocus:I,onBlur:O,separators:v,onPreprocess:Y,onBuildTokenValue:f,onNewTokenValuesAppend:K,onLastTokenDelete:X,onInputValueChange:T}))};B.propTypes={style:a().object,className:a().string,readOnly:a().bool,autoFocus:a().bool,placeholder:a().string,tokenValues:a().array.isRequired,onTokenValuesChange:a().func,separators:a().array,onPreprocess:a().func,onBuildTokenValue:a().func,onInputValueChange:a().func,onTokenValueValidate:a().func,onGetTokenClassName:a().func,onGetTokenDisplayLabel:a().func,onGetTokenEditableValue:a().func,onGetTokenErrorMessage:a().func,customizeTokenComponent:a().func},B.defaultProps={className:"",readOnly:!1,autoFocus:!1,placeholder:"",separators:[",",";","\n","\r","\r\n"],onBuildTokenValue:function(e){return e.trim()},onInputValueChange:function(){},onTokenValueValidate:function(){},onGetTokenClassName:function(){return""},onGetTokenDisplayLabel:P,onGetTokenEditableValue:P,onGetTokenErrorMessage:function(e,t){return t.error}};const q=B})(),o})()}));
//# sourceMappingURL=index.js.map
{
"name": "react-customize-token-input",
"version": "0.5.2",
"description": "A react token input component. Allow customize data structure and render functions",
"version": "1.2.1",
"description": "A react token (tag) input component. Allow customize data structure and render functions",
"main": "lib/index.js",

@@ -11,13 +11,20 @@ "files": [

"scripts": {
"prepublish": "npm run eslint && npm test && npm run clean && npm run build && npm run build-examples",
"build": "webpack && npm run cleancss",
"build-examples": "cd examples; webpack",
"prepublish": "yarn run eslint && yarn run clean && yarn run build && yarn run build:examples",
"build": "webpack",
"build:examples": "cd examples; webpack",
"clean": "rm -f {lib,dist}/*",
"cleancss": "cleancss -o dist/react-customize-token-input.min.css dist/react-customize-token-input.css",
"demo": "http-server -p 8000 docs/",
"eslint": "eslint --ext .js --ext .jsx *.js examples src test",
"test": "tap test/*.js --node-arg=--require --node-arg=babel-register --node-arg=--require --node-arg=babel-polyfill",
"coveralls": "tap test/*.js --coverage --coverage-report=text-lcov --nyc-arg=--require --nyc-arg=babel-register --nyc-arg=--require --nyc-arg=babel-polyfill | coveralls",
"dev": "cd examples; webpack-dev-server --hot --inline --host 0.0.0.0 --port 8000 --content-base ../docs"
"eslint": "eslint --max-warnings 0 --ext .jsx,.js,.ts,.tsx examples src test",
"dev": "cd examples; webpack && webpack serve --hot --inline --host 0.0.0.0 --port 8000 --content-base ../docs"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx}": [
"prettier --write",
"eslint --fix --max-warnings 0"
]
},
"repository": {

@@ -32,57 +39,61 @@ "type": "git",

"react",
"react-token-input",
"react-customize-token-input",
"token-input",
"token",
"tag",
"token input",
"tag input",
"preprocess",
"inline edit",
"customize",
"customize data structure",
"Customize render functions",
"pre-processs",
"preprocesss"
"customize render"
],
"peerDependencies": {
"react": "^16.10.2"
},
"dependencies": {
"classnames": "2.2.5",
"prop-types": "15.6.2",
"react": "16.4.2",
"react-input-autosize": "2.2.1"
"classnames": "^2.3.1",
"prop-types": "^15.7.2",
"react-input-autosize": "^3.0.0"
},
"devDependencies": {
"babel-cli": "6.26.0",
"babel-core": "6.26.3",
"babel-eslint": "8.2.3",
"babel-loader": "7.1.4",
"babel-plugin-transform-decorators-legacy": "1.3.4",
"babel-preset-env": "1.7.0",
"babel-preset-react": "6.24.1",
"babel-preset-stage-0": "6.24.1",
"clean-css": "4.1.11",
"clean-css-cli": "4.1.11",
"coveralls": "3.0.1",
"css-loader": "0.28.11",
"enzyme": "3.3.0",
"enzyme-adapter-react-16": "1.1.1",
"eslint": "4.19.1",
"eslint-config-trendmicro": "1.3.1",
"eslint-loader": "2.0.0",
"eslint-plugin-import": "2.12.0",
"eslint-plugin-jsx-a11y": "6.0.3",
"eslint-plugin-react": "7.8.2",
"extract-text-webpack-plugin": "3.0.2",
"file-loader": "1.1.11",
"find-imports": "0.5.2",
"html-webpack-plugin": "3.2.0",
"http-server": "0.10.0",
"jsdom": "11.11.0",
"nib": "1.1.2",
"react": "16.4.2",
"react-dom": "16.4.2",
"style-loader": "0.21.0",
"stylint": "1.5.9",
"stylint-loader": "1.0.0",
"stylus-loader": "3.0.2",
"tap": "12.0.1",
"trendmicro-ui": "0.5.2",
"url-loader": "1.0.1",
"webpack": "3.11.0",
"webpack-dev-server": "2.11.2"
"@babel/core": "^7.14.8",
"@babel/eslint-parser": "^7.14.9",
"@babel/eslint-plugin": "^7.14.5",
"@babel/preset-env": "^7.14.9",
"@babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"babel-plugin-transform-react-qa-classes": "^1.6.0",
"css-loader": "^6.2.0",
"eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-config-prettier": "^8.3.0",
"eslint-config-react-app": "^6.0.0",
"eslint-plugin-import": "^2.23.4",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-react": "^7.24.0",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-webpack-plugin": "^3.0.1",
"html-webpack-plugin": "^5.3.2",
"husky": "^7.0.1",
"lint-staged": "^11.1.1",
"mini-css-extract-plugin": "^2.1.0",
"nib": "^1.1.2",
"prettier": "^2.3.2",
"react": "^16.10.2",
"react-dev-utils": "^11.0.4",
"react-dom": "^16.14.0",
"style-loader": "^3.2.1",
"stylelint": "^13.13.1",
"stylelint-config-prettier": "^8.0.2",
"stylelint-config-rational-order": "^0.1.2",
"stylelint-config-standard": "^22.0.0",
"stylelint-prettier": "^1.2.0",
"stylelint-webpack-plugin": "^3.0.1",
"stylus": "^0.54.8",
"stylus-loader": "^6.1.0",
"webpack": "^5.48.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
}
}

@@ -5,11 +5,16 @@ # React TokenInput [![build status](https://travis-ci.org/seawind543/react-token-input.svg?branch=master)](https://travis-ci.org/seawind543/react-token-input) [![Coverage Status](https://coveralls.io/repos/github/seawind543/react-token-input/badge.svg?branch=master)](https://coveralls.io/github/seawind543/react-token-input?branch=master)

A react token input component, which allow:
1. Apply **customize data structure**.
2. **Customize render functions** for `token label part` or `the complete token`.
3. Customize **separate characters** for separate user input.
4. **Pre-processs** function for **normalized** user input value .
React TokenInput (react-customize-token-input)
A react token (tag) `controlled` input component, which support:
- Apply to **customize data structure**.
- **Customize token component** for `label of token` or `the complete token`.
- Customize **separate characters** for separate end-user input string.
- **Inline editing** on exist token.
- **Paste** on values.
- **Preprocessing** function for **normalized** user input value.
It could be helpful to reproduce a single value into multiple values too.
5. **Validate** function.
- **Validate** function.
Demo: https://seawind543.github.io/react-token-input/
Live Demo: https://seawind543.github.io/react-token-input/

@@ -21,6 +26,6 @@ ## Installation

```
npm install --save react react-customize-token-input
yarn add react react-customize-token-input
```
2. At this point you can import `react-token-input` and its styles in your application as follows:
2. At this point you can import `react-token-input` and its styles in your application by:

@@ -36,13 +41,11 @@ ```javascript

## Dev
1. Run `npm install` to install required packages.
2. Run `npm run dev` to launch `webpack-dev-server`.
1. Run `yarn install` to install required packages.
2. Run `yarn dev` to launch `webpack-dev-server`.
3. After step 2, you will see following message output in command console.
```
Project is running at http://0.0.0.0:8000/
webpack output is served from /
```
4. It might take some time for webpack to compiled. Please wait for message below output in the command console.
```
webpack: Compiled with warnings.
「wds」: Project is running at http://0.0.0.0:8000/
「wds」: webpack output is served from /
「wds」: Content not from webpack is served from ../docs
```

@@ -52,276 +55,354 @@

4. After step 3 complete, you could access `http://localhost:8000/` to see result.
## Usage
```javascript
// Simple sample.
// Take default, data is array of string
<TokenInput />
```
See Live Demo: https://seawind543.github.io/react-token-input/
```javascript
// Read only
<TokenInput readOnly={true} />
```
(Examples in the folder `examples`)
```javascript
// Customize data structure and validator
<TokenInput
defaultData={this.state.cData}
buildDataFromValue={this.actions.cData.buildDataFromValue}
dataValue={this.actions.cData.dataValue}
tokenLabelRender={this.actions.cData.tokenLabelRender}
validator={this.actions.cData.validator}
tokenErrorMessage={this.actions.cData.tokenErrorMessage}
onTokensUpdate={this.actions.cData.handleTokensUpdate}
/>
```
## Props
```javascript
// Reproduce value
<TokenInput
reproduceValue={this.actions.urls.reproduceValue}
onTokensUpdate={this.actions.urls.handleTokensUpdate}
/>
```
// Assign style to the TokenInput
style: PropTypes.object,
## Props
// Assign className to the TokenInput
className: PropTypes.string,
```javascript
// style: PropTypes.object,
className: PropTypes.string,
// Specific TokenInput is `readOnly` or not
readOnly: PropTypes.bool,
// Specific TokenInput is readOnly or not
readOnly: PropTypes.bool,
// Specific TokenInput should be autoFocus or not
autoFocus: PropTypes.bool,
// placeholder of TokenInput
placeholder: PropTypes.string,
// Placeholder of TokenInput
placeholder: PropTypes.string,
// Specific TokenInput should be autoFocus or not
autoFocus: PropTypes.bool,
// [Required] An array of tokenValue of TokenInput
tokenValues: PropTypes.array.isRequired,
// data for TokenInput to build pre-set tokens. Default is empty array
defaultData: PropTypes.array,
/**
* A callback function invoked when tokenValues update
*
* onTokenValuesChange(modifiedTokenValues)
*
* @ modifiedTokenValues
* Type: An array of tokenValue of TokenInput
* Description: Updated tokenValues
*/
onTokenValuesChange: PropTypes.func,
/**
* Array of characters for separate user input string.
* For example, separate user input string 'abc;def' into [abc, def] by separators [';']
*/
separators: PropTypes.array,
/**
* An array of characters for split the user input string.
* For example,
* Split the user input string `abc;def` into `['abc', 'def']`
* by separators `[';']`
*
* Note:
* It take the `String.prototype.split()` and `RegExp` to split the user input string.
* Make sure your customized separators could be used with `RegExp`.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
*/
separators: PropTypes.array,
/**
* function for pre-process user input values.
*
* Case 1:
* Make your normalize process in this function, such as trim.
*
* Case 2:
* Sometimes, we will want to auto-fit user input, this function could help on it.
* For example, user input is 'www.google.com',
* and we want to auto fit it into 'http://www.google.com' and 'https://www.google.com'
*
* preprocessor(values)
*
* @ values
* Type: array of string values
* Description: user input values // (values that input string separate by separators)
*
* @ return
* Type: array of string values
* Description: values after pre-process
*/
preprocessor: PropTypes.func,
/**
* A callback function for preprocessing the user input string
* (after it is split into `array of value`).
*
* Note: This function execute after `split` but before `onBuildTokenValue`
*
* [Use case 1]
* Make your normalize process in this function, such as `String.prototype.trim()`.
*
* [Use case 2]
* Sometimes, we will want to auto-fit user input, this function could help with it.
* For example, the user input string is `www.google.com`,
* and we want to auto-fit it into `http://www.google.com` and `https://www.google.com`.
*
*
* onPreprocess(inputStringValues)
*
* @ inputStringValues
* Type: An array of string values
* Description:
* The user input string values // (split from the user input string by the `separators`)
*
* @ return
* Type: An array of string values
* Description: The values after preprocess
*/
onPreprocess: PropTypes.func,
/**
* function for TokenInput to build user input value into customize data structure.
* You could make your normalize process in this function too.
* buildDataFromValue(value)
*
* @ value
* Type: string
* Description: user input value // (value are the input string separate by separators)
*
* @ return
* Type: object || string || number
* Description: customize data
*/
buildDataFromValue: PropTypes.func,
/**
* A callback function for building `user input string value` into
* the `tokenValue` (customize data structure).
*
* Note: You could make your normalize process in this function too.
*
* onBuildTokenValue(stringValue)
*
* @ stringValue
* Type: string
* Description: The user input value // (A value split by separators)
*
* @ return
* Type: any (string | number | object | customize data structure)
* Description: customize data structure
*/
onBuildTokenValue: PropTypes.func,
/**
* function for TokenInput to get value from customize data structure for user to perform "edit"
* dataValue(data)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ return
* Type: string
* Description: The value for user to edit
*/
dataValue: PropTypes.func,
/**
* A callback function invoked when end-user typing but not become token yet
*
* onInputValueChange(newValue, previousValue)
*
* @ newValue
* Type: string
* Description: end-user input string
*
* @ previousValue
* Type: string
* Description: previous end-user input string
*/
onInputValueChange: PropTypes.func,
/**
* function for TokenInput to get className for a token
* tokenClassName(data, meta)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ meta
* Description: token's meta data
* {
* key, // private key for render
* activated, // Boolean; Specific the token is activated for edit or not
* error // null or ERROR object. Specific the token's validate status
* }
*
*
* @ return
* Type: string
* Description: The className
*/
tokenClassName: PropTypes.func,
/**
* A callback function for validate tokenValue
*
* onTokenValueValidate(tokenValue, tokenIndex, tokenValues)
*
* @ tokenValue
* Type: any (string | number | object | customize data structure)
* Description: The tokenValue build by `onBuildTokenValue`
*
* @ tokenIndex
* Type: number
* Description: The array index for this tokenValue in tokenValues
*
* @ tokenValues
* Type: array
* Description: The array of tokenValue of TokenInput
*
* @ return
* Type: any (string | number | object | customize data structure)
* Description:
* The customize error.
* Specific the token's validate status or errorMessage.
* Could be an error message to display or error object
*
* Will be use by `onGetTokenErrorMessage`
*/
onTokenValueValidate: PropTypes.func,
/**
* A token label renderer for TokenInput to rendering a token's content part (label)
* Apply this to customize token's content. For example render token with "icon and text".
* tokenLabelRender(data)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ return
* Type: string || node
* Description: The token's content. By default, will apply dataValue()
*/
tokenLabelRender: PropTypes.func,
/**
* A callback function for getting customizes `className` for a token
*
* onGetTokenClassName(tokenValue, tokenMeta)
*
* @ tokenValue
* Type: any (string | number | object | customize data structure)
* Description: The tokenValue build by `onBuildTokenValue`
*
* @ tokenMeta
* Description: token's meta data
* {
* // A private key for render
* key: string,
*
* // Specific the token is activated for `edit` or not
* activated: boolean,
*
* // Customize data structure built by `onTokenValue Validate`
* // Specific the token's validate status or errorMessage
* error: any,
* }
*
* @ return
* Type: string
* Description: The customizes className
*/
onGetTokenClassName: PropTypes.func,
/**
* function for TokenInput to get error message from customize error
* The "customize error" is generate by "validator" function
* tokenErrorMessage(error)
*
* @ error
* Type: customize error
* Description: customize error
*
* @ return
* Type: string
* Description: The error message to describe an invalidte token
*/
tokenErrorMessage: PropTypes.func,
/**
* A callback function for getting displayable `label` for a token
* Apply this to customize the token's content
* For example, render token with `icon` or `Additional text`
*
* onGetTokenDisplayLabel(tokenValue, tokenMeta)
*
* @ tokenValue
* Type: any (string | number | object | customize data structure)
* Description: The tokenValue build by `onBuildTokenValue`
*
* @ tokenMeta
* Description: token's meta data
* {
* // A private key for render
* key: string,
*
* // Specific the token is activated for `edit` or not
* activated: boolean,
*
* // Customize data structure built by `onTokenValue Validate`
* // Specific the token's validate status or errorMessage
* error: any,
* }
*
* @ return
* Type: string || react node
* Description: The token's content.
* By default, will apply `getDefaultTokenEditableValue`
*/
onGetTokenDisplayLabel: PropTypes.func,
/**
* A token renderer for TokenInput to rendering a token
* Apply this to customize all token.
* tokenRender(props)
*
* @ props.key
* Type: string
* Description: Each child in an array or iterator should have a unique "key" prop.
*
* @ props.data
* Type: object || string || number
* Description: customize data onject
*
* @ props.meta
* Description: token's meta data
* {
* key, // private key for render
* activated, // Boolean; Specific the token is activated for edit or not
* error // null or ERROR object. Specific the token's validate status
* }
*
* @ props.readOnly
* Type: boolean
* Description: Is readOnly or not
*
* @ props.onStartEdit
* Type: function
* Description: Callback function invoked when user start edit the token
*
* @ props.onEndEdit(data)
* Type: function
* Description: Callback function invoked when user end edit the token
* parameter:
* data => customize data onject for update result of edit.
* Make no change, in case do not provide data.
*
* @ props.onDelete
* Type: function
* Description: Callback function invoked when user delete the token
*
*
* @ return
* Type: node
* Description: The token's content.
*/
tokenRender: PropTypes.func,
/**
* A callback function for getting `string input value`
* from `tokenValue` for the end-user to perform `edit`
*
* onGetTokenEditableValue(tokenValue)
*
* @ tokenValue
* Type: any (string | number | object | customize data structure)
* Description: The tokenValue build by `onBuildTokenValue`
*
* @ return
* Type: string
* Description: The value for end-user to `edit` in an input field
*/
onGetTokenEditableValue: PropTypes.func,
/**
* function for validate data
* validator(data, index, allData)
*
* @ data
* Type: object || string || number
* Description: customize data onject
*
* @ index
* Type: number
* Description: data's array index in allData
*
* @ allData
* Type: array
* Description: array of allData
*
* @ return
* Type: null || customize error
* Description: The error.
* Could be error message to display or error object
* return null means "validate"
*/
validator: PropTypes.func,
/**
* A callback function for getting the error message from the customize error
* The `customize error` is generate by `onTokenValueValidate`
*
* onGetTokenErrorMessage(tokenValue, tokenMeta)
*
* @ error
* Type: customize error
* Description: customize error
*
* @ return
* Type: string | any
* Description: The error message to describe an invalid token
*/
onGetTokenErrorMessage: PropTypes.func,
/**
* Callback function invoked when user typing but not become token yet
* onInputValueChange(value)
*
* @ value
* Type: string
* Description: user input string
*/
onInputValueChange: PropTypes.func,
/**
* A customize react functional component for rendering a token
* Apply this to customize all token function.
*
* customizeTokenComponent={MyToken}
*/
customizeTokenComponent: PropTypes.func,
```
/**
* Callback function invoked data updated
* onTokensUpdate(tokens)
*
* @ tokens
* Type: Array
* Description: Array of token data
*
* token data
* {
* value, // customize data
* meta: {
* key, // private key for render
* activated, // Boolean; Specific the token is activated for edit or not
* error // null or ERROR object. Specific the token's validate status
* }
* }
*/
onTokensUpdate: PropTypes.func
## Default value of optional Props
```javascript
className: '',
readOnly: false,
autoFocus: false,
placeholder: '',
// TokenCreator
separators: [
',',
';',
'\n', // for copy past
'\r', // for copy past
'\r\n', // for copy past
];
onBuildTokenValue: buildDefaultTokenValue,
onInputValueChange: () => {}, // Dummy function
onTokenValueValidate: () => undefined,
// Token
onGetTokenClassName: () => '',
onGetTokenDisplayLabel: getDefaultTokenEditableValue,
onGetTokenEditableValue: getDefaultTokenEditableValue,
onGetTokenErrorMessage: getDefaultTokenErrorMessage,
```
### Priority of props
## Props of customizeTokenComponent
When ```tokenRender``` is provide, following props will be ignored.
```javascript
buildDataFromValue
dataValue
tokenClassName
tokenLabelRender
tokenErrorMessage
// Same as props of TokenInput
readOnly: PropTypes.bool.isRequired,
// tokenValue of token
tokenValue: PropTypes.any.isRequired,
// tokenMeta of token
tokenMeta: PropTypes.object.isRequired,
// Same as props `onGetTokenClassName` of TokenInput
onGetClassName: PropTypes.func.isRequired,
// Same as props `onGetTokenDisplayLabel` of TokenInput
onGetDisplayLabel: PropTypes.func.isRequired,
// Same as props `onGetTokenEditableValue` of TokenInput
onGetEditableValue: PropTypes.func.isRequired,
// Same as props `onGetTokenErrorMessage` of TokenInput
onGetErrorMessage: PropTypes.func.isRequired,
// Editing
// Same as props `onBuildTokenValue` of TokenInput
onBuildTokenValue: PropTypes.func.isRequired,
/**
* A callback function, which should be `invoked` when end-user `start editing`
*
* Note:
* Call this function to tell TokenInput it is start to editing the token.
* As result, TokenInput will set `tokenMeta.activate` to `true`
*
* onEditStart()
*
* @ return
* Type: void
*/
onEditStart: PropTypes.func.isRequired,
/**
* A callback function, which should be `invoked` when end-user `end editing`
*
* Note:
* Call this function to tell TokenInput it is finish editing the token.
* As result, TokenInput will set `tokenMeta.activate` to `false`
*
* onEditEnd(newTokenValue?)
*
* @ newTokenValue
* Type: undefined | any (string | number | object | customize data structure)
* Description:
* The new tokenValue build by `onBuildTokenValue.
* TokenInput will update it, and
* TokenInput will call `onTokenValuesChange`
*
* Note:
* When newTokenValue is `undefined`,
* TokenInput will treat as `Cancel` (End without update newTokenValue).
* The `onTokenValuesChange` will not be called.
*
* @ return
* Type: void
*/
onEditEnd: PropTypes.func.isRequired,
/**
* A callback function, which should be `invoked` when end-user `delete` the token
*
* Note:
* Call this function to tell TokenInput to delete the token.
* As result, TokenInput will remove it, and
* TokenInput will call `onTokenValuesChange` to update tokenValues.
*
* onDelete()
*
* @ return
* Type: void
*/
onDelete: PropTypes.func.isRequired,
```

@@ -328,0 +409,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc