@vickram/react-auto-complete
Version:
React auto-complete plugin
1,737 lines (1,449 loc) • 894 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["AutoComplete"] = factory();
else
root["AutoComplete"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (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 = 18);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (process.env.NODE_ENV !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
if (process.env.NODE_ENV === 'production') {
module.exports = __webpack_require__(21);
} else {
module.exports = __webpack_require__(22);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var emptyFunction = __webpack_require__(1);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = warning;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (process.env.NODE_ENV !== 'production') {
var invariant = __webpack_require__(4);
var warning = __webpack_require__(6);
var ReactPropTypesSecret = __webpack_require__(8);
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if (process.env.NODE_ENV !== 'production') {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
module.exports = checkPropTypes;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var hyphenate = __webpack_require__(28);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var emptyFunction = __webpack_require__(1);
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function listen(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function remove() {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function capture(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if (process.env.NODE_ENV !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function registerDefault() {}
};
module.exports = EventListener;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*
* @param {?DOMDocument} doc Defaults to current document.
* @return {?DOMElement}
*/
function getActiveElement(doc) /*?DOMElement*/{
doc = doc || (typeof document !== 'undefined' ? document : undefined);
if (typeof doc === 'undefined') {
return null;
}
try {
return doc.activeElement || doc.body;
} catch (e) {
return doc.body;
}
}
module.exports = getActiveElement;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*
*/
/*eslint-disable no-self-compare */
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Added the nonzero y check to make Flow happy, but it is redundant
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (is(objA, objB)) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
var isTextNode = __webpack_require__(25);
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*/
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if ('contains' in outerNode) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var camelize = __webpack_require__(29);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @typechecks static-only
*/
/**
* Memoizes the return value of a function that accepts one string argument.
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(19);
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
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__(5);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(23);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _server = __webpack_require__(30);
var _server2 = _interopRequireDefault(_server);
var _propTypes = __webpack_require__(33);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames2 = __webpack_require__(36);
var _classnames3 = _interopRequireDefault(_classnames2);
__webpack_require__(37);
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 _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 WINDOW = global.window;
var helperService = new HelperService();
var AutoComplete = function (_React$Component) {
_inherits(AutoComplete, _React$Component);
function AutoComplete(props) {
_classCallCheck(this, AutoComplete);
var _this = _possibleConstructorReturn(this, (AutoComplete.__proto__ || Object.getPrototypeOf(AutoComplete)).call(this, props));
_this._instanceId = helperService.registerComponent(_this);
_this._bindMethods();
_this._originalSearchText = null;
_this._queryCounter = 0;
_this._endOfPagedList = false;
_this._currentPageIndex = 0;
_this._elementComponent = null;
_this.state = {
searchText: null,
dataLoadInProgress: false,
containerVisible: _this.props.isInline,
selectedIndex: -1,
renderItems: []
};
return _this;
}
_createClass(AutoComplete, [{
key: 'componentDidMount',
value: function componentDidMount() {
this._subscribeDOMEvents();
var publicApi = {
positionDropdown: this._positionDropdownIfVisible.bind(this),
hideDropdown: this._hideDropdown.bind(this)
};
this._safeCallback(this.props.ready, publicApi);
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
if (this.state.positionDropdownUsingJQuery) {
this._positionUsingJQuery();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._unsubscribeDOMEvents();
if (this._container) {
this._container = null;
}
}
}, {
key: 'initialize',
value: function initialize(target) {
this._target = target;
this._subscribeTargetDOMEvents();
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (this.props.isInline) {
return this._getAutoCompleteList();
}
if (_.isEmpty(this.props.children)) {
return _reactDom2.default.createPortal(this._getContainer(), WINDOW.document.body);
}
var children = _react2.default.cloneElement(this.props.children, {
ref: function ref(element) {
if (!element || element === _this2._elementComponent) {
return;
}
_this2._elementComponent = element;
if (element.tagName.toUpperCase() === 'INPUT') {
return _this2.initialize(element);
}
var inputElement = element.querySelector('input');
if (inputElement) {
return _this2.initialize(inputElement);
}
console.warn('No input element was found in props.children collection');
return null;
}
});
return _react2.default.createElement(
_react2.default.Fragment,
null,
children,
this._getContainer()
);
}
}, {
key: '_bindMethods',
value: function _bindMethods() {
this._handleWindowResize = this._handleWindowResize.bind(this);
this._handleDocumentKeyDown = this._handleDocumentKeyDown.bind(this);
this._handleDocumentClick = this._handleDocumentClick.bind(this);
this._handleTargetFocus = this._handleTargetFocus.bind(this);
this._handleTargetInput = this._handleTargetInput.bind(this);
this._handleTargetKeyDown = this._handleTargetKeyDown.bind(this);
this._handleScroll = this._handleScroll.bind(this);
this._safeCallback = this._safeCallback.bind(this);
this._show = this._show.bind(this);
this._queryAndRender = this._queryAndRender.bind(this);
this._getSelectedCssClass = this._getSelectedCssClass.bind(this);
this._selectItem = this._selectItem.bind(this);
this.initialize = this.initialize.bind(this);
}
}, {
key: '_getContainer',
value: function _getContainer() {
var _this3 = this;
var classNames = (0, _classnames3.default)(this.props.containerCssClass, 'auto-complete-container unselectable', { 'auto-complete-absolute-container': !this.props.isInline });
return _react2.default.createElement(
'div',
{
className: classNames,
'data-instance-id': this._instanceId,
style: this._getContainerInlineStyle(),
ref: function ref(x) {
return _this3._container = x;
}
},
this._getAutoCompleteList()
);
}
}, {
key: '_getContainerInlineStyle',
value: function _getContainerInlineStyle() {
return _extends({
display: this.state.containerVisible ? 'block' : 'none',
width: this.state.dropdownWidth
}, this.state.containerPosition);
}
}, {
key: '_getAutoCompleteList',
value: function _getAutoCompleteList() {
var _this4 = this;
return _react2.default.createElement(AutoCompleteList, {
ref: function ref(x) {
return _this4._autoCompleteList = x;
},
searchText: this.state.searchText,
items: this.state.renderItems,
selectedIndex: this.state.selectedIndex,
dropdownHeight: this.state.dropdownHeight,
noMatchItemEnabled: this.props.noMatchItemEnabled,
renderNoMatchItem: this.props.renderNoMatchItem,
getSelectedCssClass: this._getSelectedCssClass,
onItemClick: this._selectItem,
onScroll: this._handleScroll
});
}
}, {
key: '_subscribeDOMEvents',
value: function _subscribeDOMEvents() {
WINDOW.addEventListener(DOM_EVENT.RESIZE, this._handleWindowResize);
WINDOW.document.addEventListener(DOM_EVENT.KEYDOWN, this._handleDocumentKeyDown);
WINDOW.document.addEventListener(DOM_EVENT.CLICK, this._handleDocumentClick);
}
}, {
key: '_subscribeTargetDOMEvents',
value: function _subscribeTargetDOMEvents() {
if (this._target) {
this._target.addEventListener(DOM_EVENT.FOCUS, this._handleTargetFocus);
this._target.addEventListener(DOM_EVENT.INPUT, this._handleTargetInput);
this._target.addEventListener(DOM_EVENT.KEYDOWN, this._handleTargetKeyDown);
}
}
}, {
key: '_unsubscribeDOMEvents',
value: function _unsubscribeDOMEvents() {
WINDOW.removeEventListener(DOM_EVENT.RESIZE, this._handleWindowResize);
WINDOW.document.removeEventListener(DOM_EVENT.KEYDOWN, this._handleDocumentKeyDown);
WINDOW.document.removeEventListener(DOM_EVENT.CLICK, this._handleDocumentClick);
if (this._target) {
this._target.removeEventListener(DOM_EVENT.FOCUS, this._handleTargetFocus);
this._target.removeEventListener(DOM_EVENT.INPUT, this._handleTargetInput);
this._target.removeEventListener(DOM_EVENT.KEYDOWN, this._handleTargetKeyDown);
}
}
}, {
key: '_handleWindowResize',
value: function _handleWindowResize(event) {
if (this.props.hideDropdownOnWindowResize) {
this._autoHide();
}
}
}, {
key: '_handleDocumentKeyDown',
value: function _handleDocumentKeyDown() {
// hide inactive dropdowns when multiple auto complete exist on a page
helperService.hideAllInactive();
}
}, {
key: '_handleDocumentClick',
value: function _handleDocumentClick(event) {
// hide inactive dropdowns when multiple auto complete exist on a page
helperService.hideAllInactive();
// ignore inline
if (this.props.isInline) {
return;
}
// no container. probably unmounted
if (!this._container) {
return;
}
// ignore target click
if (event.target === this._target) {
event.stopPropagation();
return;
}
if (this._containerContainsTarget(event.target)) {
event.stopPropagation();
return;
}
this._autoHide();
}
}, {
key: '_containerContainsTarget',
value: function _containerContainsTarget(target) {
// use native Node.contains
// https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
if (_.isFunction(this._container.contains) && this._container.contains(target)) {
return true;
}
// otherwise use .has() if jQuery is available
if (WINDOW.jQuery) {
var $container = WINDOW.jQuery(this._container);
if (_.isFunction($container.has) && $container.has(target).length > 0) {
return true;
}
}
// assume target is not in container
return false;
}
}, {
key: '_handleTargetFocus',
value: function _handleTargetFocus(event) {
// when the target(textbox) gets focus activate the corresponding container
this._activate();
if (this.props.activateOnFocus) {
this._waitAndQuery(event.target.value, 100);
}
}
}, {
key: '_handleTargetInput',
value: function _handleTargetInput(event) {
this._tryQuery(event.target.value);
}
}, {
key: '_handleTargetKeyDown',
value: function _handleTargetKeyDown(event) {
var keyCode = event.charCode || event.keyCode || 0;
if (ignoreKeyCode(keyCode)) {
return;
}
switch (keyCode) {
case KEYCODE.UPARROW:
this._scrollToPreviousItem();
event.stopPropagation();
event.preventDefault();
break;
case KEYCODE.DOWNARROW:
this._scrollToNextItem();
event.stopPropagation();
event.preventDefault();
break;
case KEYCODE.ENTER:
this._selectItem(this.state.selectedIndex, true);
//prevent postback upon hitting enter
event.preventDefault();
event.stopPropagation();
break;
case KEYCODE.ESCAPE:
this._restoreOriginalText();
this._autoHide();
event.preventDefault();
event.stopPropagation();
break;
default:
break;
}
}
}, {
key: '_handleScroll',
value: function _handleScroll(event) {
if (!this.props.pagingEnabled || !this.state.containerVisible) {
return;
}
var scrollList = event.target;
// scrolled to the bottom?
if (scrollList.offsetHeight + scrollList.scrollTop >= scrollList.scrollHeight) {
this._tryLoadNextPage();
}
}
}, {
key: '_activate',
value: function _activate() {
helperService.setActiveInstanceId(this._instanceId);
// do not reset if the container (dropdown list) is currently visible
// Ex: Switching to a different tab or window and switching back
// again when the dropdown list is visible.
if (!this.state.containerVisible) {
this._originalSearchText = null;
}
}
}, {
key: '_resetAndQuery',
value: function _resetAndQuery(searchText) {
this._empty();
this._reset();
return this._query(searchText, 0);
}
}, {
key: '_show',
value: function _show() {
// the show() method is called after the items are ready for display
// the textbox position can change (ex: window resize) when it has focus
// so reposition the dropdown before it's shown
this._positionDropdown();
// callback
this._safeCallback(this.props.dropdownShown);
}
}, {
key: '_autoHide',
value: function _autoHide() {
if (this.props.autoHideDropdown) {
this._hideDropdown();
}
}
}, {
key: '_empty',
value: function _empty() {
this.setState({
selectedIndex: -1,
renderItems: []
});
}
}, {
key: '_restoreOriginalText',
value: function _restoreOriginalText() {
if (!this._originalSearchText) {
return;
}
this._target.value = this._originalSearchText;
}
}, {
key: '_scrollToPreviousItem',
value: function _scrollToPreviousItem() {
var itemIndex = this._getItemIndexFromOffset(-1);
if (itemIndex === -1) {
return;
}
this._scrollToItem(itemIndex);
}
}, {
key: '_scrollToNextItem',
value: function _scrollToNextItem() {
var itemIndex = this._getItemIndexFromOffset(1);
if (itemIndex === -1) {
return;
}
this._scrollToItem(itemIndex);
if (this._shouldLoadNextPageAtItemIndex(itemIndex)) {
this._loadNextPage();
}
}
/**
* @param {number} itemOffset
*/
}, {
key: '_getItemIndexFromOffset',
value: function _getItemIndexFromOffset(itemOffset) {
var itemIndex = this.state.selectedIndex + itemOffset;
if (itemIndex >= this.state.renderItems.length) {
return -1;
}
return itemIndex;
}
/**
* @param {number} itemIndex
*/
}, {
key: '_scrollToItem',
value: function _scrollToItem(itemIndex) {
if (!this.state.containerVisible) {
return;
}
this._selectItem(itemIndex);
this._autoCompleteList.scrollToItem(itemIndex);
}
}, {
key: '_selectItem',
value: function _selectItem(itemIndex, closeDropdownAndRaiseCallback) {
var item = this.state.renderItems[itemIndex];
if (!item) {
return;
}
this.setState({ selectedIndex: itemIndex });
this._updateTarget(item);
if (closeDropdownAndRaiseCallback) {
this._autoHide();
this._safeCallback(this.props.itemSelected, { item: item.data });
}
}
/**
* @param {number} itemIndex
* @returns {string}
*/
}, {
key: '_getSelectedCssClass',
value: function _getSelectedCssClass(itemIndex) {
return itemIndex === this.state.selectedIndex ? this.props.selectedCssClass : '';
}
/**
* @param {string} searchText
*/
}, {
key: '_tryQuery',
value: function _tryQuery(searchText) {
// query only if minimum number of chars are typed; else hide dropdown
if (this.props.minimumChars === 0 || searchText && searchText.length >= this.props.minimumChars) {
this._waitAndQuery(searchText);
return;
}
this._autoHide();
}
/**
* @param {string} searchText
* @param {number} delay
*/
}, {
key: '_waitAndQuery',
value: function _waitAndQuery(searchText, delay) {
// wait few millisecs before calling query(); this to check if the user has stopped typing
var timer = setTimeout(function () {
// has searchText unchanged?
if (searchText === this._target.value) {
this._resetAndQuery(searchText);
}
//cancel the timeout
clearTimeout(timer);
}.bind(this), delay || 300);
}
}, {
key: '_tryLoadNextPage',
value: function _tryLoadNextPage() {
if (this._shouldLoadNextPage()) {
this._loadNextPage();
}
}
}, {
key: '_loadNextPage',
value: function _loadNextPage() {
return this._query(this._originalSearchText, this._currentPageIndex + 1);
}
/**
* @param {string} searchText
* @param {number} pageIndex
*/
}, {
key: '_query',
value: function _query(searchText, pageIndex) {
/** @type {QueryArgs} */
var queryArgs = {
searchText: searchText,
paging: {
pageIndex: pageIndex,
pageSize: this.props.pageSize
},
queryId: ++this._queryCounter
};
var renderListFn = this.props.pagingEnabled ? this._renderPagedList : this._renderList;
return this._queryAndRender(queryArgs, renderListFn.bind(this, queryArgs));
}
/**
* @param {QueryArgs} queryArgs
* @param {function(Array): Promise} renderListFn
*/
}, {
key: '_queryAndRender',
value: function _queryAndRender(queryArgs, renderListFn) {
var _this5 = this;
var options = this.props;
// backup original search term in case we need to restore if user hits ESCAPE
this._originalSearchText = queryArgs.searchText;
this.setState({
dataLoadInProgress: true,
searchText: queryArgs.searchText
});
this._safeCallback(options.loading);
return Promise.resolve(options.data(queryArgs.searchText, queryArgs.paging)).then(function (data) {
// verify that the queryId did not change since the possibility exists that the
// search text changed before the 'data' promise was resolved. Say, due to a lag
// in getting data from a remote web service.
if (_this5._didQueryIdChange(queryArgs)) {
_this5._autoHide();
return;
}
if (_this5._shouldHideDropdown(queryArgs, data)) {
_this5._autoHide();
return;
}
renderListFn(data).then(_this5._show);
// callback
_this5._safeCallback(options.loadingComplete);
}).catch(function (error) {
// callback
_this5._safeCallback(options.loadingComplete, { error: error });
}).finally(function () {
_this5.setState({ dataLoadInProgress: false });
});
}
/**
* @param {function()} callback
* @param {Object} callbackArgs
*/