path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
ajax/libs/react-native-web/0.17.5/exports/ScrollView/index.js
cdnjs/cdnjs
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import createReactClass from 'create-react-class'; import dismissKeyboard from '../../modules/dismissKeyboard'; import invariant from 'fbjs/lib/invariant'; import mergeRefs from '../../modules/mergeRefs'; import ScrollResponder from '../../modules/ScrollResponder'; import ScrollViewBase from './ScrollViewBase'; import StyleSheet from '../StyleSheet'; import View from '../View'; import React from 'react'; var emptyObject = {}; /* eslint-disable react/prefer-es6-class */ var ScrollView = createReactClass({ displayName: "ScrollView", mixins: [ScrollResponder.Mixin], getInitialState: function getInitialState() { return this.scrollResponderMixinGetInitialState(); }, flashScrollIndicators: function flashScrollIndicators() { this.scrollResponderFlashScrollIndicators(); }, /** * Returns a reference to the underlying scroll responder, which supports * operations like `scrollTo`. All ScrollView-like components should * implement this method so that they can be composed while providing access * to the underlying scroll responder's methods. */ getScrollResponder: function getScrollResponder() { return this; }, getScrollableNode: function getScrollableNode() { return this._scrollNodeRef; }, getInnerViewRef: function getInnerViewRef() { return this._innerViewRef; }, getInnerViewNode: function getInnerViewNode() { return this._innerViewRef; }, getNativeScrollRef: function getNativeScrollRef() { return this._scrollNodeRef; }, /** * Scrolls to a given x, y offset, either immediately or with a smooth animation. * Syntax: * * scrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true}) * * Note: The weird argument signature is due to the fact that, for historical reasons, * the function also accepts separate arguments as as alternative to the options object. * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED. */ scrollTo: function scrollTo(y, x, animated) { if (typeof y === 'number') { console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.'); } else { var _ref = y || emptyObject; x = _ref.x; y = _ref.y; animated = _ref.animated; } this.getScrollResponder().scrollResponderScrollTo({ x: x || 0, y: y || 0, animated: animated !== false }); }, /** * If this is a vertical ScrollView scrolls to the bottom. * If this is a horizontal ScrollView scrolls to the right. * * Use `scrollToEnd({ animated: true })` for smooth animated scrolling, * `scrollToEnd({ animated: false })` for immediate scrolling. * If no options are passed, `animated` defaults to true. */ scrollToEnd: function scrollToEnd(options) { // Default to true var animated = (options && options.animated) !== false; var horizontal = this.props.horizontal; var scrollResponder = this.getScrollResponder(); var scrollResponderNode = scrollResponder.scrollResponderGetScrollableNode(); var x = horizontal ? scrollResponderNode.scrollWidth : 0; var y = horizontal ? 0 : scrollResponderNode.scrollHeight; scrollResponder.scrollResponderScrollTo({ x: x, y: y, animated: animated }); }, render: function render() { var _this$props = this.props, contentContainerStyle = _this$props.contentContainerStyle, horizontal = _this$props.horizontal, onContentSizeChange = _this$props.onContentSizeChange, refreshControl = _this$props.refreshControl, stickyHeaderIndices = _this$props.stickyHeaderIndices, pagingEnabled = _this$props.pagingEnabled, forwardedRef = _this$props.forwardedRef, keyboardDismissMode = _this$props.keyboardDismissMode, onScroll = _this$props.onScroll, other = _objectWithoutPropertiesLoose(_this$props, ["contentContainerStyle", "horizontal", "onContentSizeChange", "refreshControl", "stickyHeaderIndices", "pagingEnabled", "forwardedRef", "keyboardDismissMode", "onScroll"]); if (process.env.NODE_ENV !== 'production' && this.props.style) { var style = StyleSheet.flatten(this.props.style); var childLayoutProps = ['alignItems', 'justifyContent'].filter(function (prop) { return style && style[prop] !== undefined; }); invariant(childLayoutProps.length === 0, "ScrollView child layout (" + JSON.stringify(childLayoutProps) + ") " + 'must be applied through the contentContainerStyle prop.'); } var contentSizeChangeProps = {}; if (onContentSizeChange) { contentSizeChangeProps = { onLayout: this._handleContentOnLayout }; } var hasStickyHeaderIndices = !horizontal && Array.isArray(stickyHeaderIndices); var children = hasStickyHeaderIndices || pagingEnabled ? React.Children.map(this.props.children, function (child, i) { var isSticky = hasStickyHeaderIndices && stickyHeaderIndices.indexOf(i) > -1; if (child != null && (isSticky || pagingEnabled)) { return /*#__PURE__*/React.createElement(View, { style: StyleSheet.compose(isSticky && styles.stickyHeader, pagingEnabled && styles.pagingEnabledChild) }, child); } else { return child; } }) : this.props.children; var contentContainer = /*#__PURE__*/React.createElement(View, _extends({}, contentSizeChangeProps, { children: children, collapsable: false, ref: this._setInnerViewRef, style: StyleSheet.compose(horizontal && styles.contentContainerHorizontal, contentContainerStyle) })); var baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical; var pagingEnabledStyle = horizontal ? styles.pagingEnabledHorizontal : styles.pagingEnabledVertical; var props = _objectSpread(_objectSpread({}, other), {}, { style: [baseStyle, pagingEnabled && pagingEnabledStyle, this.props.style], onTouchStart: this.scrollResponderHandleTouchStart, onTouchMove: this.scrollResponderHandleTouchMove, onTouchEnd: this.scrollResponderHandleTouchEnd, onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag, onScrollEndDrag: this.scrollResponderHandleScrollEndDrag, onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin, onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd, onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder, onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture, onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder, onScroll: this._handleScroll, onResponderGrant: this.scrollResponderHandleResponderGrant, onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest, onResponderTerminate: this.scrollResponderHandleTerminate, onResponderRelease: this.scrollResponderHandleResponderRelease, onResponderReject: this.scrollResponderHandleResponderReject }); var ScrollViewClass = ScrollViewBase; invariant(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined'); var scrollView = /*#__PURE__*/React.createElement(ScrollViewClass, _extends({}, props, { ref: this._setScrollNodeRef }), contentContainer); if (refreshControl) { return /*#__PURE__*/React.cloneElement(refreshControl, { style: props.style }, scrollView); } return scrollView; }, _handleContentOnLayout: function _handleContentOnLayout(e) { var _e$nativeEvent$layout = e.nativeEvent.layout, width = _e$nativeEvent$layout.width, height = _e$nativeEvent$layout.height; this.props.onContentSizeChange(width, height); }, _handleScroll: function _handleScroll(e) { if (process.env.NODE_ENV !== 'production') { if (this.props.onScroll && this.props.scrollEventThrottle == null) { console.log('You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + "cause frame drops, use a bigger number if you don't need as " + 'much precision.'); } } if (this.props.keyboardDismissMode === 'on-drag') { dismissKeyboard(); } this.scrollResponderHandleScroll(e); }, _setInnerViewRef: function _setInnerViewRef(node) { this._innerViewRef = node; }, _setScrollNodeRef: function _setScrollNodeRef(node) { this._scrollNodeRef = node; // ScrollView needs to add more methods to the hostNode in addition to those // added by `usePlatformMethods`. This is temporarily until an API like // `ScrollView.scrollTo(hostNode, { x, y })` is added to React Native. if (node != null) { node.getScrollResponder = this.getScrollResponder; node.getInnerViewNode = this.getInnerViewNode; node.getInnerViewRef = this.getInnerViewRef; node.getNativeScrollRef = this.getNativeScrollRef; node.getScrollableNode = this.getScrollableNode; node.scrollTo = this.scrollTo; node.scrollToEnd = this.scrollToEnd; node.flashScrollIndicators = this.flashScrollIndicators; node.scrollResponderZoomTo = this.scrollResponderZoomTo; node.scrollResponderScrollNativeHandleToKeyboard = this.scrollResponderScrollNativeHandleToKeyboard; } var ref = mergeRefs(this.props.forwardedRef); ref(node); } }); var commonStyle = { flexGrow: 1, flexShrink: 1, // Enable hardware compositing in modern browsers. // Creates a new layer with its own backing surface that can significantly // improve scroll performance. transform: [{ translateZ: 0 }], // iOS native scrolling WebkitOverflowScrolling: 'touch' }; var styles = StyleSheet.create({ baseVertical: _objectSpread(_objectSpread({}, commonStyle), {}, { flexDirection: 'column', overflowX: 'hidden', overflowY: 'auto' }), baseHorizontal: _objectSpread(_objectSpread({}, commonStyle), {}, { flexDirection: 'row', overflowX: 'auto', overflowY: 'hidden' }), contentContainerHorizontal: { flexDirection: 'row' }, stickyHeader: { position: 'sticky', top: 0, zIndex: 10 }, pagingEnabledHorizontal: { scrollSnapType: 'x mandatory' }, pagingEnabledVertical: { scrollSnapType: 'y mandatory' }, pagingEnabledChild: { scrollSnapAlign: 'start' } }); var ForwardedScrollView = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) { return /*#__PURE__*/React.createElement(ScrollView, _extends({}, props, { forwardedRef: forwardedRef })); }); ForwardedScrollView.displayName = 'ScrollView'; export default ForwardedScrollView;
ajax/libs/material-ui/5.0.0-alpha.3/esm/RootRef/RootRef.js
cdnjs/cdnjs
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; import _createClass from "@babel/runtime/helpers/esm/createClass"; import _inherits from "@babel/runtime/helpers/esm/inherits"; import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf"; function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } import * as React from 'react'; import * as ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import { exactProp, refType } from '@material-ui/utils'; import setRef from '../utils/setRef'; /** * ⚠️⚠️⚠️ * If you want the DOM element of a Material-UI component check out * [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element) * first. * * This component uses `findDOMNode` which is deprecated in React.StrictMode. * * Helper component to allow attaching a ref to a * wrapped element to access the underlying DOM element. * * It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801. * For example: * ```jsx * import React from 'react'; * import RootRef from '@material-ui/core/RootRef'; * * function MyComponent() { * const domRef = React.useRef(); * * React.useEffect(() => { * console.log(domRef.current); // DOM node * }, []); * * return ( * <RootRef rootRef={domRef}> * <SomeChildComponent /> * </RootRef> * ); * } * ``` */ var RootRef = /*#__PURE__*/function (_React$Component) { _inherits(RootRef, _React$Component); var _super = _createSuper(RootRef); function RootRef() { _classCallCheck(this, RootRef); return _super.apply(this, arguments); } _createClass(RootRef, [{ key: "componentDidMount", value: function componentDidMount() { this.ref = ReactDOM.findDOMNode(this); setRef(this.props.rootRef, this.ref); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var ref = ReactDOM.findDOMNode(this); if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) { if (prevProps.rootRef !== this.props.rootRef) { setRef(prevProps.rootRef, null); } this.ref = ref; setRef(this.props.rootRef, this.ref); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.ref = null; setRef(this.props.rootRef, null); } }, { key: "render", value: function render() { return this.props.children; } }]); return RootRef; }(React.Component); process.env.NODE_ENV !== "production" ? RootRef.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The wrapped element. */ children: PropTypes.element.isRequired, /** * A ref that points to the first DOM node of the wrapped element. */ rootRef: refType.isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? RootRef.propTypes = exactProp(RootRef.propTypes) : void 0; } export default RootRef;
ajax/libs/primereact/7.2.1/fieldset/fieldset.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { UniqueComponentId, classNames } from 'primereact/utils'; import { CSSTransition } from 'primereact/csstransition'; import { Ripple } from 'primereact/ripple'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Fieldset = /*#__PURE__*/function (_Component) { _inherits(Fieldset, _Component); var _super = _createSuper(Fieldset); function Fieldset(props) { var _this; _classCallCheck(this, Fieldset); _this = _super.call(this, props); var state = { id: props.id }; if (!_this.props.onToggle) { state = _objectSpread(_objectSpread({}, state), {}, { collapsed: props.collapsed }); } _this.state = state; _this.toggle = _this.toggle.bind(_assertThisInitialized(_this)); _this.contentRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Fieldset, [{ key: "toggle", value: function toggle(event) { if (this.props.toggleable) { var collapsed = this.props.onToggle ? this.props.collapsed : this.state.collapsed; if (collapsed) this.expand(event);else this.collapse(event); if (this.props.onToggle) { this.props.onToggle({ originalEvent: event, value: !collapsed }); } } event.preventDefault(); } }, { key: "expand", value: function expand(event) { if (!this.props.onToggle) { this.setState({ collapsed: false }); } if (this.props.onExpand) { this.props.onExpand(event); } } }, { key: "collapse", value: function collapse(event) { if (!this.props.onToggle) { this.setState({ collapsed: true }); } if (this.props.onCollapse) { this.props.onCollapse(event); } } }, { key: "isCollapsed", value: function isCollapsed() { return this.props.toggleable ? this.props.onToggle ? this.props.collapsed : this.state.collapsed : false; } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } } }, { key: "renderContent", value: function renderContent(collapsed) { var id = this.state.id + '_content'; return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.contentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, "in": !collapsed, unmountOnExit: true, options: this.props.transitionOptions }, /*#__PURE__*/React.createElement("div", { ref: this.contentRef, id: id, className: "p-toggleable-content", "aria-hidden": collapsed, role: "region", "aria-labelledby": this.state.id + '_header' }, /*#__PURE__*/React.createElement("div", { className: "p-fieldset-content" }, this.props.children))); } }, { key: "renderToggleIcon", value: function renderToggleIcon(collapsed) { if (this.props.toggleable) { var className = classNames('p-fieldset-toggler pi', { 'pi-plus': collapsed, 'pi-minus': !collapsed }); return /*#__PURE__*/React.createElement("span", { className: className }); } return null; } }, { key: "renderLegendContent", value: function renderLegendContent(collapsed) { if (this.props.toggleable) { var toggleIcon = this.renderToggleIcon(collapsed); var ariaControls = this.state.id + '_content'; return /*#__PURE__*/React.createElement("a", { href: '#' + ariaControls, "aria-controls": ariaControls, id: this.state.id + '_header', "aria-expanded": !collapsed, tabIndex: this.props.toggleable ? null : -1 }, toggleIcon, /*#__PURE__*/React.createElement("span", { className: "p-fieldset-legend-text" }, this.props.legend), /*#__PURE__*/React.createElement(Ripple, null)); } return /*#__PURE__*/React.createElement("span", { className: "p-fieldset-legend-text", id: this.state.id + '_header' }, this.props.legend); } }, { key: "renderLegend", value: function renderLegend(collapsed) { var legendContent = this.renderLegendContent(collapsed); if (this.props.legend != null || this.props.toggleable) { return /*#__PURE__*/React.createElement("legend", { className: "p-fieldset-legend p-unselectable-text", onClick: this.toggle }, legendContent); } } }, { key: "render", value: function render() { var className = classNames('p-fieldset p-component', this.props.className, { 'p-fieldset-toggleable': this.props.toggleable }); var collapsed = this.isCollapsed(); var legend = this.renderLegend(collapsed); var content = this.renderContent(collapsed); return /*#__PURE__*/React.createElement("fieldset", { id: this.props.id, className: className, style: this.props.style, onClick: this.props.onClick }, legend, content); } }]); return Fieldset; }(Component); _defineProperty(Fieldset, "defaultProps", { id: null, legend: null, className: null, style: null, toggleable: null, collapsed: null, transitionOptions: null, onExpand: null, onCollapse: null, onToggle: null, onClick: null }); export { Fieldset };
ajax/libs/primereact/7.0.0-rc.1/card/card.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { ObjectUtils, classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Card = /*#__PURE__*/function (_Component) { _inherits(Card, _Component); var _super = _createSuper(Card); function Card() { _classCallCheck(this, Card); return _super.apply(this, arguments); } _createClass(Card, [{ key: "renderHeader", value: function renderHeader() { if (this.props.header) { return /*#__PURE__*/React.createElement("div", { className: "p-card-header" }, ObjectUtils.getJSXElement(this.props.header, this.props)); } return null; } }, { key: "renderBody", value: function renderBody() { var title = this.props.title && /*#__PURE__*/React.createElement("div", { className: "p-card-title" }, ObjectUtils.getJSXElement(this.props.title, this.props)); var subTitle = this.props.subTitle && /*#__PURE__*/React.createElement("div", { className: "p-card-subtitle" }, ObjectUtils.getJSXElement(this.props.subTitle, this.props)); var children = this.props.children && /*#__PURE__*/React.createElement("div", { className: "p-card-content" }, this.props.children); var footer = this.props.footer && /*#__PURE__*/React.createElement("div", { className: "p-card-footer" }, ObjectUtils.getJSXElement(this.props.footer, this.props)); return /*#__PURE__*/React.createElement("div", { className: "p-card-body" }, title, subTitle, children, footer); } }, { key: "render", value: function render() { var header = this.renderHeader(); var body = this.renderBody(); var className = classNames('p-card p-component', this.props.className); return /*#__PURE__*/React.createElement("div", { className: className, style: this.props.style, id: this.props.id }, header, body); } }]); return Card; }(Component); _defineProperty(Card, "defaultProps", { id: null, header: null, footer: null, title: null, subTitle: null, style: null, className: null }); export { Card };
ajax/libs/material-ui/4.9.4/es/internal/svg-icons/ArrowDropDown.js
cdnjs/cdnjs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M7 10l5 5 5-5z" }), 'ArrowDropDown');
ajax/libs/react-native-web/0.13.1/exports/KeyboardAvoidingView/index.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import View from '../View'; import React from 'react'; var KeyboardAvoidingView = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(KeyboardAvoidingView, _React$Component); function KeyboardAvoidingView() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this; _this.frame = null; _this.onLayout = function (event) { _this.frame = event.nativeEvent.layout; }; return _this; } var _proto = KeyboardAvoidingView.prototype; _proto.relativeKeyboardHeight = function relativeKeyboardHeight(keyboardFrame) { var frame = this.frame; if (!frame || !keyboardFrame) { return 0; } var keyboardY = keyboardFrame.screenY - (this.props.keyboardVerticalOffset || 0); return Math.max(frame.y + frame.height - keyboardY, 0); }; _proto.onKeyboardChange = function onKeyboardChange(event) {}; _proto.render = function render() { var _this$props = this.props, behavior = _this$props.behavior, contentContainerStyle = _this$props.contentContainerStyle, keyboardVerticalOffset = _this$props.keyboardVerticalOffset, rest = _objectWithoutPropertiesLoose(_this$props, ["behavior", "contentContainerStyle", "keyboardVerticalOffset"]); return React.createElement(View, _extends({ onLayout: this.onLayout }, rest)); }; return KeyboardAvoidingView; }(React.Component); export default KeyboardAvoidingView;
ajax/libs/material-ui/4.11.2/esm/RootRef/RootRef.js
cdnjs/cdnjs
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; import _createClass from "@babel/runtime/helpers/esm/createClass"; import _inherits from "@babel/runtime/helpers/esm/inherits"; import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf"; function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } import * as React from 'react'; import * as ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import { exactProp, refType } from '@material-ui/utils'; import setRef from '../utils/setRef'; /** * ⚠️⚠️⚠️ * If you want the DOM element of a Material-UI component check out * [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element) * first. * * This component uses `findDOMNode` which is deprecated in React.StrictMode. * * Helper component to allow attaching a ref to a * wrapped element to access the underlying DOM element. * * It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801. * For example: * ```jsx * import React from 'react'; * import RootRef from '@material-ui/core/RootRef'; * * function MyComponent() { * const domRef = React.useRef(); * * React.useEffect(() => { * console.log(domRef.current); // DOM node * }, []); * * return ( * <RootRef rootRef={domRef}> * <SomeChildComponent /> * </RootRef> * ); * } * ``` */ var RootRef = /*#__PURE__*/function (_React$Component) { _inherits(RootRef, _React$Component); var _super = _createSuper(RootRef); function RootRef() { _classCallCheck(this, RootRef); return _super.apply(this, arguments); } _createClass(RootRef, [{ key: "componentDidMount", value: function componentDidMount() { this.ref = ReactDOM.findDOMNode(this); setRef(this.props.rootRef, this.ref); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var ref = ReactDOM.findDOMNode(this); if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) { if (prevProps.rootRef !== this.props.rootRef) { setRef(prevProps.rootRef, null); } this.ref = ref; setRef(this.props.rootRef, this.ref); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.ref = null; setRef(this.props.rootRef, null); } }, { key: "render", value: function render() { return this.props.children; } }]); return RootRef; }(React.Component); process.env.NODE_ENV !== "production" ? RootRef.propTypes = { /** * The wrapped element. */ children: PropTypes.element.isRequired, /** * A ref that points to the first DOM node of the wrapped element. */ rootRef: refType.isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? RootRef.propTypes = exactProp(RootRef.propTypes) : void 0; } export default RootRef;
ajax/libs/material-ui/4.9.2/es/TableFooter/TableFooter.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Tablelvl2Context from '../Table/Tablelvl2Context'; export const styles = { /* Styles applied to the root element. */ root: { display: 'table-footer-group' } }; const tablelvl2 = { variant: 'footer' }; const TableFooter = React.forwardRef(function TableFooter(props, ref) { const { classes, className, component: Component = 'tfoot' } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "component"]); return React.createElement(Tablelvl2Context.Provider, { value: tablelvl2 }, React.createElement(Component, _extends({ className: clsx(classes.root, className), ref: ref }, other))); }); process.env.NODE_ENV !== "production" ? TableFooter.propTypes = { /** * The content of the component, normally `TableRow`. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType } : void 0; export default withStyles(styles, { name: 'MuiTableFooter' })(TableFooter);
ajax/libs/react-native-web/0.17.1/exports/createElement/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import createDOMProps from '../../modules/createDOMProps'; import React from 'react'; var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = createDOMProps(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return /*#__PURE__*/React.createElement.apply(React, [Component, domProps].concat(children)); }; export default createElement;
ajax/libs/primereact/7.2.1/utils/utils.esm.js
cdnjs/cdnjs
import React from 'react'; function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _nonIterableRest() { 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest(); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function classNames() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args) { var classes = []; for (var i = 0; i < args.length; i++) { var className = args[i]; if (!className) continue; var type = _typeof(className); if (type === 'string' || type === 'number') { classes.push(className); } else if (type === 'object') { var _classes = Array.isArray(className) ? className : Object.entries(className).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], value = _ref2[1]; return !!value ? key : null; }); classes = _classes.length ? classes.concat(_classes.filter(function (c) { return !!c; })) : classes; } } return classes.join(' '); } return undefined; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var DomHandler = /*#__PURE__*/function () { function DomHandler() { _classCallCheck(this, DomHandler); } _createClass(DomHandler, null, [{ key: "innerWidth", value: function innerWidth(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width += parseFloat(style.paddingLeft) + parseFloat(style.paddingRight); return width; } return 0; } }, { key: "width", value: function width(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight); return width; } return 0; } }, { key: "getBrowserLanguage", value: function getBrowserLanguage() { return navigator.userLanguage || navigator.languages && navigator.languages.length && navigator.languages[0] || navigator.language || navigator.browserLanguage || navigator.systemLanguage || 'en'; } }, { key: "getWindowScrollTop", value: function getWindowScrollTop() { var doc = document.documentElement; return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); } }, { key: "getWindowScrollLeft", value: function getWindowScrollLeft() { var doc = document.documentElement; return (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); } }, { key: "getOuterWidth", value: function getOuterWidth(el, margin) { if (el) { var width = el.offsetWidth || el.getBoundingClientRect().width; if (margin) { var style = getComputedStyle(el); width += parseFloat(style.marginLeft) + parseFloat(style.marginRight); } return width; } return 0; } }, { key: "getOuterHeight", value: function getOuterHeight(el, margin) { if (el) { var height = el.offsetHeight || el.getBoundingClientRect().height; if (margin) { var style = getComputedStyle(el); height += parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } return 0; } }, { key: "getClientHeight", value: function getClientHeight(el, margin) { if (el) { var height = el.clientHeight; if (margin) { var style = getComputedStyle(el); height += parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } return 0; } }, { key: "getClientWidth", value: function getClientWidth(el, margin) { if (el) { var width = el.clientWidth; if (margin) { var style = getComputedStyle(el); width += parseFloat(style.marginLeft) + parseFloat(style.marginRight); } return width; } return 0; } }, { key: "getViewport", value: function getViewport() { var win = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], w = win.innerWidth || e.clientWidth || g.clientWidth, h = win.innerHeight || e.clientHeight || g.clientHeight; return { width: w, height: h }; } }, { key: "getOffset", value: function getOffset(el) { if (el) { var rect = el.getBoundingClientRect(); return { top: rect.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0), left: rect.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0) }; } return { top: 'auto', left: 'auto' }; } }, { key: "index", value: function index(element) { if (element) { var children = element.parentNode.childNodes; var num = 0; for (var i = 0; i < children.length; i++) { if (children[i] === element) return num; if (children[i].nodeType === 1) num++; } } return -1; } }, { key: "addMultipleClasses", value: function addMultipleClasses(element, className) { if (element && className) { if (element.classList) { var styles = className.split(' '); for (var i = 0; i < styles.length; i++) { element.classList.add(styles[i]); } } else { var _styles = className.split(' '); for (var _i = 0; _i < _styles.length; _i++) { element.className += ' ' + _styles[_i]; } } } } }, { key: "removeMultipleClasses", value: function removeMultipleClasses(element, className) { if (element && className) { if (element.classList) { var styles = className.split(' '); for (var i = 0; i < styles.length; i++) { element.classList.remove(styles[i]); } } else { var _styles2 = className.split(' '); for (var _i2 = 0; _i2 < _styles2.length; _i2++) { element.className = element.className.replace(new RegExp('(^|\\b)' + _styles2[_i2].split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } } } } }, { key: "addClass", value: function addClass(element, className) { if (element && className) { if (element.classList) element.classList.add(className);else element.className += ' ' + className; } } }, { key: "removeClass", value: function removeClass(element, className) { if (element && className) { if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } } }, { key: "hasClass", value: function hasClass(element, className) { if (element) { if (element.classList) return element.classList.contains(className);else return new RegExp('(^| )' + className + '( |$)', 'gi').test(element.className); } } }, { key: "find", value: function find(element, selector) { return element ? Array.from(element.querySelectorAll(selector)) : []; } }, { key: "findSingle", value: function findSingle(element, selector) { if (element) { return element.querySelector(selector); } return null; } }, { key: "getHeight", value: function getHeight(el) { if (el) { var height = el.offsetHeight; var style = getComputedStyle(el); height -= parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth); return height; } return 0; } }, { key: "getWidth", value: function getWidth(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth); return width; } return 0; } }, { key: "alignOverlay", value: function alignOverlay(overlay, target, appendTo) { var calculateMinWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; if (overlay && target) { if (appendTo === 'self') { this.relativePosition(overlay, target); } else { calculateMinWidth && (overlay.style.minWidth = DomHandler.getOuterWidth(target) + 'px'); this.absolutePosition(overlay, target); } } } }, { key: "absolutePosition", value: function absolutePosition(element, target) { if (element) { var elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : this.getHiddenElementDimensions(element); var elementOuterHeight = elementDimensions.height; var elementOuterWidth = elementDimensions.width; var targetOuterHeight = target.offsetHeight; var targetOuterWidth = target.offsetWidth; var targetOffset = target.getBoundingClientRect(); var windowScrollTop = this.getWindowScrollTop(); var windowScrollLeft = this.getWindowScrollLeft(); var viewport = this.getViewport(); var top, left; if (targetOffset.top + targetOuterHeight + elementOuterHeight > viewport.height) { top = targetOffset.top + windowScrollTop - elementOuterHeight; if (top < 0) { top = windowScrollTop; } element.style.transformOrigin = 'bottom'; } else { top = targetOuterHeight + targetOffset.top + windowScrollTop; element.style.transformOrigin = 'top'; } if (targetOffset.left + targetOuterWidth + elementOuterWidth > viewport.width) left = Math.max(0, targetOffset.left + windowScrollLeft + targetOuterWidth - elementOuterWidth);else left = targetOffset.left + windowScrollLeft; element.style.top = top + 'px'; element.style.left = left + 'px'; } } }, { key: "relativePosition", value: function relativePosition(element, target) { if (element) { var elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : this.getHiddenElementDimensions(element); var targetHeight = target.offsetHeight; var targetOffset = target.getBoundingClientRect(); var viewport = this.getViewport(); var top, left; if (targetOffset.top + targetHeight + elementDimensions.height > viewport.height) { top = -1 * elementDimensions.height; if (targetOffset.top + top < 0) { top = -1 * targetOffset.top; } element.style.transformOrigin = 'bottom'; } else { top = targetHeight; element.style.transformOrigin = 'top'; } if (elementDimensions.width > viewport.width) { // element wider then viewport and cannot fit on screen (align at left side of viewport) left = targetOffset.left * -1; } else if (targetOffset.left + elementDimensions.width > viewport.width) { // element wider then viewport but can be fit on screen (align at right side of viewport) left = (targetOffset.left + elementDimensions.width - viewport.width) * -1; } else { // element fits on screen (align with target) left = 0; } element.style.top = top + 'px'; element.style.left = left + 'px'; } } }, { key: "flipfitCollision", value: function flipfitCollision(element, target) { var _this = this; var my = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'left top'; var at = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'left bottom'; var callback = arguments.length > 4 ? arguments[4] : undefined; var targetOffset = target.getBoundingClientRect(); var viewport = this.getViewport(); var myArr = my.split(' '); var atArr = at.split(' '); var getPositionValue = function getPositionValue(arr, isOffset) { return isOffset ? +arr.substring(arr.search(/(\+|-)/g)) || 0 : arr.substring(0, arr.search(/(\+|-)/g)) || arr; }; var position = { my: { x: getPositionValue(myArr[0]), y: getPositionValue(myArr[1] || myArr[0]), offsetX: getPositionValue(myArr[0], true), offsetY: getPositionValue(myArr[1] || myArr[0], true) }, at: { x: getPositionValue(atArr[0]), y: getPositionValue(atArr[1] || atArr[0]), offsetX: getPositionValue(atArr[0], true), offsetY: getPositionValue(atArr[1] || atArr[0], true) } }; var myOffset = { left: function left() { var totalOffset = position.my.offsetX + position.at.offsetX; return totalOffset + targetOffset.left + (position.my.x === 'left' ? 0 : -1 * (position.my.x === 'center' ? _this.getOuterWidth(element) / 2 : _this.getOuterWidth(element))); }, top: function top() { var totalOffset = position.my.offsetY + position.at.offsetY; return totalOffset + targetOffset.top + (position.my.y === 'top' ? 0 : -1 * (position.my.y === 'center' ? _this.getOuterHeight(element) / 2 : _this.getOuterHeight(element))); } }; var alignWithAt = { count: { x: 0, y: 0 }, left: function left() { var left = myOffset.left(); var scrollLeft = DomHandler.getWindowScrollLeft(); element.style.left = left + scrollLeft + 'px'; if (this.count.x === 2) { element.style.left = scrollLeft + 'px'; this.count.x = 0; } else if (left < 0) { this.count.x++; position.my.x = 'left'; position.at.x = 'right'; position.my.offsetX *= -1; position.at.offsetX *= -1; this.right(); } }, right: function right() { var left = myOffset.left() + DomHandler.getOuterWidth(target); var scrollLeft = DomHandler.getWindowScrollLeft(); element.style.left = left + scrollLeft + 'px'; if (this.count.x === 2) { element.style.left = viewport.width - DomHandler.getOuterWidth(element) + scrollLeft + 'px'; this.count.x = 0; } else if (left + DomHandler.getOuterWidth(element) > viewport.width) { this.count.x++; position.my.x = 'right'; position.at.x = 'left'; position.my.offsetX *= -1; position.at.offsetX *= -1; this.left(); } }, top: function top() { var top = myOffset.top(); var scrollTop = DomHandler.getWindowScrollTop(); element.style.top = top + scrollTop + 'px'; if (this.count.y === 2) { element.style.left = scrollTop + 'px'; this.count.y = 0; } else if (top < 0) { this.count.y++; position.my.y = 'top'; position.at.y = 'bottom'; position.my.offsetY *= -1; position.at.offsetY *= -1; this.bottom(); } }, bottom: function bottom() { var top = myOffset.top() + DomHandler.getOuterHeight(target); var scrollTop = DomHandler.getWindowScrollTop(); element.style.top = top + scrollTop + 'px'; if (this.count.y === 2) { element.style.left = viewport.height - DomHandler.getOuterHeight(element) + scrollTop + 'px'; this.count.y = 0; } else if (top + DomHandler.getOuterHeight(target) > viewport.height) { this.count.y++; position.my.y = 'bottom'; position.at.y = 'top'; position.my.offsetY *= -1; position.at.offsetY *= -1; this.top(); } }, center: function center(axis) { if (axis === 'y') { var top = myOffset.top() + DomHandler.getOuterHeight(target) / 2; element.style.top = top + DomHandler.getWindowScrollTop() + 'px'; if (top < 0) { this.bottom(); } else if (top + DomHandler.getOuterHeight(target) > viewport.height) { this.top(); } } else { var left = myOffset.left() + DomHandler.getOuterWidth(target) / 2; element.style.left = left + DomHandler.getWindowScrollLeft() + 'px'; if (left < 0) { this.left(); } else if (left + DomHandler.getOuterWidth(element) > viewport.width) { this.right(); } } } }; alignWithAt[position.at.x]('x'); alignWithAt[position.at.y]('y'); if (this.isFunction(callback)) { callback(position); } } }, { key: "findCollisionPosition", value: function findCollisionPosition(position) { if (position) { var isAxisY = position === 'top' || position === 'bottom'; var myXPosition = position === 'left' ? 'right' : 'left'; var myYPosition = position === 'top' ? 'bottom' : 'top'; if (isAxisY) { return { axis: 'y', my: "center ".concat(myYPosition), at: "center ".concat(position) }; } return { axis: 'x', my: "".concat(myXPosition, " center"), at: "".concat(position, " center") }; } } }, { key: "getParents", value: function getParents(element) { var parents = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return element['parentNode'] === null ? parents : this.getParents(element.parentNode, parents.concat([element.parentNode])); } }, { key: "getScrollableParents", value: function getScrollableParents(element) { var scrollableParents = []; if (element) { var parents = this.getParents(element); var overflowRegex = /(auto|scroll)/; var overflowCheck = function overflowCheck(node) { var styleDeclaration = node ? getComputedStyle(node) : null; return styleDeclaration && (overflowRegex.test(styleDeclaration.getPropertyValue('overflow')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowX')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowY'))); }; var _iterator = _createForOfIteratorHelper(parents), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var parent = _step.value; var scrollSelectors = parent.nodeType === 1 && parent.dataset['scrollselectors']; if (scrollSelectors) { var selectors = scrollSelectors.split(','); var _iterator2 = _createForOfIteratorHelper(selectors), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var selector = _step2.value; var el = this.findSingle(parent, selector); if (el && overflowCheck(el)) { scrollableParents.push(el); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } if (parent.nodeType !== 9 && overflowCheck(parent)) { scrollableParents.push(parent); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return scrollableParents; } }, { key: "getHiddenElementOuterHeight", value: function getHiddenElementOuterHeight(element) { if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; var elementHeight = element.offsetHeight; element.style.display = 'none'; element.style.visibility = 'visible'; return elementHeight; } return 0; } }, { key: "getHiddenElementOuterWidth", value: function getHiddenElementOuterWidth(element) { if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; var elementWidth = element.offsetWidth; element.style.display = 'none'; element.style.visibility = 'visible'; return elementWidth; } return 0; } }, { key: "getHiddenElementDimensions", value: function getHiddenElementDimensions(element) { var dimensions = {}; if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; dimensions.width = element.offsetWidth; dimensions.height = element.offsetHeight; element.style.display = 'none'; element.style.visibility = 'visible'; } return dimensions; } }, { key: "fadeIn", value: function fadeIn(element, duration) { if (element) { element.style.opacity = 0; var last = +new Date(); var opacity = 0; var tick = function tick() { opacity = +element.style.opacity + (new Date().getTime() - last) / duration; element.style.opacity = opacity; last = +new Date(); if (+opacity < 1) { window.requestAnimationFrame && requestAnimationFrame(tick) || setTimeout(tick, 16); } }; tick(); } } }, { key: "fadeOut", value: function fadeOut(element, duration) { if (element) { var opacity = 1, interval = 50, gap = interval / duration; var fading = setInterval(function () { opacity -= gap; if (opacity <= 0) { opacity = 0; clearInterval(fading); } element.style.opacity = opacity; }, interval); } } }, { key: "getUserAgent", value: function getUserAgent() { return navigator.userAgent; } }, { key: "isIOS", value: function isIOS() { return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window['MSStream']; } }, { key: "isAndroid", value: function isAndroid() { return /(android)/i.test(navigator.userAgent); } }, { key: "isTouchDevice", value: function isTouchDevice() { return 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; } }, { key: "isFunction", value: function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } }, { key: "appendChild", value: function appendChild(element, target) { if (this.isElement(target)) target.appendChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.appendChild(element);else throw new Error('Cannot append ' + target + ' to ' + element); } }, { key: "removeChild", value: function removeChild(element, target) { if (this.isElement(target)) target.removeChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.removeChild(element);else throw new Error('Cannot remove ' + element + ' from ' + target); } }, { key: "isElement", value: function isElement(obj) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? obj instanceof HTMLElement : obj && _typeof(obj) === "object" && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === "string"; } }, { key: "scrollInView", value: function scrollInView(container, item) { var borderTopValue = getComputedStyle(container).getPropertyValue('borderTopWidth'); var borderTop = borderTopValue ? parseFloat(borderTopValue) : 0; var paddingTopValue = getComputedStyle(container).getPropertyValue('paddingTop'); var paddingTop = paddingTopValue ? parseFloat(paddingTopValue) : 0; var containerRect = container.getBoundingClientRect(); var itemRect = item.getBoundingClientRect(); var offset = itemRect.top + document.body.scrollTop - (containerRect.top + document.body.scrollTop) - borderTop - paddingTop; var scroll = container.scrollTop; var elementHeight = container.clientHeight; var itemHeight = this.getOuterHeight(item); if (offset < 0) { container.scrollTop = scroll + offset; } else if (offset + itemHeight > elementHeight) { container.scrollTop = scroll + offset - elementHeight + itemHeight; } } }, { key: "clearSelection", value: function clearSelection() { if (window.getSelection) { if (window.getSelection().empty) { window.getSelection().empty(); } else if (window.getSelection().removeAllRanges && window.getSelection().rangeCount > 0 && window.getSelection().getRangeAt(0).getClientRects().length > 0) { window.getSelection().removeAllRanges(); } } else if (document['selection'] && document['selection'].empty) { try { document['selection'].empty(); } catch (error) {//ignore IE bug } } } }, { key: "calculateScrollbarWidth", value: function calculateScrollbarWidth(el) { if (el) { var style = getComputedStyle(el); return el.offsetWidth - el.clientWidth - parseFloat(style.borderLeftWidth) - parseFloat(style.borderRightWidth); } else { if (this.calculatedScrollbarWidth != null) return this.calculatedScrollbarWidth; var scrollDiv = document.createElement("div"); scrollDiv.className = "p-scrollbar-measure"; document.body.appendChild(scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); this.calculatedScrollbarWidth = scrollbarWidth; return scrollbarWidth; } } }, { key: "getBrowser", value: function getBrowser() { if (!this.browser) { var matched = this.resolveUserAgent(); this.browser = {}; if (matched.browser) { this.browser[matched.browser] = true; this.browser['version'] = matched.version; } if (this.browser['chrome']) { this.browser['webkit'] = true; } else if (this.browser['webkit']) { this.browser['safari'] = true; } } return this.browser; } }, { key: "resolveUserAgent", value: function resolveUserAgent() { var ua = navigator.userAgent.toLowerCase(); var match = /(chrome)[ ]([\w.]+)/.exec(ua) || /(webkit)[ ]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ ]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[1] || "", version: match[2] || "0" }; } }, { key: "isVisible", value: function isVisible(element) { return element && element.offsetParent != null; } }, { key: "isExist", value: function isExist(element) { return element !== null && typeof element !== 'undefined' && element.nodeName && element.parentNode; } }, { key: "hasDOM", value: function hasDOM() { return !!(typeof window !== 'undefined' && window.document && window.document.createElement); } }, { key: "getFocusableElements", value: function getFocusableElements(element) { var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var focusableElements = DomHandler.find(element, "button:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])".concat(selector, ",\n [href][clientHeight][clientWidth]:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n input:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n select:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n textarea:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n [tabIndex]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n [contenteditable]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector)); var visibleFocusableElements = []; var _iterator3 = _createForOfIteratorHelper(focusableElements), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var focusableElement = _step3.value; if (getComputedStyle(focusableElement).display !== "none" && getComputedStyle(focusableElement).visibility !== "hidden") visibleFocusableElements.push(focusableElement); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return visibleFocusableElements; } }, { key: "getFirstFocusableElement", value: function getFirstFocusableElement(element, selector) { var focusableElements = DomHandler.getFocusableElements(element, selector); return focusableElements.length > 0 ? focusableElements[0] : null; } }, { key: "getLastFocusableElement", value: function getLastFocusableElement(element, selector) { var focusableElements = DomHandler.getFocusableElements(element, selector); return focusableElements.length > 0 ? focusableElements[focusableElements.length - 1] : null; } }, { key: "getCursorOffset", value: function getCursorOffset(el, prevText, nextText, currentText) { if (el) { var style = getComputedStyle(el); var ghostDiv = document.createElement('div'); ghostDiv.style.position = 'absolute'; ghostDiv.style.top = '0px'; ghostDiv.style.left = '0px'; ghostDiv.style.visibility = 'hidden'; ghostDiv.style.pointerEvents = 'none'; ghostDiv.style.overflow = style.overflow; ghostDiv.style.width = style.width; ghostDiv.style.height = style.height; ghostDiv.style.padding = style.padding; ghostDiv.style.border = style.border; ghostDiv.style.overflowWrap = style.overflowWrap; ghostDiv.style.whiteSpace = style.whiteSpace; ghostDiv.style.lineHeight = style.lineHeight; ghostDiv.innerHTML = prevText.replace(/\r\n|\r|\n/g, '<br />'); var ghostSpan = document.createElement('span'); ghostSpan.textContent = currentText; ghostDiv.appendChild(ghostSpan); var text = document.createTextNode(nextText); ghostDiv.appendChild(text); document.body.appendChild(ghostDiv); var offsetLeft = ghostSpan.offsetLeft, offsetTop = ghostSpan.offsetTop, clientHeight = ghostSpan.clientHeight; document.body.removeChild(ghostDiv); return { left: Math.abs(offsetLeft - el.scrollLeft), top: Math.abs(offsetTop - el.scrollTop) + clientHeight }; } return { top: 'auto', left: 'auto' }; } }, { key: "invokeElementMethod", value: function invokeElementMethod(element, methodName, args) { element[methodName].apply(element, args); } }, { key: "isClickable", value: function isClickable(element) { var targetNode = element.nodeName; var parentNode = element.parentElement && element.parentElement.nodeName; return targetNode === 'INPUT' || targetNode === 'TEXTAREA' || targetNode === 'BUTTON' || targetNode === 'A' || parentNode === 'INPUT' || parentNode === 'TEXTAREA' || parentNode === 'BUTTON' || parentNode === 'A' || this.hasClass(element, 'p-button') || this.hasClass(element.parentElement, 'p-button') || this.hasClass(element.parentElement, 'p-checkbox') || this.hasClass(element.parentElement, 'p-radiobutton'); } }, { key: "applyStyle", value: function applyStyle(element, style) { if (typeof style === 'string') { element.style.cssText = this.style; } else { for (var prop in this.style) { element.style[prop] = style[prop]; } } } }, { key: "exportCSV", value: function exportCSV(csv, filename) { var blob = new Blob([csv], { type: 'application/csv;charset=utf-8;' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob(blob, filename + '.csv'); } else { var isDownloaded = DomHandler.saveAs({ name: filename + '.csv', src: URL.createObjectURL(blob) }); if (!isDownloaded) { csv = 'data:text/csv;charset=utf-8,' + csv; window.open(encodeURI(csv)); } } } }, { key: "saveAs", value: function saveAs(file) { if (file) { var link = document.createElement('a'); if (link.download !== undefined) { var name = file.name, src = file.src; link.setAttribute('href', src); link.setAttribute('download', name); link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); return true; } } return false; } }, { key: "createInlineStyle", value: function createInlineStyle(nonce) { var styleElement = document.createElement('style'); try { if (!nonce) { nonce = process.env.REACT_APP_CSS_NONCE; } } catch (error) {// NOOP } nonce && styleElement.setAttribute('nonce', nonce); document.head.appendChild(styleElement); return styleElement; } }, { key: "removeInlineStyle", value: function removeInlineStyle(styleElement) { if (this.isExist(styleElement)) { try { document.head.removeChild(styleElement); } catch (error) {// style element may have already been removed in a fast refresh } styleElement = null; } return styleElement; } }]); return DomHandler; }(); var ConnectedOverlayScrollHandler = /*#__PURE__*/function () { function ConnectedOverlayScrollHandler(element) { var listener = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; _classCallCheck(this, ConnectedOverlayScrollHandler); this.element = element; this.listener = listener; } _createClass(ConnectedOverlayScrollHandler, [{ key: "bindScrollListener", value: function bindScrollListener() { this.scrollableParents = DomHandler.getScrollableParents(this.element); for (var i = 0; i < this.scrollableParents.length; i++) { this.scrollableParents[i].addEventListener('scroll', this.listener); } } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollableParents) { for (var i = 0; i < this.scrollableParents.length; i++) { this.scrollableParents[i].removeEventListener('scroll', this.listener); } } } }, { key: "destroy", value: function destroy() { this.unbindScrollListener(); this.element = null; this.listener = null; this.scrollableParents = null; } }]); return ConnectedOverlayScrollHandler; }(); function EventBus () { var allHandlers = new Map(); return { on: function on(type, handler) { var handlers = allHandlers.get(type); if (!handlers) handlers = [handler];else handlers.push(handler); allHandlers.set(type, handlers); }, off: function off(type, handler) { var handlers = allHandlers.get(type); handlers && handlers.splice(handlers.indexOf(handler) >>> 0, 1); }, emit: function emit(type, evt) { var handlers = allHandlers.get(type); handlers && handlers.slice().forEach(function (handler) { return handler(evt); }); } }; } 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 ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function mask(el, options) { var defaultOptions = { mask: null, slotChar: '_', autoClear: true, unmask: false, readOnly: false, onComplete: null, onChange: null, onFocus: null, onBlur: null }; options = _objectSpread$1(_objectSpread$1({}, defaultOptions), options); var tests, partialPosition, len, firstNonMaskPos, defs, androidChrome, lastRequiredNonMaskPos, oldVal, focusText, caretTimeoutId, buffer, defaultBuffer; var caret = function caret(first, last) { var range, begin, end; if (!el.offsetParent || el !== document.activeElement) { return; } if (typeof first === 'number') { begin = first; end = typeof last === 'number' ? last : begin; if (el.setSelectionRange) { el.setSelectionRange(begin, end); } else if (el['createTextRange']) { range = el['createTextRange'](); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } } else { if (el.setSelectionRange) { begin = el.selectionStart; end = el.selectionEnd; } else if (document['selection'] && document['selection'].createRange) { range = document['selection'].createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }; var isCompleted = function isCompleted() { for (var i = firstNonMaskPos; i <= lastRequiredNonMaskPos; i++) { if (tests[i] && buffer[i] === getPlaceholder(i)) { return false; } } return true; }; var getPlaceholder = function getPlaceholder(i) { if (i < options.slotChar.length) { return options.slotChar.charAt(i); } return options.slotChar.charAt(0); }; var getValue = function getValue() { return options.unmask ? getUnmaskedValue() : el && el.value; }; var seekNext = function seekNext(pos) { while (++pos < len && !tests[pos]) { } return pos; }; var seekPrev = function seekPrev(pos) { while (--pos >= 0 && !tests[pos]) { } return pos; }; var shiftL = function shiftL(begin, end) { var i, j; if (begin < 0) { return; } for (i = begin, j = seekNext(end); i < len; i++) { if (tests[i]) { if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; buffer[j] = getPlaceholder(j); } else { break; } j = seekNext(j); } } writeBuffer(); caret(Math.max(firstNonMaskPos, begin)); }; var shiftR = function shiftR(pos) { var i, c, j, t; for (i = pos, c = getPlaceholder(pos); i < len; i++) { if (tests[i]) { j = seekNext(i); t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) { c = t; } else { break; } } } }; var handleAndroidInput = function handleAndroidInput(e) { var curVal = el.value; var pos = caret(); if (oldVal && oldVal.length && oldVal.length > curVal.length) { // a deletion or backspace happened checkVal(true); while (pos.begin > 0 && !tests[pos.begin - 1]) { pos.begin--; } if (pos.begin === 0) { while (pos.begin < firstNonMaskPos && !tests[pos.begin]) { pos.begin++; } } caret(pos.begin, pos.begin); } else { checkVal(true); while (pos.begin < len && !tests[pos.begin]) { pos.begin++; } caret(pos.begin, pos.begin); } if (options.onComplete && isCompleted()) { options.onComplete({ originalEvent: e, value: getValue() }); } }; var onBlur = function onBlur(e) { checkVal(); updateModel(e); if (options.onBlur) { options.onBlur(e); } if (el.value !== focusText) { var event = document.createEvent('HTMLEvents'); event.initEvent('change', true, false); el.dispatchEvent(event); } }; var onKeyDown = function onKeyDown(e) { if (options.readOnly) { return; } var k = e.which || e.keyCode, pos, begin, end; var iPhone = /iphone/i.test(DomHandler.getUserAgent()); oldVal = el.value; //backspace, delete, and escape get special treatment if (k === 8 || k === 46 || iPhone && k === 127) { pos = caret(); begin = pos.begin; end = pos.end; if (end - begin === 0) { begin = k !== 46 ? seekPrev(begin) : end = seekNext(begin - 1); end = k === 46 ? seekNext(end) : end; } clearBuffer(begin, end); shiftL(begin, end - 1); updateModel(e); e.preventDefault(); } else if (k === 13) { // enter onBlur(e); updateModel(e); } else if (k === 27) { // escape el.value = focusText; caret(0, checkVal()); updateModel(e); e.preventDefault(); } }; var onKeyPress = function onKeyPress(e) { if (options.readOnly) { return; } var k = e.which || e.keyCode, pos = caret(), p, c, next, completed; if (e.ctrlKey || e.altKey || e.metaKey || k < 32) { //Ignore return; } else if (k && k !== 13) { if (pos.end - pos.begin !== 0) { clearBuffer(pos.begin, pos.end); shiftL(pos.begin, pos.end - 1); } p = seekNext(pos.begin - 1); if (p < len) { c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); next = seekNext(p); if (/android/i.test(DomHandler.getUserAgent())) { //Path for CSP Violation on FireFox OS 1.1 var proxy = function proxy() { caret(next); }; setTimeout(proxy, 0); } else { caret(next); } if (pos.begin <= lastRequiredNonMaskPos) { completed = isCompleted(); } } } e.preventDefault(); } updateModel(e); if (options.onComplete && completed) { options.onComplete({ originalEvent: e, value: getValue() }); } }; var clearBuffer = function clearBuffer(start, end) { var i; for (i = start; i < end && i < len; i++) { if (tests[i]) { buffer[i] = getPlaceholder(i); } } }; var writeBuffer = function writeBuffer() { el.value = buffer.join(''); }; var checkVal = function checkVal(allow) { //try to place characters where they belong var test = el.value, lastMatch = -1, i, c, pos; for (i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = getPlaceholder(i); while (pos++ < test.length) { c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) { clearBuffer(i + 1, len); break; } } else { if (buffer[i] === test.charAt(pos)) { pos++; } if (i < partialPosition) { lastMatch = i; } } } if (allow) { writeBuffer(); } else if (lastMatch + 1 < partialPosition) { if (options.autoClear || buffer.join('') === defaultBuffer) { // Invalid value. Remove it and replace it with the // mask, which is the default behavior. if (el.value) el.value = ''; clearBuffer(0, len); } else { // Invalid value, but we opt to show the value to the // user and allow them to correct their mistake. writeBuffer(); } } else { writeBuffer(); el.value = el.value.substring(0, lastMatch + 1); } return partialPosition ? i : firstNonMaskPos; }; var onFocus = function onFocus(e) { if (options.readOnly) { return; } clearTimeout(caretTimeoutId); var pos; focusText = el.value; pos = checkVal(); caretTimeoutId = setTimeout(function () { if (el !== document.activeElement) { return; } writeBuffer(); if (pos === options.mask.replace("?", "").length) { caret(0, pos); } else { caret(pos); } }, 10); if (options.onFocus) { options.onFocus(e); } }; var onInput = function onInput(event) { if (androidChrome) handleAndroidInput(event);else handleInputChange(event); }; var handleInputChange = function handleInputChange(e) { if (options.readOnly) { return; } var pos = checkVal(true); caret(pos); updateModel(e); if (options.onComplete && isCompleted()) { options.onComplete({ originalEvent: e, value: getValue() }); } }; var getUnmaskedValue = function getUnmaskedValue() { var unmaskedBuffer = []; for (var i = 0; i < buffer.length; i++) { var c = buffer[i]; if (tests[i] && c !== getPlaceholder(i)) { unmaskedBuffer.push(c); } } return unmaskedBuffer.join(''); }; var updateModel = function updateModel(e) { if (options.onChange) { var val = getValue().replace(options.slotChar, ''); options.onChange({ originalEvent: e, value: defaultBuffer !== val ? val : '' }); } }; var bindEvents = function bindEvents() { el.addEventListener('focus', onFocus); el.addEventListener('blur', onBlur); el.addEventListener('keydown', onKeyDown); el.addEventListener('keypress', onKeyPress); el.addEventListener('input', onInput); el.addEventListener('paste', handleInputChange); }; var unbindEvents = function unbindEvents() { el.removeEventListener('focus', onFocus); el.removeEventListener('blur', onBlur); el.removeEventListener('keydown', onKeyDown); el.removeEventListener('keypress', onKeyPress); el.removeEventListener('input', onInput); el.removeEventListener('paste', handleInputChange); }; var init = function init() { tests = []; partialPosition = options.mask.length; len = options.mask.length; firstNonMaskPos = null; defs = { '9': '[0-9]', 'a': '[A-Za-z]', '*': '[A-Za-z0-9]' }; var ua = DomHandler.getUserAgent(); androidChrome = /chrome/i.test(ua) && /android/i.test(ua); var maskTokens = options.mask.split(''); for (var i = 0; i < maskTokens.length; i++) { var c = maskTokens[i]; if (c === '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if (firstNonMaskPos === null) { firstNonMaskPos = tests.length - 1; } if (i < partialPosition) { lastRequiredNonMaskPos = tests.length - 1; } } else { tests.push(null); } } buffer = []; for (var _i = 0; _i < maskTokens.length; _i++) { var _c = maskTokens[_i]; if (_c !== '?') { if (defs[_c]) buffer.push(getPlaceholder(_i));else buffer.push(_c); } } defaultBuffer = buffer.join(''); }; if (el && options.mask) { init(); bindEvents(); } return { init: init, bindEvents: bindEvents, unbindEvents: unbindEvents, updateModel: updateModel, getValue: getValue }; } var ObjectUtils = /*#__PURE__*/function () { function ObjectUtils() { _classCallCheck(this, ObjectUtils); } _createClass(ObjectUtils, null, [{ key: "equals", value: function equals(obj1, obj2, field) { if (field && obj1 && _typeof(obj1) === 'object' && obj2 && _typeof(obj2) === 'object') return this.resolveFieldData(obj1, field) === this.resolveFieldData(obj2, field);else return this.deepEquals(obj1, obj2); } }, { key: "deepEquals", value: function deepEquals(a, b) { if (a === b) return true; if (a && b && _typeof(a) == 'object' && _typeof(b) == 'object') { var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; if (arrA && arrB) { length = a.length; if (length !== b.length) return false; for (i = length; i-- !== 0;) { if (!this.deepEquals(a[i], b[i])) return false; } return true; } if (arrA !== arrB) return false; var dateA = a instanceof Date, dateB = b instanceof Date; if (dateA !== dateB) return false; if (dateA && dateB) return a.getTime() === b.getTime(); var regexpA = a instanceof RegExp, regexpB = b instanceof RegExp; if (regexpA !== regexpB) return false; if (regexpA && regexpB) return a.toString() === b.toString(); var keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) { if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; } for (i = length; i-- !== 0;) { key = keys[i]; if (!this.deepEquals(a[key], b[key])) return false; } return true; } /*eslint no-self-compare: "off"*/ return a !== a && b !== b; } }, { key: "resolveFieldData", value: function resolveFieldData(data, field) { if (data && Object.keys(data).length && field) { if (this.isFunction(field)) { return field(data); } else if (field.indexOf('.') === -1) { return data[field]; } else { var fields = field.split('.'); var value = data; for (var i = 0, len = fields.length; i < len; ++i) { if (value == null) { return null; } value = value[fields[i]]; } return value; } } else { return null; } } }, { key: "isFunction", value: function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } }, { key: "findDiffKeys", value: function findDiffKeys(obj1, obj2) { if (!obj1 || !obj2) { return {}; } return Object.keys(obj1).filter(function (key) { return !obj2.hasOwnProperty(key); }).reduce(function (result, current) { result[current] = obj1[current]; return result; }, {}); } }, { key: "reorderArray", value: function reorderArray(value, from, to) { var target; if (value && from !== to) { if (to >= value.length) { target = to - value.length; while (target-- + 1) { value.push(undefined); } } value.splice(to, 0, value.splice(from, 1)[0]); } } }, { key: "findIndexInList", value: function findIndexInList(value, list, dataKey) { var _this = this; if (list) { return dataKey ? list.findIndex(function (item) { return _this.equals(item, value, dataKey); }) : list.findIndex(function (item) { return item === value; }); } return -1; } }, { key: "getJSXElement", value: function getJSXElement(obj) { for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } return this.isFunction(obj) ? obj.apply(void 0, params) : obj; } }, { key: "getPropValue", value: function getPropValue(obj) { for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { params[_key2 - 1] = arguments[_key2]; } return this.isFunction(obj) ? obj.apply(void 0, params) : obj; } }, { key: "getRefElement", value: function getRefElement(ref) { if (ref) { return _typeof(ref) === 'object' && ref.hasOwnProperty('current') ? ref.current : ref; } return null; } }, { key: "removeAccents", value: function removeAccents(str) { if (str && str.search(/[\xC0-\xFF]/g) > -1) { str = str.replace(/[\xC0-\xC5]/g, "A").replace(/[\xC6]/g, "AE").replace(/[\xC7]/g, "C").replace(/[\xC8-\xCB]/g, "E").replace(/[\xCC-\xCF]/g, "I").replace(/[\xD0]/g, "D").replace(/[\xD1]/g, "N").replace(/[\xD2-\xD6\xD8]/g, "O").replace(/[\xD9-\xDC]/g, "U").replace(/[\xDD]/g, "Y").replace(/[\xDE]/g, "P").replace(/[\xE0-\xE5]/g, "a").replace(/[\xE6]/g, "ae").replace(/[\xE7]/g, "c").replace(/[\xE8-\xEB]/g, "e").replace(/[\xEC-\xEF]/g, "i").replace(/[\xF1]/g, "n").replace(/[\xF2-\xF6\xF8]/g, "o").replace(/[\xF9-\xFC]/g, "u").replace(/[\xFE]/g, "p").replace(/[\xFD\xFF]/g, "y"); } return str; } }, { key: "isEmpty", value: function isEmpty(value) { return value === null || value === undefined || value === '' || Array.isArray(value) && value.length === 0 || !(value instanceof Date) && _typeof(value) === 'object' && Object.keys(value).length === 0; } }, { key: "isNotEmpty", value: function isNotEmpty(value) { return !this.isEmpty(value); } /** * Compare value1 and value2 ascending by default (1) or pass in order as -1 for descending. * * @param {any} value1 the first value * @param {any} value2 the second value * @param {number | undefined} order by default ascending (1) set to descending (-1) * @param {string | undefined} locale the locale to use (default to browser locale if null) * @returns either 0, 1 or -1 for comparing the two values */ }, { key: "sort", value: function sort(value1, value2) { var order = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; var locale = arguments.length > 3 ? arguments[3] : undefined; var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, locale, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return order * result; } }]); return ObjectUtils; }(); function _extends() { _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; }; return _extends.apply(this, arguments); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var IconUtils = /*#__PURE__*/function () { function IconUtils() { _classCallCheck(this, IconUtils); } _createClass(IconUtils, null, [{ key: "getJSXIcon", value: function getJSXIcon(icon, iconProps, options) { var content = null; if (icon) { var iconType = _typeof(icon); var className = classNames(iconProps.className, iconType === 'string' && icon); content = /*#__PURE__*/React.createElement("span", _extends({}, iconProps, { className: className })); if (iconType !== 'string') { var defaultContentOptions = _objectSpread({ iconProps: iconProps, element: content }, options); return ObjectUtils.getJSXElement(icon, defaultContentOptions); } } return content; } }]); return IconUtils; }(); var lastId = 0; function UniqueComponentId () { var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'pr_id_'; lastId++; return "".concat(prefix).concat(lastId); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread(); } function handler() { var zIndexes = []; var generateZIndex = function generateZIndex(key, autoZIndex) { var baseZIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 999; var lastZIndex = getLastZIndex(key, autoZIndex, baseZIndex); var newZIndex = lastZIndex.value + (lastZIndex.key === key ? 0 : baseZIndex) + 1; zIndexes.push({ key: key, value: newZIndex }); return newZIndex; }; var revertZIndex = function revertZIndex(zIndex) { zIndexes = zIndexes.filter(function (obj) { return obj.value !== zIndex; }); }; var getCurrentZIndex = function getCurrentZIndex(key, autoZIndex) { return getLastZIndex(key, autoZIndex).value; }; var getLastZIndex = function getLastZIndex(key, autoZIndex) { var baseZIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; return _toConsumableArray(zIndexes).reverse().find(function (obj) { return autoZIndex ? true : obj.key === key; }) || { key: key, value: baseZIndex }; }; var getZIndex = function getZIndex(el) { return el ? parseInt(el.style.zIndex, 10) || 0 : 0; }; return { get: getZIndex, set: function set(key, el, autoZIndex, baseZIndex) { if (el) { el.style.zIndex = String(generateZIndex(key, autoZIndex, baseZIndex)); } }, clear: function clear(el) { if (el) { revertZIndex(ZIndexUtils.get(el)); el.style.zIndex = ''; } }, getCurrent: function getCurrent(key, autoZIndex) { return getCurrentZIndex(key, autoZIndex); } }; } var ZIndexUtils = handler(); export { ConnectedOverlayScrollHandler, DomHandler, EventBus, IconUtils, ObjectUtils, UniqueComponentId, ZIndexUtils, classNames, mask };
ajax/libs/material-ui/5.0.0-alpha.4/es/utils/createSvgIcon.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import SvgIcon from '../SvgIcon'; /** * Private module reserved for @material-ui/x packages. */ export default function createSvgIcon(path, displayName) { const Component = (props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({ ref: ref }, props), path); if (process.env.NODE_ENV !== 'production') { // Need to set `displayName` on the inner component for React.memo. // React prior to 16.14 ignores `displayName` on the wrapper. Component.displayName = `${displayName}Icon`; } Component.muiName = SvgIcon.muiName; return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component)); }
ajax/libs/react-native-web/0.13.11/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AppContainer from './AppContainer'; import invariant from 'fbjs/lib/invariant'; import render, { hydrate } from '../render'; import styleResolver from '../StyleSheet/styleResolver'; import React from 'react'; export default function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? hydrate : render; invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn(React.createElement(AppContainer, { rootTag: rootTag, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)), rootTag, callback); } export function getApplication(RootComponent, initialProps, WrapperComponent) { var element = React.createElement(AppContainer, { rootTag: {}, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = styleResolver.getStyleSheet(); return React.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
ajax/libs/react-native-web/0.11.5/exports/Switch/index.js
cdnjs/cdnjs
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import applyNativeMethods from '../../modules/applyNativeMethods'; import ColorPropType from '../ColorPropType'; import createElement from '../createElement'; import multiplyStyleLengthValue from '../../modules/multiplyStyleLengthValue'; import StyleSheet from '../StyleSheet'; import UIManager from '../UIManager'; import View from '../View'; import ViewPropTypes from '../ViewPropTypes'; import React, { Component } from 'react'; import { bool, func } from 'prop-types'; var emptyObject = {}; var thumbDefaultBoxShadow = '0px 1px 3px rgba(0,0,0,0.5)'; var thumbFocusedBoxShadow = thumbDefaultBoxShadow + ", 0 0 0 10px rgba(0,0,0,0.1)"; var Switch = /*#__PURE__*/ function (_Component) { _inheritsLoose(Switch, _Component); function Switch() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _Component.call.apply(_Component, [this].concat(args)) || this; _this._handleChange = function (event) { var onValueChange = _this.props.onValueChange; onValueChange && onValueChange(event.nativeEvent.target.checked); }; _this._handleFocusState = function (event) { var isFocused = event.nativeEvent.type === 'focus'; var boxShadow = isFocused ? thumbFocusedBoxShadow : thumbDefaultBoxShadow; if (_this._thumbElement) { _this._thumbElement.setNativeProps({ style: { boxShadow: boxShadow } }); } }; _this._setCheckboxRef = function (element) { _this._checkboxElement = element; }; _this._setThumbRef = function (element) { _this._thumbElement = element; }; return _this; } var _proto = Switch.prototype; _proto.blur = function blur() { UIManager.blur(this._checkboxElement); }; _proto.focus = function focus() { UIManager.focus(this._checkboxElement); }; _proto.render = function render() { var _this$props = this.props, accessibilityLabel = _this$props.accessibilityLabel, activeThumbColor = _this$props.activeThumbColor, activeTrackColor = _this$props.activeTrackColor, disabled = _this$props.disabled, onValueChange = _this$props.onValueChange, style = _this$props.style, thumbColor = _this$props.thumbColor, trackColor = _this$props.trackColor, value = _this$props.value, onTintColor = _this$props.onTintColor, thumbTintColor = _this$props.thumbTintColor, tintColor = _this$props.tintColor, other = _objectWithoutPropertiesLoose(_this$props, ["accessibilityLabel", "activeThumbColor", "activeTrackColor", "disabled", "onValueChange", "style", "thumbColor", "trackColor", "value", "onTintColor", "thumbTintColor", "tintColor"]); var _StyleSheet$flatten = StyleSheet.flatten(style), styleHeight = _StyleSheet$flatten.height, styleWidth = _StyleSheet$flatten.width; var height = styleHeight || 20; var minWidth = multiplyStyleLengthValue(height, 2); var width = styleWidth > minWidth ? styleWidth : minWidth; var trackBorderRadius = multiplyStyleLengthValue(height, 0.5); var trackCurrentColor = value ? onTintColor || activeTrackColor : tintColor || trackColor; var thumbCurrentColor = value ? activeThumbColor : thumbTintColor || thumbColor; var thumbHeight = height; var thumbWidth = thumbHeight; var rootStyle = [styles.root, style, { height: height, width: width }, disabled && styles.cursorDefault]; var trackStyle = [styles.track, { backgroundColor: trackCurrentColor, borderRadius: trackBorderRadius }, disabled && styles.disabledTrack]; var thumbStyle = [styles.thumb, { backgroundColor: thumbCurrentColor, height: thumbHeight, width: thumbWidth }, disabled && styles.disabledThumb]; var nativeControl = createElement('input', { accessibilityLabel: accessibilityLabel, checked: value, disabled: disabled, onBlur: this._handleFocusState, onChange: this._handleChange, onFocus: this._handleFocusState, ref: this._setCheckboxRef, style: [styles.nativeControl, styles.cursorInherit], type: 'checkbox' }); return React.createElement(View, _extends({}, other, { style: rootStyle }), React.createElement(View, { style: trackStyle }), React.createElement(View, { ref: this._setThumbRef, style: [thumbStyle, value && styles.thumbOn, { marginStart: value ? multiplyStyleLengthValue(thumbWidth, -1) : 0 }] }), nativeControl); }; return Switch; }(Component); Switch.displayName = 'Switch'; Switch.defaultProps = { activeThumbColor: '#009688', activeTrackColor: '#A3D3CF', disabled: false, style: emptyObject, thumbColor: '#FAFAFA', trackColor: '#939393', value: false }; Switch.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, ViewPropTypes, { activeThumbColor: ColorPropType, activeTrackColor: ColorPropType, disabled: bool, onValueChange: func, thumbColor: ColorPropType, trackColor: ColorPropType, value: bool, /* eslint-disable react/sort-prop-types */ // Equivalent of 'activeTrackColor' onTintColor: ColorPropType, // Equivalent of 'thumbColor' thumbTintColor: ColorPropType, // Equivalent of 'trackColor' tintColor: ColorPropType }) : {}; var styles = StyleSheet.create({ root: { cursor: 'pointer', userSelect: 'none' }, cursorDefault: { cursor: 'default' }, cursorInherit: { cursor: 'inherit' }, track: _objectSpread({}, StyleSheet.absoluteFillObject, { height: '70%', margin: 'auto', transitionDuration: '0.1s', width: '100%' }), disabledTrack: { backgroundColor: '#D5D5D5' }, thumb: { alignSelf: 'flex-start', borderRadius: '100%', boxShadow: thumbDefaultBoxShadow, start: '0%', transform: [{ translateZ: 0 }], transitionDuration: '0.1s' }, thumbOn: { start: '100%' }, disabledThumb: { backgroundColor: '#BDBDBD' }, nativeControl: _objectSpread({}, StyleSheet.absoluteFillObject, { height: '100%', margin: 0, opacity: 0, padding: 0, width: '100%' }) }); export default applyNativeMethods(Switch);
ajax/libs/material-ui/4.9.4/es/DialogContentText/DialogContentText.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import PropTypes from 'prop-types'; import withStyles from '../styles/withStyles'; import Typography from '../Typography'; export const styles = { /* Styles applied to the root element. */ root: { marginBottom: 12 } }; const DialogContentText = React.forwardRef(function DialogContentText(props, ref) { return React.createElement(Typography, _extends({ component: "p", variant: "body1", color: "textSecondary", ref: ref }, props)); }); process.env.NODE_ENV !== "production" ? DialogContentText.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired } : void 0; export default withStyles(styles, { name: 'MuiDialogContentText' })(DialogContentText);
ajax/libs/primereact/6.5.0-rc.1/menu/menu.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, ZIndexUtils, ConnectedOverlayScrollHandler, classNames, ObjectUtils } from 'primereact/utils'; import { CSSTransition } from 'primereact/csstransition'; import OverlayEventBus from 'primereact/overlayeventbus'; import { Portal } from 'primereact/portal'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } var propTypes = {exports: {}}; /** * 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$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; /** * 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 = ReactPropTypesSecret_1; function emptyFunction() {} function emptyFunctionWithReset() {} emptyFunctionWithReset.resetWarningCache = emptyFunction; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } var err = 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' ); err.name = 'Invariant Violation'; throw err; } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, elementType: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim, checkPropTypes: emptyFunctionWithReset, resetWarningCache: emptyFunction }; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /** * 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. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod propTypes.exports = factoryWithThrowingShims(); } var PropTypes = propTypes.exports; function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Menu = /*#__PURE__*/function (_Component) { _inherits(Menu, _Component); var _super = _createSuper(Menu); function Menu(props) { var _this; _classCallCheck(this, Menu); _this = _super.call(this, props); _this.state = { visible: !props.popup }; _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExit = _this.onExit.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); _this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this)); _this.menuRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Menu, [{ key: "onPanelClick", value: function onPanelClick(event) { if (this.props.popup) { OverlayEventBus.emit('overlay-click', { originalEvent: event, target: this.target }); } } }, { key: "onItemClick", value: function onItemClick(event, item) { if (item.disabled) { event.preventDefault(); return; } if (!item.url) { event.preventDefault(); } if (item.command) { item.command({ originalEvent: event, item: item }); } if (this.props.popup) { this.hide(event); } } }, { key: "onItemKeyDown", value: function onItemKeyDown(event, item) { var listItem = event.currentTarget.parentElement; switch (event.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.children[0].focus(); } event.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.children[0].focus(); } event.preventDefault(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || !DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || !DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "toggle", value: function toggle(event) { if (this.props.popup) { if (this.state.visible) this.hide(event);else this.show(event); } } }, { key: "show", value: function show(event) { var _this2 = this; this.target = event.currentTarget; var currentEvent = event; this.setState({ visible: true }, function () { if (_this2.props.onShow) { _this2.props.onShow(currentEvent); } }); } }, { key: "hide", value: function hide(event) { var _this3 = this; var currentEvent = event; this.setState({ visible: false }, function () { if (_this3.props.onHide) { _this3.props.onHide(currentEvent); } }); } }, { key: "onEnter", value: function onEnter() { ZIndexUtils.set('menu', this.menuRef.current, this.props.baseZIndex); DomHandler.absolutePosition(this.menuRef.current, this.target); } }, { key: "onEntered", value: function onEntered() { this.bindDocumentListeners(); this.bindScrollListener(); } }, { key: "onExit", value: function onExit() { this.target = null; this.unbindDocumentListeners(); this.unbindScrollListener(); } }, { key: "onExited", value: function onExited() { ZIndexUtils.clear(this.menuRef.current); } }, { key: "bindDocumentListeners", value: function bindDocumentListeners() { var _this4 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this4.state.visible && _this4.isOutsideClicked(event)) { _this4.hide(event); } }; document.addEventListener('click', this.documentClickListener); } if (!this.documentResizeListener) { this.documentResizeListener = function (event) { if (_this4.state.visible && !DomHandler.isAndroid()) { _this4.hide(event); } }; window.addEventListener('resize', this.documentResizeListener); } } }, { key: "unbindDocumentListeners", value: function unbindDocumentListeners() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } if (this.documentResizeListener) { window.removeEventListener('resize', this.documentResizeListener); this.documentResizeListener = null; } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this5 = this; if (!this.scrollHandler) { this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, function (event) { if (_this5.state.visible) { _this5.hide(event); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "isOutsideClicked", value: function isOutsideClicked(event) { return this.menuRef && this.menuRef.current && !(this.menuRef.current.isSameNode(event.target) || this.menuRef.current.contains(event.target)); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentListeners(); if (this.scrollHandler) { this.scrollHandler.destroy(); this.scrollHandler = null; } ZIndexUtils.clear(this.menuRef.current); } }, { key: "renderSubmenu", value: function renderSubmenu(submenu, index) { var _this6 = this; var className = classNames('p-submenu-header', { 'p-disabled': submenu.disabled }, submenu.className); var items = submenu.items.map(function (item, index) { return _this6.renderMenuitem(item, index); }); return /*#__PURE__*/React.createElement(React.Fragment, { key: submenu.label + '_' + index }, /*#__PURE__*/React.createElement("li", { className: className, style: submenu.style, role: "presentation", "aria-disabled": submenu.disabled }, submenu.label), items); } }, { key: "renderSeparator", value: function renderSeparator(index) { return /*#__PURE__*/React.createElement("li", { key: 'separator_' + index, className: "p-menu-separator", role: "separator" }); } }, { key: "renderMenuitem", value: function renderMenuitem(item, index) { var _this7 = this; var className = classNames('p-menuitem', item.className); var linkClassName = classNames('p-menuitem-link', { 'p-disabled': item.disabled }); var iconClassName = classNames('p-menuitem-icon', item.icon); var icon = item.icon && /*#__PURE__*/React.createElement("span", { className: iconClassName }); var label = item.label && /*#__PURE__*/React.createElement("span", { className: "p-menuitem-text" }, item.label); var tabIndex = item.disabled ? null : 0; var content = /*#__PURE__*/React.createElement("a", { href: item.url || '#', className: linkClassName, role: "menuitem", target: item.target, onClick: function onClick(event) { return _this7.onItemClick(event, item); }, onKeyDown: function onKeyDown(event) { return _this7.onItemKeyDown(event, item); }, tabIndex: tabIndex, "aria-disabled": item.disabled }, icon, label); if (item.template) { var defaultContentOptions = { onClick: function onClick(event) { return _this7.onItemClick(event, item); }, onKeyDown: function onKeyDown(event) { return _this7.onItemKeyDown(event, item); }, className: linkClassName, tabIndex: tabIndex, labelClassName: 'p-menuitem-text', iconClassName: iconClassName, element: content, props: this.props }; content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions); } return /*#__PURE__*/React.createElement("li", { key: item.label + '_' + index, className: className, style: item.style, role: "none" }, content); } }, { key: "renderItem", value: function renderItem(item, index) { if (item.separator) { return this.renderSeparator(index); } else { if (item.items) return this.renderSubmenu(item, index);else return this.renderMenuitem(item, index); } } }, { key: "renderMenu", value: function renderMenu() { var _this8 = this; return this.props.model.map(function (item, index) { return _this8.renderItem(item, index); }); } }, { key: "renderElement", value: function renderElement() { if (this.props.model) { var className = classNames('p-menu p-component', this.props.className, { 'p-menu-overlay': this.props.popup }); var menuitems = this.renderMenu(); return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.menuRef, classNames: "p-connected-overlay", in: this.state.visible, timeout: { enter: 120, exit: 100 }, options: this.props.transitionOptions, unmountOnExit: true, onEnter: this.onEnter, onEntered: this.onEntered, onExit: this.onExit, onExited: this.onExited }, /*#__PURE__*/React.createElement("div", { ref: this.menuRef, id: this.props.id, className: className, style: this.props.style, onClick: this.onPanelClick }, /*#__PURE__*/React.createElement("ul", { className: "p-menu-list p-reset", role: "menu" }, menuitems))); } return null; } }, { key: "render", value: function render() { var element = this.renderElement(); return this.props.popup ? /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: this.props.appendTo }) : element; } }]); return Menu; }(Component); _defineProperty(Menu, "defaultProps", { id: null, model: null, popup: false, style: null, className: null, autoZIndex: true, baseZIndex: 0, appendTo: null, transitionOptions: null, onShow: null, onHide: null }); _defineProperty(Menu, "propTypes", { id: PropTypes.string, model: PropTypes.array, popup: PropTypes.bool, style: PropTypes.object, className: PropTypes.string, autoZIndex: PropTypes.bool, baseZIndex: PropTypes.number, appendTo: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), transitionOptions: PropTypes.object, onShow: PropTypes.func, onHide: PropTypes.func }); export { Menu };
ajax/libs/material-ui/4.9.2/es/LinearProgress/LinearProgress.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import capitalize from '../utils/capitalize'; import withStyles from '../styles/withStyles'; import { darken, lighten } from '../styles/colorManipulator'; import useTheme from '../styles/useTheme'; const TRANSITION_DURATION = 4; // seconds export const styles = theme => { const getColor = color => theme.palette.type === 'light' ? lighten(color, 0.62) : darken(color, 0.5); const backgroundPrimary = getColor(theme.palette.primary.main); const backgroundSecondary = getColor(theme.palette.secondary.main); return { /* Styles applied to the root element. */ root: { position: 'relative', overflow: 'hidden', height: 4 }, /* Styles applied to the root and bar2 element if `color="primary"`; bar2 if `variant="buffer"`. */ colorPrimary: { backgroundColor: backgroundPrimary }, /* Styles applied to the root and bar2 elements if `color="secondary"`; bar2 if `variant="buffer"`. */ colorSecondary: { backgroundColor: backgroundSecondary }, /* Styles applied to the root element if `variant="determinate"`. */ determinate: {}, /* Styles applied to the root element if `variant="indeterminate"`. */ indeterminate: {}, /* Styles applied to the root element if `variant="buffer"`. */ buffer: { backgroundColor: 'transparent' }, /* Styles applied to the root element if `variant="query"`. */ query: { transform: 'rotate(180deg)' }, /* Styles applied to the additional bar element if `variant="buffer"`. */ dashed: { position: 'absolute', marginTop: 0, height: '100%', width: '100%', animation: '$buffer 3s infinite linear' }, /* Styles applied to the additional bar element if `variant="buffer"` and `color="primary"`. */ dashedColorPrimary: { backgroundImage: `radial-gradient(${backgroundPrimary} 0%, ${backgroundPrimary} 16%, transparent 42%)`, backgroundSize: '10px 10px', backgroundPosition: '0px -23px' }, /* Styles applied to the additional bar element if `variant="buffer"` and `color="secondary"`. */ dashedColorSecondary: { backgroundImage: `radial-gradient(${backgroundSecondary} 0%, ${backgroundSecondary} 16%, transparent 42%)`, backgroundSize: '10px 10px', backgroundPosition: '0px -23px' }, /* Styles applied to the layered bar1 and bar2 elements. */ bar: { width: '100%', position: 'absolute', left: 0, bottom: 0, top: 0, transition: 'transform 0.2s linear', transformOrigin: 'left' }, /* Styles applied to the bar elements if `color="primary"`; bar2 if `variant` not "buffer". */ barColorPrimary: { backgroundColor: theme.palette.primary.main }, /* Styles applied to the bar elements if `color="secondary"`; bar2 if `variant` not "buffer". */ barColorSecondary: { backgroundColor: theme.palette.secondary.main }, /* Styles applied to the bar1 element if `variant="indeterminate or query"`. */ bar1Indeterminate: { width: 'auto', animation: '$indeterminate1 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite' }, /* Styles applied to the bar1 element if `variant="determinate"`. */ bar1Determinate: { transition: `transform .${TRANSITION_DURATION}s linear` }, /* Styles applied to the bar1 element if `variant="buffer"`. */ bar1Buffer: { zIndex: 1, transition: `transform .${TRANSITION_DURATION}s linear` }, /* Styles applied to the bar2 element if `variant="indeterminate or query"`. */ bar2Indeterminate: { width: 'auto', animation: '$indeterminate2 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite' }, /* Styles applied to the bar2 element if `variant="buffer"`. */ bar2Buffer: { transition: `transform .${TRANSITION_DURATION}s linear` }, // Legends: // || represents the viewport // - represents a light background // x represents a dark background '@keyframes indeterminate1': { // |-----|---x-||-----||-----| '0%': { left: '-35%', right: '100%' }, // |-----|-----||-----||xxxx-| '60%': { left: '100%', right: '-90%' }, '100%': { left: '100%', right: '-90%' } }, '@keyframes indeterminate2': { // |xxxxx|xxxxx||-----||-----| '0%': { left: '-200%', right: '100%' }, // |-----|-----||-----||-x----| '60%': { left: '107%', right: '-8%' }, '100%': { left: '107%', right: '-8%' } }, '@keyframes buffer': { '0%': { opacity: 1, backgroundPosition: '0px -23px' }, '50%': { opacity: 0, backgroundPosition: '0px -23px' }, '100%': { opacity: 1, backgroundPosition: '-200px -23px' } } }; }; /** * ## ARIA * * If the progress bar is describing the loading progress of a particular region of a page, * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy` * attribute to `true` on that region until it has finished loading. */ const LinearProgress = React.forwardRef(function LinearProgress(props, ref) { const { classes, className, color = 'primary', value, valueBuffer, variant = 'indeterminate' } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "color", "value", "valueBuffer", "variant"]); const theme = useTheme(); const rootProps = {}; const inlineStyles = { bar1: {}, bar2: {} }; if (variant === 'determinate' || variant === 'buffer') { if (value !== undefined) { rootProps['aria-valuenow'] = Math.round(value); let transform = value - 100; if (theme.direction === 'rtl') { transform = -transform; } inlineStyles.bar1.transform = `translateX(${transform}%)`; } else if (process.env.NODE_ENV !== 'production') { console.error('Material-UI: you need to provide a value prop ' + 'when using the determinate or buffer variant of LinearProgress .'); } } if (variant === 'buffer') { if (valueBuffer !== undefined) { let transform = (valueBuffer || 0) - 100; if (theme.direction === 'rtl') { transform = -transform; } inlineStyles.bar2.transform = `translateX(${transform}%)`; } else if (process.env.NODE_ENV !== 'production') { console.error('Material-UI: you need to provide a valueBuffer prop ' + 'when using the buffer variant of LinearProgress.'); } } return React.createElement("div", _extends({ className: clsx(classes.root, classes[`color${capitalize(color)}`], className, { determinate: classes.determinate, indeterminate: classes.indeterminate, buffer: classes.buffer, query: classes.query }[variant]), role: "progressbar" }, rootProps, { ref: ref }, other), variant === 'buffer' ? React.createElement("div", { className: clsx(classes.dashed, classes[`dashedColor${capitalize(color)}`]) }) : null, React.createElement("div", { className: clsx(classes.bar, classes[`barColor${capitalize(color)}`], (variant === 'indeterminate' || variant === 'query') && classes.bar1Indeterminate, { determinate: classes.bar1Determinate, buffer: classes.bar1Buffer }[variant]), style: inlineStyles.bar1 }), variant === 'determinate' ? null : React.createElement("div", { className: clsx(classes.bar, (variant === 'indeterminate' || variant === 'query') && classes.bar2Indeterminate, variant === 'buffer' ? [classes[`color${capitalize(color)}`], classes.bar2Buffer] : classes[`barColor${capitalize(color)}`]), style: inlineStyles.bar2 })); }); process.env.NODE_ENV !== "production" ? LinearProgress.propTypes = { /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['primary', 'secondary']), /** * The value of the progress indicator for the determinate and buffer variants. * Value between 0 and 100. */ value: PropTypes.number, /** * The value for the buffer variant. * Value between 0 and 100. */ valueBuffer: PropTypes.number, /** * The variant to use. * Use indeterminate or query when there is no progress value. */ variant: PropTypes.oneOf(['determinate', 'indeterminate', 'buffer', 'query']) } : void 0; export default withStyles(styles, { name: 'MuiLinearProgress' })(LinearProgress);
ajax/libs/react-native-web/0.11.7/vendor/react-native/FlatList/index.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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; } /** * Copyright (c) 2015-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. * * * @format */ import UnimplementedView from '../../../modules/UnimplementedView'; import React from 'react'; import View from '../../../exports/View'; import VirtualizedList from '../VirtualizedList'; import invariant from 'fbjs/lib/invariant'; var defaultProps = _objectSpread({}, VirtualizedList.defaultProps, { numColumns: 1 }); /** * A performant interface for rendering simple, flat lists, supporting the most handy features: * * - Fully cross-platform. * - Optional horizontal mode. * - Configurable viewability callbacks. * - Header support. * - Footer support. * - Separator support. * - Pull to Refresh. * - Scroll loading. * - ScrollToIndex support. * * If you need section support, use [`<SectionList>`](docs/sectionlist.html). * * Minimal Example: * * <FlatList * data={[{key: 'a'}, {key: 'b'}]} * renderItem={({item}) => <Text>{item.key}</Text>} * /> * * More complex, multi-select example demonstrating `PureComponent` usage for perf optimization and avoiding bugs. * * - By binding the `onPressItem` handler, the props will remain `===` and `PureComponent` will * prevent wasteful re-renders unless the actual `id`, `selected`, or `title` props change, even * if the components rendered in `MyListItem` did not have such optimizations. * - By passing `extraData={this.state}` to `FlatList` we make sure `FlatList` itself will re-render * when the `state.selected` changes. Without setting this prop, `FlatList` would not know it * needs to re-render any items because it is also a `PureComponent` and the prop comparison will * not show any changes. * - `keyExtractor` tells the list to use the `id`s for the react keys instead of the default `key` property. * * * class MyListItem extends React.PureComponent { * _onPress = () => { * this.props.onPressItem(this.props.id); * }; * * render() { * const textColor = this.props.selected ? "red" : "black"; * return ( * <TouchableOpacity onPress={this._onPress}> * <View> * <Text style={{ color: textColor }}> * {this.props.title} * </Text> * </View> * </TouchableOpacity> * ); * } * } * * class MultiSelectList extends React.PureComponent { * state = {selected: (new Map(): Map<string, boolean>)}; * * _keyExtractor = (item, index) => item.id; * * _onPressItem = (id: string) => { * // updater functions are preferred for transactional updates * this.setState((state) => { * // copy the map rather than modifying state. * const selected = new Map(state.selected); * selected.set(id, !selected.get(id)); // toggle * return {selected}; * }); * }; * * _renderItem = ({item}) => ( * <MyListItem * id={item.id} * onPressItem={this._onPressItem} * selected={!!this.state.selected.get(item.id)} * title={item.title} * /> * ); * * render() { * return ( * <FlatList * data={this.props.data} * extraData={this.state} * keyExtractor={this._keyExtractor} * renderItem={this._renderItem} * /> * ); * } * } * * This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist.html), * and thus inherits its props (as well as those of `ScrollView`) that aren't explicitly listed * here, along with the following caveats: * * - Internal state is not preserved when content scrolls out of the render window. Make sure all * your data is captured in the item data or external stores like Flux, Redux, or Relay. * - This is a `PureComponent` which means that it will not re-render if `props` remain shallow- * equal. Make sure that everything your `renderItem` function depends on is passed as a prop * (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on * changes. This includes the `data` prop and parent component state. * - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously * offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see * blank content. This is a tradeoff that can be adjusted to suit the needs of each application, * and we are working on improving it behind the scenes. * - By default, the list looks for a `key` prop on each item and uses that for the React key. * Alternatively, you can provide a custom `keyExtractor` prop. * * Also inherits [ScrollView Props](docs/scrollview.html#props), unless it is nested in another FlatList of same orientation. */ var FlatList = /*#__PURE__*/ function (_React$PureComponent) { _inheritsLoose(FlatList, _React$PureComponent); var _proto = FlatList.prototype; /** * Scrolls to the end of the content. May be janky without `getItemLayout` prop. */ _proto.scrollToEnd = function scrollToEnd(params) { if (this._listRef) { this._listRef.scrollToEnd(params); } } /** * Scrolls to the item at the specified index such that it is positioned in the viewable area * such that `viewPosition` 0 places it at the top, 1 at the bottom, and 0.5 centered in the * middle. `viewOffset` is a fixed number of pixels to offset the final target position. * * Note: cannot scroll to locations outside the render window without specifying the * `getItemLayout` prop. */ ; _proto.scrollToIndex = function scrollToIndex(params) { if (this._listRef) { this._listRef.scrollToIndex(params); } } /** * Requires linear scan through data - use `scrollToIndex` instead if possible. * * Note: cannot scroll to locations outside the render window without specifying the * `getItemLayout` prop. */ ; _proto.scrollToItem = function scrollToItem(params) { if (this._listRef) { this._listRef.scrollToItem(params); } } /** * Scroll to a specific content pixel offset in the list. * * Check out [scrollToOffset](docs/virtualizedlist.html#scrolltooffset) of VirtualizedList */ ; _proto.scrollToOffset = function scrollToOffset(params) { if (this._listRef) { this._listRef.scrollToOffset(params); } } /** * Tells the list an interaction has occurred, which should trigger viewability calculations, e.g. * if `waitForInteractions` is true and the user has not scrolled. This is typically called by * taps on items or by navigation actions. */ ; _proto.recordInteraction = function recordInteraction() { if (this._listRef) { this._listRef.recordInteraction(); } } /** * Displays the scroll indicators momentarily. * * @platform ios */ ; _proto.flashScrollIndicators = function flashScrollIndicators() { if (this._listRef) { this._listRef.flashScrollIndicators(); } } /** * Provides a handle to the underlying scroll responder. */ ; _proto.getScrollResponder = function getScrollResponder() { if (this._listRef) { return this._listRef.getScrollResponder(); } }; _proto.getScrollableNode = function getScrollableNode() { if (this._listRef) { return this._listRef.getScrollableNode(); } }; _proto.setNativeProps = function setNativeProps(props) { if (this._listRef) { this._listRef.setNativeProps(props); } }; _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() { this._checkProps(this.props); }; _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) { invariant(nextProps.numColumns === this.props.numColumns, 'Changing numColumns on the fly is not supported. Change the key prop on FlatList when ' + 'changing the number of columns to force a fresh render of the component.'); invariant(nextProps.onViewableItemsChanged === this.props.onViewableItemsChanged, 'Changing onViewableItemsChanged on the fly is not supported'); invariant(nextProps.viewabilityConfig === this.props.viewabilityConfig, 'Changing viewabilityConfig on the fly is not supported'); invariant(nextProps.viewabilityConfigCallbackPairs === this.props.viewabilityConfigCallbackPairs, 'Changing viewabilityConfigCallbackPairs on the fly is not supported'); this._checkProps(nextProps); }; function FlatList(props) { var _this; _this = _React$PureComponent.call(this, props) || this; _this._hasWarnedLegacy = false; _this._virtualizedListPairs = []; _this._captureRef = function (ref) { _this._listRef = ref; }; _this._getItem = function (data, index) { var numColumns = _this.props.numColumns; if (numColumns > 1) { var ret = []; for (var kk = 0; kk < numColumns; kk++) { var _item = data[index * numColumns + kk]; _item && ret.push(_item); } return ret; } else { return data[index]; } }; _this._getItemCount = function (data) { return data ? Math.ceil(data.length / _this.props.numColumns) : 0; }; _this._keyExtractor = function (items, index) { var _this$props = _this.props, keyExtractor = _this$props.keyExtractor, numColumns = _this$props.numColumns; if (numColumns > 1) { invariant(Array.isArray(items), 'FlatList: Encountered internal consistency error, expected each item to consist of an ' + 'array with 1-%s columns; instead, received a single item.', numColumns); return items.map(function (it, kk) { return keyExtractor(it, index * numColumns + kk); }).join(':'); } else { /* $FlowFixMe(>=0.63.0 site=react_native_fb) This comment suppresses an * error found when Flow v0.63 was deployed. To see the error delete this * comment and run Flow. */ return keyExtractor(items, index); } }; _this._renderItem = function (info) { var _this$props2 = _this.props, renderItem = _this$props2.renderItem, numColumns = _this$props2.numColumns, columnWrapperStyle = _this$props2.columnWrapperStyle; if (numColumns > 1) { var _item2 = info.item, _index = info.index; invariant(Array.isArray(_item2), 'Expected array of items with numColumns > 1'); return React.createElement(View, { style: [{ flexDirection: 'row' }, columnWrapperStyle] }, _item2.map(function (it, kk) { var element = renderItem({ item: it, index: _index * numColumns + kk, separators: info.separators }); return element && React.cloneElement(element, { key: kk }); })); } else { return renderItem(info); } }; if (_this.props.viewabilityConfigCallbackPairs) { _this._virtualizedListPairs = _this.props.viewabilityConfigCallbackPairs.map(function (pair) { return { viewabilityConfig: pair.viewabilityConfig, onViewableItemsChanged: _this._createOnViewableItemsChanged(pair.onViewableItemsChanged) }; }); } else if (_this.props.onViewableItemsChanged) { /* $FlowFixMe(>=0.63.0 site=react_native_fb) This comment suppresses an * error found when Flow v0.63 was deployed. To see the error delete this * comment and run Flow. */ _this._virtualizedListPairs.push({ viewabilityConfig: _this.props.viewabilityConfig, onViewableItemsChanged: _this._createOnViewableItemsChanged(_this.props.onViewableItemsChanged) }); } return _this; } _proto._checkProps = function _checkProps(props) { var getItem = props.getItem, getItemCount = props.getItemCount, horizontal = props.horizontal, legacyImplementation = props.legacyImplementation, numColumns = props.numColumns, columnWrapperStyle = props.columnWrapperStyle, onViewableItemsChanged = props.onViewableItemsChanged, viewabilityConfigCallbackPairs = props.viewabilityConfigCallbackPairs; invariant(!getItem && !getItemCount, 'FlatList does not support custom data formats.'); if (numColumns > 1) { invariant(!horizontal, 'numColumns does not support horizontal.'); } else { invariant(!columnWrapperStyle, 'columnWrapperStyle not supported for single column lists'); } if (legacyImplementation) { invariant(numColumns === 1, 'Legacy list does not support multiple columns.'); // Warning: may not have full feature parity and is meant more for debugging and performance // comparison. if (!this._hasWarnedLegacy) { console.warn('FlatList: Using legacyImplementation - some features not supported and performance ' + 'may suffer'); this._hasWarnedLegacy = true; } } invariant(!(onViewableItemsChanged && viewabilityConfigCallbackPairs), 'FlatList does not support setting both onViewableItemsChanged and ' + 'viewabilityConfigCallbackPairs.'); }; _proto._pushMultiColumnViewable = function _pushMultiColumnViewable(arr, v) { var _this$props3 = this.props, numColumns = _this$props3.numColumns, keyExtractor = _this$props3.keyExtractor; v.item.forEach(function (item, ii) { invariant(v.index != null, 'Missing index!'); var index = v.index * numColumns + ii; arr.push(_objectSpread({}, v, { item: item, key: keyExtractor(item, index), index: index })); }); }; _proto._createOnViewableItemsChanged = function _createOnViewableItemsChanged(onViewableItemsChanged) { var _this2 = this; return function (info) { var numColumns = _this2.props.numColumns; if (onViewableItemsChanged) { if (numColumns > 1) { var changed = []; var viewableItems = []; info.viewableItems.forEach(function (v) { return _this2._pushMultiColumnViewable(viewableItems, v); }); info.changed.forEach(function (v) { return _this2._pushMultiColumnViewable(changed, v); }); onViewableItemsChanged({ viewableItems: viewableItems, changed: changed }); } else { onViewableItemsChanged(info); } } }; }; _proto.render = function render() { if (this.props.legacyImplementation) { return ( /* $FlowFixMe(>=0.66.0 site=react_native_fb) This comment suppresses an * error found when Flow v0.66 was deployed. To see the error delete * this comment and run Flow. */ React.createElement(UnimplementedView, _extends({}, this.props, { /* $FlowFixMe(>=0.66.0 site=react_native_fb) This comment suppresses * an error found when Flow v0.66 was deployed. To see the error * delete this comment and run Flow. */ items: this.props.data, ref: this._captureRef })) ); } else { return React.createElement(VirtualizedList, _extends({}, this.props, { renderItem: this._renderItem, getItem: this._getItem, getItemCount: this._getItemCount, keyExtractor: this._keyExtractor, ref: this._captureRef, viewabilityConfigCallbackPairs: this._virtualizedListPairs })); } }; return FlatList; }(React.PureComponent); FlatList.defaultProps = defaultProps; export default FlatList;
ajax/libs/primereact/7.2.1/captcha/captcha.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Captcha = /*#__PURE__*/function (_Component) { _inherits(Captcha, _Component); var _super = _createSuper(Captcha); function Captcha() { _classCallCheck(this, Captcha); return _super.apply(this, arguments); } _createClass(Captcha, [{ key: "init", value: function init() { var _this = this; this._instance = window.grecaptcha.render(this.targetEL, { 'sitekey': this.props.siteKey, 'theme': this.props.theme, 'type': this.props.type, 'size': this.props.size, 'tabindex': this.props.tabIndex, 'hl': this.props.language, 'callback': function callback(response) { _this.recaptchaCallback(response); }, 'expired-callback': function expiredCallback() { _this.recaptchaExpiredCallback(); } }); } }, { key: "reset", value: function reset() { if (this._instance === null) return; window.grecaptcha.reset(this._instance); } }, { key: "getResponse", value: function getResponse() { if (this._instance === null) return null; return window.grecaptcha.getResponse(this._instance); } }, { key: "recaptchaCallback", value: function recaptchaCallback(response) { if (this.props.onResponse) { this.props.onResponse({ response: response }); } } }, { key: "recaptchaExpiredCallback", value: function recaptchaExpiredCallback() { if (this.props.onExpire) { this.props.onExpire(); } } }, { key: "addRecaptchaScript", value: function addRecaptchaScript() { var _this2 = this; this.recaptchaScript = null; if (!window.grecaptcha) { var head = document.head || document.getElementsByTagName('head')[0]; this.recaptchaScript = document.createElement('script'); this.recaptchaScript.src = "https://www.google.com/recaptcha/api.js?render=explicit"; this.recaptchaScript.async = true; this.recaptchaScript.defer = true; this.recaptchaScript.onload = function () { if (!window.grecaptcha) { console.warn("Recaptcha is not loaded"); return; } window.grecaptcha.ready(function () { _this2.init(); }); }; head.appendChild(this.recaptchaScript); } } }, { key: "componentDidMount", value: function componentDidMount() { this.addRecaptchaScript(); if (window.grecaptcha) { this.init(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.recaptchaScript) { this.recaptchaScript.parentNode.removeChild(this.recaptchaScript); } } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/React.createElement("div", { id: this.props.id, ref: function ref(el) { return _this3.targetEL = el; } }); } }]); return Captcha; }(Component); _defineProperty(Captcha, "defaultProps", { id: null, siteKey: null, theme: "light", type: "image", size: "normal", tabIndex: 0, language: "en", onResponse: null, onExpire: null }); export { Captcha };
ajax/libs/react-native-web/0.13.4/exports/Touchable/index.js
cdnjs/cdnjs
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ 'use strict'; function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 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; } import AccessibilityUtil from '../../modules/AccessibilityUtil'; import BoundingDimensions from './BoundingDimensions'; import findNodeHandle from '../findNodeHandle'; import normalizeColor from 'normalize-css-color'; import Position from './Position'; import React from 'react'; import UIManager from '../UIManager'; import View from '../View'; var extractSingleTouch = function extractSingleTouch(nativeEvent) { var touches = nativeEvent.touches; var changedTouches = nativeEvent.changedTouches; var hasTouches = touches && touches.length > 0; var hasChangedTouches = changedTouches && changedTouches.length > 0; return !hasTouches && hasChangedTouches ? changedTouches[0] : hasTouches ? touches[0] : nativeEvent; }; /** * `Touchable`: Taps done right. * * You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable` * will measure time/geometry and tells you when to give feedback to the user. * * ====================== Touchable Tutorial =============================== * The `Touchable` mixin helps you handle the "press" interaction. It analyzes * the geometry of elements, and observes when another responder (scroll view * etc) has stolen the touch lock. It notifies your component when it should * give feedback to the user. (bouncing/highlighting/unhighlighting). * * - When a touch was activated (typically you highlight) * - When a touch was deactivated (typically you unhighlight) * - When a touch was "pressed" - a touch ended while still within the geometry * of the element, and no other element (like scroller) has "stolen" touch * lock ("responder") (Typically you bounce the element). * * A good tap interaction isn't as simple as you might think. There should be a * slight delay before showing a highlight when starting a touch. If a * subsequent touch move exceeds the boundary of the element, it should * unhighlight, but if that same touch is brought back within the boundary, it * should rehighlight again. A touch can move in and out of that boundary * several times, each time toggling highlighting, but a "press" is only * triggered if that touch ends while within the element's boundary and no * scroller (or anything else) has stolen the lock on touches. * * To create a new type of component that handles interaction using the * `Touchable` mixin, do the following: * * - Initialize the `Touchable` state. * * getInitialState: function() { * return merge(this.touchableGetInitialState(), yourComponentState); * } * * - Choose the rendered component who's touches should start the interactive * sequence. On that rendered node, forward all `Touchable` responder * handlers. You can choose any rendered node you like. Choose a node whose * hit target you'd like to instigate the interaction sequence: * * // In render function: * return ( * <View * onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} * onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest} * onResponderGrant={this.touchableHandleResponderGrant} * onResponderMove={this.touchableHandleResponderMove} * onResponderRelease={this.touchableHandleResponderRelease} * onResponderTerminate={this.touchableHandleResponderTerminate}> * <View> * Even though the hit detection/interactions are triggered by the * wrapping (typically larger) node, we usually end up implementing * custom logic that highlights this inner one. * </View> * </View> * ); * * - You may set up your own handlers for each of these events, so long as you * also invoke the `touchable*` handlers inside of your custom handler. * * - Implement the handlers on your component class in order to provide * feedback to the user. See documentation for each of these class methods * that you should implement. * * touchableHandlePress: function() { * this.performBounceAnimation(); // or whatever you want to do. * }, * touchableHandleActivePressIn: function() { * this.beginHighlighting(...); // Whatever you like to convey activation * }, * touchableHandleActivePressOut: function() { * this.endHighlighting(...); // Whatever you like to convey deactivation * }, * * - There are more advanced methods you can implement (see documentation below): * touchableGetHighlightDelayMS: function() { * return 20; * } * // In practice, *always* use a predeclared constant (conserve memory). * touchableGetPressRectOffset: function() { * return {top: 20, left: 20, right: 20, bottom: 100}; * } */ /** * Touchable states. */ var States = { NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect` RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect` RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect` RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect` RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT', // Responder, active, out of `PressRect`, after long press threshold ERROR: 'ERROR' }; /* * Quick lookup map for states that are considered to be "active" */ var baseStatesConditions = { NOT_RESPONDER: false, RESPONDER_INACTIVE_PRESS_IN: false, RESPONDER_INACTIVE_PRESS_OUT: false, RESPONDER_ACTIVE_PRESS_IN: false, RESPONDER_ACTIVE_PRESS_OUT: false, RESPONDER_ACTIVE_LONG_PRESS_IN: false, RESPONDER_ACTIVE_LONG_PRESS_OUT: false, ERROR: false }; var IsActive = _objectSpread({}, baseStatesConditions, { RESPONDER_ACTIVE_PRESS_OUT: true, RESPONDER_ACTIVE_PRESS_IN: true }); /** * Quick lookup for states that are considered to be "pressing" and are * therefore eligible to result in a "selection" if the press stops. */ var IsPressingIn = _objectSpread({}, baseStatesConditions, { RESPONDER_INACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_LONG_PRESS_IN: true }); var IsLongPressingIn = _objectSpread({}, baseStatesConditions, { RESPONDER_ACTIVE_LONG_PRESS_IN: true }); /** * Inputs to the state machine. */ var Signals = { DELAY: 'DELAY', RESPONDER_GRANT: 'RESPONDER_GRANT', RESPONDER_RELEASE: 'RESPONDER_RELEASE', RESPONDER_TERMINATED: 'RESPONDER_TERMINATED', ENTER_PRESS_RECT: 'ENTER_PRESS_RECT', LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT', LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED' }; /** * Mapping from States x Signals => States */ var Transitions = { NOT_RESPONDER: { DELAY: States.ERROR, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.ERROR, RESPONDER_TERMINATED: States.ERROR, ENTER_PRESS_RECT: States.ERROR, LEAVE_PRESS_RECT: States.ERROR, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_IN: { DELAY: States.RESPONDER_ACTIVE_PRESS_IN, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_OUT: { DELAY: States.RESPONDER_ACTIVE_PRESS_OUT, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_LONG_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_LONG_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, error: { DELAY: States.NOT_RESPONDER, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.NOT_RESPONDER, LEAVE_PRESS_RECT: States.NOT_RESPONDER, LONG_PRESS_DETECTED: States.NOT_RESPONDER } }; // ==== Typical Constants for integrating into UI components ==== // var HIT_EXPAND_PX = 20; // var HIT_VERT_OFFSET_PX = 10; var HIGHLIGHT_DELAY_MS = 130; var PRESS_EXPAND_PX = 20; var LONG_PRESS_THRESHOLD = 500; var LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS; var LONG_PRESS_ALLOWED_MOVEMENT = 10; // Default amount "active" region protrudes beyond box /** * By convention, methods prefixed with underscores are meant to be @private, * and not @protected. Mixers shouldn't access them - not even to provide them * as callback handlers. * * * ========== Geometry ========= * `Touchable` only assumes that there exists a `HitRect` node. The `PressRect` * is an abstract box that is extended beyond the `HitRect`. * * +--------------------------+ * | | - "Start" events in `HitRect` cause `HitRect` * | +--------------------+ | to become the responder. * | | +--------------+ | | - `HitRect` is typically expanded around * | | | | | | the `VisualRect`, but shifted downward. * | | | VisualRect | | | - After pressing down, after some delay, * | | | | | | and before letting up, the Visual React * | | +--------------+ | | will become "active". This makes it eligible * | | HitRect | | for being highlighted (so long as the * | +--------------------+ | press remains in the `PressRect`). * | PressRect o | * +----------------------|---+ * Out Region | * +-----+ This gap between the `HitRect` and * `PressRect` allows a touch to move far away * from the original hit rect, and remain * highlighted, and eligible for a "Press". * Customize this via * `touchableGetPressRectOffset()`. * * * * ======= State Machine ======= * * +-------------+ <---+ RESPONDER_RELEASE * |NOT_RESPONDER| * +-------------+ <---+ RESPONDER_TERMINATED * + * | RESPONDER_GRANT (HitRect) * v * +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+ * |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN| * +---------------------------+ +-------------------------+ +------------------------------+ * + ^ + ^ + ^ * |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ * |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT * | | | | | | * v + v + v + * +----------------------------+ DELAY +--------------------------+ +-------------------------------+ * |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT| * +----------------------------+ +--------------------------+ +-------------------------------+ * * T + DELAY => LONG_PRESS_DELAY_MS + DELAY * * Not drawn are the side effects of each transition. The most important side * effect is the `touchableHandlePress` abstract method invocation that occurs * when a responder is released while in either of the "Press" states. * * The other important side effects are the highlight abstract method * invocations (internal callbacks) to be implemented by the mixer. * * * @lends Touchable.prototype */ var TouchableMixin = { // HACK (part 1): basic support for touchable interactions using a keyboard componentDidMount: function componentDidMount() { var _this = this; this._touchableNode = findNodeHandle(this); if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableBlurListener = function (e) { if (_this._isTouchableKeyboardActive) { if (_this.state.touchable.touchState && _this.state.touchable.touchState !== States.NOT_RESPONDER) { _this.touchableHandleResponderTerminate({ nativeEvent: e }); } _this._isTouchableKeyboardActive = false; } }; this._touchableNode.addEventListener('blur', this._touchableBlurListener); } }, /** * Clear all timeouts on unmount */ componentWillUnmount: function componentWillUnmount() { if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableNode.removeEventListener('blur', this._touchableBlurListener); } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); }, /** * It's prefer that mixins determine state in this way, having the class * explicitly mix the state in the one and only `getInitialState` method. * * @return {object} State object to be placed inside of * `this.state.touchable`. */ touchableGetInitialState: function touchableGetInitialState() { return { touchable: { touchState: undefined, responderID: null } }; }, // ==== Hooks to Gesture Responder system ==== /** * Must return true if embedded in a native platform scroll view. */ touchableHandleResponderTerminationRequest: function touchableHandleResponderTerminationRequest() { return !this.props.rejectResponderTermination; }, /** * Must return true to start the process of `Touchable`. */ touchableHandleStartShouldSetResponder: function touchableHandleStartShouldSetResponder() { return !this.props.disabled; }, /** * Return true to cancel press on long press. */ touchableLongPressCancelsPress: function touchableLongPressCancelsPress() { return true; }, /** * Place as callback for a DOM element's `onResponderGrant` event. * @param {SyntheticEvent} e Synthetic event from event system. * */ touchableHandleResponderGrant: function touchableHandleResponderGrant(e) { var dispatchID = e.currentTarget; // Since e is used in a callback invoked on another event loop // (as in setTimeout etc), we need to call e.persist() on the // event to make sure it doesn't get reused in the event object pool. e.persist(); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); this.pressOutDelayTimeout = null; this.state.touchable.touchState = States.NOT_RESPONDER; this.state.touchable.responderID = dispatchID; this._receiveSignal(Signals.RESPONDER_GRANT, e); var delayMS = this.touchableGetHighlightDelayMS !== undefined ? Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS; delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS; if (delayMS !== 0) { this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS); } else { this._handleDelay(e); } var longDelayMS = this.touchableGetLongPressDelayMS !== undefined ? Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS; longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS; this.longPressDelayTimeout = setTimeout(this._handleLongDelay.bind(this, e), longDelayMS + delayMS); }, /** * Place as callback for a DOM element's `onResponderRelease` event. */ touchableHandleResponderRelease: function touchableHandleResponderRelease(e) { this.pressInLocation = null; this._receiveSignal(Signals.RESPONDER_RELEASE, e); }, /** * Place as callback for a DOM element's `onResponderTerminate` event. */ touchableHandleResponderTerminate: function touchableHandleResponderTerminate(e) { this.pressInLocation = null; this._receiveSignal(Signals.RESPONDER_TERMINATED, e); }, /** * Place as callback for a DOM element's `onResponderMove` event. */ touchableHandleResponderMove: function touchableHandleResponderMove(e) { // Measurement may not have returned yet. if (!this.state.touchable.positionOnActivate) { return; } var positionOnActivate = this.state.touchable.positionOnActivate; var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate; var pressRectOffset = this.touchableGetPressRectOffset ? this.touchableGetPressRectOffset() : { left: PRESS_EXPAND_PX, right: PRESS_EXPAND_PX, top: PRESS_EXPAND_PX, bottom: PRESS_EXPAND_PX }; var pressExpandLeft = pressRectOffset.left; var pressExpandTop = pressRectOffset.top; var pressExpandRight = pressRectOffset.right; var pressExpandBottom = pressRectOffset.bottom; var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null; if (hitSlop) { pressExpandLeft += hitSlop.left || 0; pressExpandTop += hitSlop.top || 0; pressExpandRight += hitSlop.right || 0; pressExpandBottom += hitSlop.bottom || 0; } var touch = extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; if (this.pressInLocation) { var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY); if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) { this._cancelLongPressDelayTimeout(); } } var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && pageY > positionOnActivate.top - pressExpandTop && pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom; if (isTouchWithinActive) { var prevState = this.state.touchable.touchState; this._receiveSignal(Signals.ENTER_PRESS_RECT, e); var curState = this.state.touchable.touchState; if (curState === States.RESPONDER_INACTIVE_PRESS_IN && prevState !== States.RESPONDER_INACTIVE_PRESS_IN) { // fix for t7967420 this._cancelLongPressDelayTimeout(); } } else { this._cancelLongPressDelayTimeout(); this._receiveSignal(Signals.LEAVE_PRESS_RECT, e); } }, /** * Invoked when the item receives focus. Mixers might override this to * visually distinguish the `VisualRect` so that the user knows that it * currently has the focus. Most platforms only support a single element being * focused at a time, in which case there may have been a previously focused * element that was blurred just prior to this. This can be overridden when * using `Touchable.Mixin.withoutDefaultFocusAndBlur`. */ touchableHandleFocus: function touchableHandleFocus(e) { this.props.onFocus && this.props.onFocus(e); }, /** * Invoked when the item loses focus. Mixers might override this to * visually distinguish the `VisualRect` so that the user knows that it * no longer has focus. Most platforms only support a single element being * focused at a time, in which case the focus may have moved to another. * This can be overridden when using * `Touchable.Mixin.withoutDefaultFocusAndBlur`. */ touchableHandleBlur: function touchableHandleBlur(e) { this.props.onBlur && this.props.onBlur(e); }, // ==== Abstract Application Callbacks ==== /** * Invoked when the item should be highlighted. Mixers should implement this * to visually distinguish the `VisualRect` so that the user knows that * releasing a touch will result in a "selection" (analog to click). * * @abstract * touchableHandleActivePressIn: function, */ /** * Invoked when the item is "active" (in that it is still eligible to become * a "select") but the touch has left the `PressRect`. Usually the mixer will * want to unhighlight the `VisualRect`. If the user (while pressing) moves * back into the `PressRect` `touchableHandleActivePressIn` will be invoked * again and the mixer should probably highlight the `VisualRect` again. This * event will not fire on an `touchEnd/mouseUp` event, only move events while * the user is depressing the mouse/touch. * * @abstract * touchableHandleActivePressOut: function */ /** * Invoked when the item is "selected" - meaning the interaction ended by * letting up while the item was either in the state * `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`. * * @abstract * touchableHandlePress: function */ /** * Invoked when the item is long pressed - meaning the interaction ended by * letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If * `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will * be called as it normally is. If `touchableHandleLongPress` is provided, by * default any `touchableHandlePress` callback will not be invoked. To * override this default behavior, override `touchableLongPressCancelsPress` * to return false. As a result, `touchableHandlePress` will be called when * lifting up, even if `touchableHandleLongPress` has also been called. * * @abstract * touchableHandleLongPress: function */ /** * Returns the number of millis to wait before triggering a highlight. * * @abstract * touchableGetHighlightDelayMS: function */ /** * Returns the amount to extend the `HitRect` into the `PressRect`. Positive * numbers mean the size expands outwards. * * @abstract * touchableGetPressRectOffset: function */ // ==== Internal Logic ==== /** * Measures the `HitRect` node on activation. The Bounding rectangle is with * respect to viewport - not page, so adding the `pageXOffset/pageYOffset` * should result in points that are in the same coordinate system as an * event's `globalX/globalY` data values. * * - Consider caching this for the lifetime of the component, or possibly * being able to share this cache between any `ScrollMap` view. * * @sideeffects * @private */ _remeasureMetricsOnActivation: function _remeasureMetricsOnActivation() { var tag = this.state.touchable.responderID; if (tag == null) { return; } UIManager.measure(tag, this._handleQueryLayout); }, _handleQueryLayout: function _handleQueryLayout(l, t, w, h, globalX, globalY) { //don't do anything UIManager failed to measure node if (!l && !t && !w && !h && !globalX && !globalY) { return; } this.state.touchable.positionOnActivate && Position.release(this.state.touchable.positionOnActivate); this.state.touchable.dimensionsOnActivate && // $FlowFixMe BoundingDimensions.release(this.state.touchable.dimensionsOnActivate); this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY); // $FlowFixMe this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(w, h); }, _handleDelay: function _handleDelay(e) { this.touchableDelayTimeout = null; this._receiveSignal(Signals.DELAY, e); }, _handleLongDelay: function _handleLongDelay(e) { this.longPressDelayTimeout = null; var curState = this.state.touchable.touchState; if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) { console.error('Attempted to transition from state `' + curState + '` to `' + States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.'); } else { this._receiveSignal(Signals.LONG_PRESS_DETECTED, e); } }, /** * Receives a state machine signal, performs side effects of the transition * and stores the new state. Validates the transition as well. * * @param {Signals} signal State machine signal. * @throws Error if invalid state transition or unrecognized signal. * @sideeffects */ _receiveSignal: function _receiveSignal(signal, e) { var responderID = this.state.touchable.responderID; var curState = this.state.touchable.touchState; var nextState = Transitions[curState] && Transitions[curState][signal]; if (!responderID && signal === Signals.RESPONDER_RELEASE) { return; } if (!nextState) { throw new Error('Unrecognized signal `' + signal + '` or state `' + curState + '` for Touchable responder `' + responderID + '`'); } if (nextState === States.ERROR) { throw new Error('Touchable cannot transition from `' + curState + '` to `' + signal + '` for responder `' + responderID + '`'); } if (curState !== nextState) { this._performSideEffectsForTransition(curState, nextState, signal, e); this.state.touchable.touchState = nextState; } }, _cancelLongPressDelayTimeout: function _cancelLongPressDelayTimeout() { this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.longPressDelayTimeout = null; }, _isHighlight: function _isHighlight(state) { return state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN; }, _savePressInLocation: function _savePressInLocation(e) { var touch = extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; var locationX = touch && touch.locationX; var locationY = touch && touch.locationY; this.pressInLocation = { pageX: pageX, pageY: pageY, locationX: locationX, locationY: locationY }; }, _getDistanceBetweenPoints: function _getDistanceBetweenPoints(aX, aY, bX, bY) { var deltaX = aX - bX; var deltaY = aY - bY; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); }, /** * Will perform a transition between touchable states, and identify any * highlighting or unhighlighting that must be performed for this particular * transition. * * @param {States} curState Current Touchable state. * @param {States} nextState Next Touchable state. * @param {Signal} signal Signal that triggered the transition. * @param {Event} e Native event. * @sideeffects */ _performSideEffectsForTransition: function _performSideEffectsForTransition(curState, nextState, signal, e) { var curIsHighlight = this._isHighlight(curState); var newIsHighlight = this._isHighlight(nextState); var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE; if (isFinalSignal) { this._cancelLongPressDelayTimeout(); } var isInitialTransition = curState === States.NOT_RESPONDER && nextState === States.RESPONDER_INACTIVE_PRESS_IN; var isActiveTransition = !IsActive[curState] && IsActive[nextState]; if (isInitialTransition || isActiveTransition) { this._remeasureMetricsOnActivation(); } if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) { this.touchableHandleLongPress && this.touchableHandleLongPress(e); } if (newIsHighlight && !curIsHighlight) { this._startHighlight(e); } else if (!newIsHighlight && curIsHighlight) { this._endHighlight(e); } if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) { var hasLongPressHandler = !!this.props.onLongPress; var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && ( // We *are* long pressing.. // But either has no long handler !hasLongPressHandler || !this.touchableLongPressCancelsPress()); // or we're told to ignore it. var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress; if (shouldInvokePress && this.touchableHandlePress) { if (!newIsHighlight && !curIsHighlight) { // we never highlighted because of delay, but we should highlight now this._startHighlight(e); this._endHighlight(e); } this.touchableHandlePress(e); } } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.touchableDelayTimeout = null; }, _playTouchSound: function _playTouchSound() { UIManager.playTouchSound(); }, _startHighlight: function _startHighlight(e) { this._savePressInLocation(e); this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e); }, _endHighlight: function _endHighlight(e) { var _this2 = this; if (this.touchableHandleActivePressOut) { if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) { this.pressOutDelayTimeout = setTimeout(function () { _this2.touchableHandleActivePressOut(e); }, this.touchableGetPressOutDelayMS()); } else { this.touchableHandleActivePressOut(e); } } }, // HACK (part 2): basic support for touchable interactions using a keyboard (including // delays and longPress) touchableHandleKeyEvent: function touchableHandleKeyEvent(e) { var type = e.type, key = e.key; if (key === 'Enter' || key === ' ') { if (type === 'keydown') { if (!this._isTouchableKeyboardActive) { if (!this.state.touchable.touchState || this.state.touchable.touchState === States.NOT_RESPONDER) { this.touchableHandleResponderGrant(e); this._isTouchableKeyboardActive = true; } } } else if (type === 'keyup') { if (this._isTouchableKeyboardActive) { if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) { this.touchableHandleResponderRelease(e); this._isTouchableKeyboardActive = false; } } } e.stopPropagation(); // prevent the default behaviour unless the Touchable functions as a link // and Enter is pressed if (!(key === 'Enter' && AccessibilityUtil.propsToAriaRole(this.props) === 'link')) { e.preventDefault(); } } }, withoutDefaultFocusAndBlur: {} }; /** * Provide an optional version of the mixin where `touchableHandleFocus` and * `touchableHandleBlur` can be overridden. This allows appropriate defaults to * be set on TV platforms, without breaking existing implementations of * `Touchable`. */ var touchableHandleFocus = TouchableMixin.touchableHandleFocus, touchableHandleBlur = TouchableMixin.touchableHandleBlur, TouchableMixinWithoutDefaultFocusAndBlur = _objectWithoutPropertiesLoose(TouchableMixin, ["touchableHandleFocus", "touchableHandleBlur"]); TouchableMixin.withoutDefaultFocusAndBlur = TouchableMixinWithoutDefaultFocusAndBlur; var Touchable = { Mixin: TouchableMixin, TOUCH_TARGET_DEBUG: false, // Highlights all touchable targets. Toggle with Inspector. /** * Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android). */ renderDebugView: function renderDebugView(_ref) { var color = _ref.color, hitSlop = _ref.hitSlop; if (!Touchable.TOUCH_TARGET_DEBUG) { return null; } if (process.env.NODE_ENV !== 'production') { throw Error('Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!'); } var debugHitSlopStyle = {}; hitSlop = hitSlop || { top: 0, bottom: 0, left: 0, right: 0 }; for (var key in hitSlop) { debugHitSlopStyle[key] = -hitSlop[key]; } var normalizedColor = normalizeColor(color); if (typeof normalizedColor !== 'number') { return null; } var hexColor = '#' + ('00000000' + normalizedColor.toString(16)).substr(-8); return React.createElement(View, { pointerEvents: "none", style: _objectSpread({ position: 'absolute', borderColor: hexColor.slice(0, -2) + '55', // More opaque borderWidth: 1, borderStyle: 'dashed', backgroundColor: hexColor.slice(0, -2) + '0F' }, debugHitSlopStyle) }); } }; export default Touchable;
ajax/libs/material-ui/4.10.0/es/utils/createSvgIcon.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import SvgIcon from '../SvgIcon'; /** * Private module reserved for @material-ui/x packages. */ export default function createSvgIcon(path, displayName) { const Component = React.memo(React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({ ref: ref }, props), path))); if (process.env.NODE_ENV !== 'production') { Component.displayName = `${displayName}Icon`; } Component.muiName = SvgIcon.muiName; return Component; }
ajax/libs/material-ui/4.9.3/es/FormLabel/FormLabel.js
cdnjs/cdnjs
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import formControlState from '../FormControl/formControlState'; import useFormControl from '../FormControl/useFormControl'; import capitalize from '../utils/capitalize'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ /* Styles applied to the root element. */ root: _extends({ color: theme.palette.text.secondary }, theme.typography.body1, { lineHeight: 1, padding: 0, '&$focused': { color: theme.palette.primary.main }, '&$disabled': { color: theme.palette.text.disabled }, '&$error': { color: theme.palette.error.main } }), /* Styles applied to the root element if the color is secondary. */ colorSecondary: { '&$focused': { color: theme.palette.secondary.main } }, /* Pseudo-class applied to the root element if `focused={true}`. */ focused: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Pseudo-class applied to the root element if `error={true}`. */ error: {}, /* Pseudo-class applied to the root element if `filled={true}`. */ filled: {}, /* Pseudo-class applied to the root element if `required={true}`. */ required: {}, /* Styles applied to the asterisk element. */ asterisk: { '&$error': { color: theme.palette.error.main } } }); const FormLabel = React.forwardRef(function FormLabel(props, ref) { const { children, classes, className, component: Component = 'label' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "color", "component", "disabled", "error", "filled", "focused", "required"]); const muiFormControl = useFormControl(); const fcs = formControlState({ props, muiFormControl, states: ['color', 'required', 'focused', 'disabled', 'error', 'filled'] }); return React.createElement(Component, _extends({ className: clsx(classes.root, classes[`color${capitalize(fcs.color || 'primary')}`], className, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required), ref: ref }, other), children, fcs.required && React.createElement("span", { className: clsx(classes.asterisk, fcs.error && classes.error) }, "\u2009", '*')); }); process.env.NODE_ENV !== "production" ? FormLabel.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['primary', 'secondary']), /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, the label should be displayed in a disabled state. */ disabled: PropTypes.bool, /** * If `true`, the label should be displayed in an error state. */ error: PropTypes.bool, /** * If `true`, the label should use filled classes key. */ filled: PropTypes.bool, /** * If `true`, the input of this label is focused (used by `FormGroup` components). */ focused: PropTypes.bool, /** * If `true`, the label will indicate that the input is required. */ required: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiFormLabel' })(FormLabel);
ajax/libs/primereact/6.6.0-rc.1/avatargroup/avatargroup.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var AvatarGroup = /*#__PURE__*/function (_Component) { _inherits(AvatarGroup, _Component); var _super = _createSuper(AvatarGroup); function AvatarGroup() { _classCallCheck(this, AvatarGroup); return _super.apply(this, arguments); } _createClass(AvatarGroup, [{ key: "render", value: function render() { var containerClassName = classNames('p-avatar-group p-component', this.props.className); return /*#__PURE__*/React.createElement("div", { className: containerClassName, style: this.props.style }, this.props.children); } }]); return AvatarGroup; }(Component); _defineProperty(AvatarGroup, "defaultProps", { style: null, className: null }); export { AvatarGroup };
ajax/libs/primereact/7.2.1/skeleton/skeleton.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/utils'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Skeleton = /*#__PURE__*/function (_Component) { _inherits(Skeleton, _Component); var _super = _createSuper(Skeleton); function Skeleton() { _classCallCheck(this, Skeleton); return _super.apply(this, arguments); } _createClass(Skeleton, [{ key: "skeletonStyle", value: function skeletonStyle() { if (this.props.size) return { width: this.props.size, height: this.props.size, borderRadius: this.props.borderRadius };else return { width: this.props.width, height: this.props.height, borderRadius: this.props.borderRadius }; } }, { key: "render", value: function render() { var skeletonClassName = classNames('p-skeleton p-component', { 'p-skeleton-circle': this.props.shape === 'circle', 'p-skeleton-none': this.props.animation === 'none' }, this.props.className); var style = this.skeletonStyle(); return /*#__PURE__*/React.createElement("div", { style: style, className: skeletonClassName }); } }]); return Skeleton; }(Component); _defineProperty(Skeleton, "defaultProps", { shape: 'rectangle', size: null, width: '100%', height: '1rem', borderRadius: null, animation: 'wave', style: null, className: null }); export { Skeleton };
ajax/libs/primereact/6.5.1/tag/tag.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Tag = /*#__PURE__*/function (_Component) { _inherits(Tag, _Component); var _super = _createSuper(Tag); function Tag() { _classCallCheck(this, Tag); return _super.apply(this, arguments); } _createClass(Tag, [{ key: "render", value: function render() { var tagClassName = classNames('p-tag p-component', { 'p-tag-info': this.props.severity === 'info', 'p-tag-success': this.props.severity === 'success', 'p-tag-warning': this.props.severity === 'warning', 'p-tag-danger': this.props.severity === 'danger', 'p-tag-rounded': this.props.rounded }, this.props.className); var iconClass = classNames('p-tag-icon', this.props.icon); return /*#__PURE__*/React.createElement("span", { className: tagClassName, style: this.props.style }, this.props.icon && /*#__PURE__*/React.createElement("span", { className: iconClass }), /*#__PURE__*/React.createElement("span", { className: "p-tag-value" }, this.props.value), /*#__PURE__*/React.createElement("span", null, this.props.children)); } }]); return Tag; }(Component); _defineProperty(Tag, "defaultProps", { value: null, severity: null, rounded: false, icon: null, style: null, className: null }); export { Tag };
ajax/libs/boardgame-io/0.47.2/esm/react-native.js
cdnjs/cdnjs
import 'nanoid'; import { _ as _inherits, a as _createSuper, b as _createClass, c as _defineProperty, d as _classCallCheck, e as _objectWithoutProperties, f as _objectSpread2 } from './Debug-f230efd0.js'; import 'redux'; import './turn-order-8aebcd40.js'; import 'immer'; import 'lodash.isplainobject'; import './reducer-d2f4a5f2.js'; import 'rfc6902'; import './initialize-428f1f11.js'; import './transport-0079de87.js'; import { C as Client$1 } from './client-74396fd9.js'; import 'flatted'; import './ai-93f31f7d.js'; import React from 'react'; import PropTypes from 'prop-types'; var _excluded = ["matchID", "playerID"]; /** * Client * * boardgame.io React Native client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React Native component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE. */ function Client(opts) { var _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer; /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _temp = _class = /*#__PURE__*/function (_React$Component) { _inherits(WrappedBoard, _React$Component); var _super = _createSuper(WrappedBoard); function WrappedBoard(props) { var _this; _classCallCheck(this, WrappedBoard); _this = _super.call(this, props); _this.client = Client$1({ game: game, numPlayers: numPlayers, multiplayer: multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, debug: false, enhancer: enhancer }); return _this; } _createClass(WrappedBoard, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.client.subscribe(function () { return _this2.forceUpdate(); }); this.client.start(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.client.stop(); this.unsubscribe(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.matchID != this.props.matchID) { this.client.updateMatchID(this.props.matchID); } if (prevProps.playerID != this.props.playerID) { this.client.updatePlayerID(this.props.playerID); } if (prevProps.credentials != this.props.credentials) { this.client.updateCredentials(this.props.credentials); } } }, { key: "render", value: function render() { var _board = null; var state = this.client.getState(); var _this$props = this.props, matchID = _this$props.matchID, playerID = _this$props.playerID, rest = _objectWithoutProperties(_this$props, _excluded); if (board) { _board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, { matchID: matchID, playerID: playerID, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, step: this.client.step, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, matchData: this.client.matchData, sendChatMessage: this.client.sendChatMessage, chatMessages: this.client.chatMessages })); } return _board; } }]); return WrappedBoard; }(React.Component), _defineProperty(_class, "propTypes", { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string }), _defineProperty(_class, "defaultProps", { matchID: 'default', playerID: null, credentials: null }), _temp; } export { Client };
ajax/libs/primereact/7.0.1/datatable/datatable.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Paginator } from 'primereact/paginator'; import { classNames, ObjectUtils, DomHandler, ZIndexUtils, ConnectedOverlayScrollHandler, UniqueComponentId } from 'primereact/utils'; import PrimeReact, { localeOption, FilterOperator, FilterMatchMode as FilterMatchMode$1, FilterService } from 'primereact/api'; import { OverlayService } from 'primereact/overlayservice'; import { Ripple } from 'primereact/ripple'; import { CSSTransition } from 'primereact/csstransition'; import { Portal } from 'primereact/portal'; import { InputText } from 'primereact/inputtext'; import { Dropdown } from 'primereact/dropdown'; import { Button } from 'primereact/button'; import { VirtualScroller } from 'primereact/virtualscroller'; function _extends() { _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; }; return _extends.apply(this, arguments); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableRest() { 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _createSuper$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowRadioButton = /*#__PURE__*/function (_Component) { _inherits(RowRadioButton, _Component); var _super = _createSuper$c(RowRadioButton); function RowRadioButton(props) { var _this; _classCallCheck(this, RowRadioButton); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onChange = _this.onChange.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowRadioButton, [{ key: "onClick", value: function onClick(event) { if (!this.props.disabled) { this.props.onChange({ originalEvent: event, data: this.props.value }); this.input.focus(); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onChange", value: function onChange(event) { this.onClick(event); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-radiobutton-box p-component', { 'p-highlight': this.props.checked, 'p-focus': this.state.focused, 'p-disabled': this.props.disabled }); var name = "".concat(this.props.tableSelector, "_dt_radio"); return /*#__PURE__*/React.createElement("div", { className: "p-radiobutton p-component" }, /*#__PURE__*/React.createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React.createElement("input", { name: name, ref: function ref(el) { return _this2.input = el; }, type: "radio", checked: this.props.checked, onFocus: this.onFocus, onBlur: this.onBlur, onChange: this.onChange, onKeyDown: this.onKeyDown })), /*#__PURE__*/React.createElement("div", { className: className, onClick: this.onClick, role: "radio", "aria-checked": this.props.checked }, /*#__PURE__*/React.createElement("div", { className: "p-radiobutton-icon" }))); } }]); return RowRadioButton; }(Component); function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowCheckbox = /*#__PURE__*/function (_Component) { _inherits(RowCheckbox, _Component); var _super = _createSuper$b(RowCheckbox); function RowCheckbox(props) { var _this; _classCallCheck(this, RowCheckbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowCheckbox, [{ key: "onClick", value: function onClick(event) { if (!this.props.disabled) { this.setState({ focused: true }); this.props.onChange({ originalEvent: event, data: this.props.value }); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var className = classNames('p-checkbox-box p-component', { 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClassName = classNames('p-checkbox-icon', { 'pi pi-check': this.props.checked }); var tabIndex = this.props.disabled ? null : '0'; return /*#__PURE__*/React.createElement("div", { className: "p-checkbox p-component", onClick: this.onClick }, /*#__PURE__*/React.createElement("div", { className: className, role: "checkbox", "aria-checked": this.props.checked, tabIndex: tabIndex, onKeyDown: this.onKeyDown, onFocus: this.onFocus, onBlur: this.onBlur }, /*#__PURE__*/React.createElement("span", { className: iconClassName }))); } }]); return RowCheckbox; }(Component); function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var BodyCell = /*#__PURE__*/function (_Component) { _inherits(BodyCell, _Component); var _super = _createSuper$a(BodyCell); function BodyCell(props) { var _this; _classCallCheck(this, BodyCell); _this = _super.call(this, props); _this.state = { editing: props.editing, editingRowData: props.rowData, styleObject: {} }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onMouseUp = _this.onMouseUp.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onEditorFocus = _this.onEditorFocus.bind(_assertThisInitialized(_this)); _this.onRowToggle = _this.onRowToggle.bind(_assertThisInitialized(_this)); _this.onRowEditSave = _this.onRowEditSave.bind(_assertThisInitialized(_this)); _this.onRowEditCancel = _this.onRowEditCancel.bind(_assertThisInitialized(_this)); _this.onRowEditInit = _this.onRowEditInit.bind(_assertThisInitialized(_this)); _this.editorCallback = _this.editorCallback.bind(_assertThisInitialized(_this)); return _this; } _createClass(BodyCell, [{ key: "field", get: function get() { return this.getColumnProp('field') || "field_".concat(this.props.index); } }, { key: "isEditable", value: function isEditable() { return this.getColumnProp('editor'); } }, { key: "isSelected", value: function isSelected() { return this.props.selection ? this.props.selection instanceof Array ? this.findIndex(this.props.selection) > -1 : this.equals(this.props.selection) : false; } }, { key: "equalsData", value: function equalsData(data) { return this.props.compareSelectionBy === 'equals' ? data === this.props.rowData : ObjectUtils.equals(data, this.props.rowData, this.props.dataKey); } }, { key: "equals", value: function equals(selectedCell) { return (selectedCell.rowIndex === this.props.rowIndex || this.equalsData(selectedCell.rowData)) && (selectedCell.field === this.field || selectedCell.cellIndex === this.props.index); } }, { key: "isOutsideClicked", value: function isOutsideClicked(target) { return this.el && !(this.el.isSameNode(target) || this.el.contains(target)); } }, { key: "getColumnProp", value: function getColumnProp(prop) { return this.props.column ? this.props.column.props[prop] : null; } }, { key: "getVirtualScrollerOption", value: function getVirtualScrollerOption(option) { return this.props.virtualScrollerOptions ? this.props.virtualScrollerOptions[option] : null; } }, { key: "getStyle", value: function getStyle() { var bodyStyle = this.getColumnProp('bodyStyle'); var columnStyle = this.getColumnProp('style'); return this.getColumnProp('frozen') ? Object.assign({}, columnStyle, bodyStyle, this.state.styleObject) : Object.assign({}, columnStyle, bodyStyle); } }, { key: "getCellCallbackParams", value: function getCellCallbackParams(event) { return { originalEvent: event, value: this.resolveFieldData(), field: this.field, rowData: this.props.rowData, rowIndex: this.props.rowIndex, cellIndex: this.props.index, selected: this.isSelected(), column: this.props.column, props: this.props }; } }, { key: "resolveFieldData", value: function resolveFieldData(data) { return ObjectUtils.resolveFieldData(data || this.props.rowData, this.field); } }, { key: "getEditingRowData", value: function getEditingRowData() { return this.props.editingMeta && this.props.editingMeta[this.props.rowIndex] ? this.props.editingMeta[this.props.rowIndex].data : this.props.rowData; } }, { key: "getTabIndex", value: function getTabIndex(cellSelected) { return this.props.allowCellSelection ? cellSelected ? 0 : this.props.rowIndex === 0 && this.props.index === 0 ? this.props.tabIndex : -1 : null; } }, { key: "findIndex", value: function findIndex(collection) { var _this2 = this; return (collection || []).findIndex(function (data) { return _this2.equals(data); }); } }, { key: "closeCell", value: function closeCell(event) { var _this3 = this; var params = this.getCellCallbackParams(event); var onBeforeCellEditHide = this.getColumnProp('onBeforeCellEditHide'); if (onBeforeCellEditHide) { onBeforeCellEditHide(params); } /* When using the 'tab' key, the focus event of the next cell is not called in IE. */ setTimeout(function () { _this3.setState({ editing: false }, function () { _this3.unbindDocumentEditListener(); OverlayService.off('overlay-click', _this3.overlayEventListener); _this3.overlayEventListener = null; }); }, 1); } }, { key: "switchCellToViewMode", value: function switchCellToViewMode(event, submit) { var callbackParams = this.getCellCallbackParams(event); var newRowData = this.state.editingRowData; var newValue = this.resolveFieldData(newRowData); var params = _objectSpread$7(_objectSpread$7({}, callbackParams), {}, { newRowData: newRowData, newValue: newValue }); var onCellEditCancel = this.getColumnProp('onCellEditCancel'); var cellEditValidator = this.getColumnProp('cellEditValidator'); var onCellEditComplete = this.getColumnProp('onCellEditComplete'); if (!submit && onCellEditCancel) { onCellEditCancel(params); } var valid = true; if (cellEditValidator) { valid = cellEditValidator(params); } if (valid) { if (submit && onCellEditComplete) { onCellEditComplete(params); } this.closeCell(event); } else { event.preventDefault(); } } }, { key: "findNextSelectableCell", value: function findNextSelectableCell(cell) { var nextCell = cell.nextElementSibling; return nextCell ? DomHandler.hasClass(nextCell, 'p-selectable-cell') ? nextCell : this.findNextSelectableRow(nextCell) : null; } }, { key: "findPrevSelectableCell", value: function findPrevSelectableCell(cell) { var prevCell = cell.previousElementSibling; return prevCell ? DomHandler.hasClass(prevCell, 'p-selectable-cell') ? prevCell : this.findPrevSelectableRow(prevCell) : null; } }, { key: "findNextSelectableRow", value: function findNextSelectableRow(row) { var nextRow = row.nextElementSibling; return nextRow ? DomHandler.hasClass(nextRow, 'p-selectable-row') ? nextRow : this.findNextSelectableRow(nextRow) : null; } }, { key: "findPrevSelectableRow", value: function findPrevSelectableRow(row) { var prevRow = row.previousElementSibling; if (prevRow) { return DomHandler.hasClass(prevRow, 'p-selectable-row') ? prevRow : this.findPrevSelectableRow(prevRow); } return null; } }, { key: "changeTabIndex", value: function changeTabIndex(currentCell, nextCell) { if (currentCell && nextCell) { currentCell.tabIndex = -1; nextCell.tabIndex = this.props.tabIndex; } } }, { key: "focusOnElement", value: function focusOnElement() { var _this4 = this; clearTimeout(this.tabindexTimeout); this.tabindexTimeout = setTimeout(function () { if (_this4.state.editing) { var focusableEl = DomHandler.getFirstFocusableElement(_this4.el, ':not(.p-cell-editor-key-helper)'); focusableEl && focusableEl.focus(); } _this4.keyHelper && (_this4.keyHelper.tabIndex = _this4.state.editing ? -1 : 0); }, 1); } }, { key: "updateStickyPosition", value: function updateStickyPosition() { if (this.getColumnProp('frozen')) { var styleObject = _objectSpread$7({}, this.state.styleObject); var align = this.getColumnProp('alignFrozen'); if (align === 'right') { var right = 0; var next = this.el.nextElementSibling; if (next) { right = DomHandler.getOuterWidth(next) + parseFloat(next.style.right || 0); } styleObject['right'] = right + 'px'; } else { var left = 0; var prev = this.el.previousElementSibling; if (prev) { left = DomHandler.getOuterWidth(prev) + parseFloat(prev.style.left || 0); } styleObject['left'] = left + 'px'; } var isSameStyle = this.state.styleObject['left'] === styleObject['left'] && this.state.styleObject['right'] === styleObject['right']; !isSameStyle && this.setState({ styleObject: styleObject }); } } }, { key: "editorCallback", value: function editorCallback(val) { var editingRowData = _objectSpread$7({}, this.state.editingRowData); editingRowData[this.field] = val; this.setState({ editingRowData: editingRowData }); // update editing meta for complete methods on row mode this.props.editingMeta[this.props.rowIndex].data[this.field] = val; } }, { key: "onClick", value: function onClick(event) { var _this5 = this; var params = this.getCellCallbackParams(event); if (this.props.editMode !== 'row' && this.isEditable() && !this.state.editing && (this.props.selectOnEdit || !this.props.selectOnEdit && this.props.selected)) { this.selfClick = true; var onBeforeCellEditShow = this.getColumnProp('onBeforeCellEditShow'); var onCellEditInit = this.getColumnProp('onCellEditInit'); var cellEditValidatorEvent = this.getColumnProp('cellEditValidatorEvent'); if (onBeforeCellEditShow) { onBeforeCellEditShow(params); } // If the data is sorted using sort icon, it has been added to wait for the sort operation when any cell is wanted to be opened. setTimeout(function () { _this5.setState({ editing: true }, function () { if (onCellEditInit) { onCellEditInit(params); } if (cellEditValidatorEvent === 'click') { _this5.bindDocumentEditListener(); _this5.overlayEventListener = function (e) { if (!_this5.isOutsideClicked(e.target)) { _this5.selfClick = true; } }; OverlayService.on('overlay-click', _this5.overlayEventListener); } }); }, 1); } if (this.props.allowCellSelection && this.props.onClick) { this.props.onClick(params); } } }, { key: "onMouseDown", value: function onMouseDown(event) { var params = this.getCellCallbackParams(event); if (this.props.onMouseDown) { this.props.onMouseDown(params); } } }, { key: "onMouseUp", value: function onMouseUp(event) { var params = this.getCellCallbackParams(event); if (this.props.onMouseUp) { this.props.onMouseUp(params); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.editMode !== 'row') { if (event.which === 13 || event.which === 9) { // tab || enter this.switchCellToViewMode(event, true); } if (event.which === 27) { // escape this.switchCellToViewMode(event, false); } } if (this.props.allowCellSelection) { var target = event.target, cell = event.currentTarget; switch (event.which) { //left arrow case 37: var prevCell = this.findPrevSelectableCell(cell); if (prevCell) { this.changeTabIndex(cell, prevCell); prevCell.focus(); } event.preventDefault(); break; //right arrow case 39: var nextCell = this.findNextSelectableCell(cell); if (nextCell) { this.changeTabIndex(cell, nextCell); nextCell.focus(); } event.preventDefault(); break; //up arrow case 38: var prevRow = this.findPrevSelectableRow(cell.parentElement); if (prevRow) { var upCell = prevRow.children[this.props.index]; this.changeTabIndex(cell, upCell); upCell.focus(); } event.preventDefault(); break; //down arrow case 40: var nextRow = this.findNextSelectableRow(cell.parentElement); if (nextRow) { var downCell = nextRow.children[this.props.index]; this.changeTabIndex(cell, downCell); downCell.focus(); } event.preventDefault(); break; //enter case 13: // @deprecated if (!DomHandler.isClickable(target)) { this.onClick(event); event.preventDefault(); } break; //space case 32: if (!DomHandler.isClickable(target) && !target.readOnly) { this.onClick(event); event.preventDefault(); } break; } } } }, { key: "onBlur", value: function onBlur(event) { this.selfClick = false; if (this.props.editMode !== 'row' && this.state.editing && this.getColumnProp('cellEditValidatorEvent') === 'blur') { this.switchCellToViewMode(event, true); } } }, { key: "onEditorFocus", value: function onEditorFocus(event) { this.onClick(event); } }, { key: "onRowToggle", value: function onRowToggle(event) { this.props.onRowToggle({ originalEvent: event, data: this.props.rowData }); event.preventDefault(); } }, { key: "onRowEditInit", value: function onRowEditInit(event) { this.props.onRowEditInit({ originalEvent: event, data: this.props.rowData, newData: this.getEditingRowData(), field: this.field, index: this.props.rowIndex }); } }, { key: "onRowEditSave", value: function onRowEditSave(event) { this.props.onRowEditSave({ originalEvent: event, data: this.props.rowData, newData: this.getEditingRowData(), field: this.field, index: this.props.rowIndex }); } }, { key: "onRowEditCancel", value: function onRowEditCancel(event) { this.props.onRowEditCancel({ originalEvent: event, data: this.props.rowData, newData: this.getEditingRowData(), field: this.field, index: this.props.rowIndex }); } }, { key: "bindDocumentEditListener", value: function bindDocumentEditListener() { var _this6 = this; if (!this.documentEditListener) { this.documentEditListener = function (e) { if (!_this6.selfClick && _this6.isOutsideClicked(e.target)) { _this6.switchCellToViewMode(e, true); } _this6.selfClick = false; }; document.addEventListener('click', this.documentEditListener, true); } } }, { key: "unbindDocumentEditListener", value: function unbindDocumentEditListener() { if (this.documentEditListener) { document.removeEventListener('click', this.documentEditListener, true); this.documentEditListener = null; this.selfClick = false; } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } if (this.props.editMode === 'cell' || this.props.editMode === 'row') { this.focusOnElement(); if (prevProps.editingMeta !== this.props.editingMeta) { this.setState({ editingRowData: this.getEditingRowData() }); } if (prevState.editing !== this.state.editing) { var callbackParams = this.getCellCallbackParams(); var params = _objectSpread$7(_objectSpread$7({}, callbackParams), {}, { editing: this.state.editing }); this.props.onEditingMetaChange(params); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentEditListener(); if (this.overlayEventListener) { OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } } }, { key: "renderLoading", value: function renderLoading() { var options = this.getVirtualScrollerOption('getLoaderOptions')(this.props.rowIndex, { cellIndex: this.props.index, cellFirst: this.props.index === 0, cellLast: this.props.index === this.getVirtualScrollerOption('columns').length - 1, cellEven: this.props.index % 2 === 0, cellOdd: this.props.index % 2 !== 0, column: this.props.column, field: this.field }); var content = ObjectUtils.getJSXElement(this.getVirtualScrollerOption('loadingTemplate'), options); return /*#__PURE__*/React.createElement("td", null, content); } }, { key: "renderElement", value: function renderElement() { var _this7 = this; var content, editorKeyHelper; var cellSelected = this.props.allowCellSelection && this.isSelected(); var isRowEditor = this.props.editMode === 'row'; var tabIndex = this.getTabIndex(cellSelected); var selectionMode = this.getColumnProp('selectionMode'); var rowReorder = this.getColumnProp('rowReorder'); var expander = this.getColumnProp('expander'); var rowEditor = this.getColumnProp('rowEditor'); var header = this.getColumnProp('header'); var body = this.getColumnProp('body'); var editor = this.getColumnProp('editor'); var frozen = this.getColumnProp('frozen'); var value = this.resolveFieldData(); var cellClassName = ObjectUtils.getPropValue(this.props.cellClassName, value, { props: this.props.tableProps, rowData: this.props.rowData }); var className = classNames(this.getColumnProp('bodyClassName'), this.getColumnProp('class'), cellClassName, { 'p-selection-column': selectionMode !== null, 'p-editable-column': editor, 'p-cell-editing': editor && this.state.editing, 'p-frozen-column': frozen, 'p-selectable-cell': this.props.allowCellSelection, 'p-highlight': cellSelected }); var style = this.getStyle(); var title = this.props.responsiveLayout === 'stack' && /*#__PURE__*/React.createElement("span", { className: "p-column-title" }, ObjectUtils.getJSXElement(header, { props: this.props.tableProps })); if (body && !this.state.editing) { content = body ? ObjectUtils.getJSXElement(body, this.props.rowData, { column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps }) : value; } else if (editor && this.state.editing) { content = ObjectUtils.getJSXElement(editor, { rowData: this.state.editingRowData, value: this.resolveFieldData(this.state.editingRowData), column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps, editorCallback: this.editorCallback }); } else if (selectionMode) { var showSelection = this.props.showSelectionElement ? this.props.showSelectionElement(this.props.rowData, { rowIndex: this.props.rowIndex, props: this.props.tableProps }) : true; content = showSelection && /*#__PURE__*/React.createElement(React.Fragment, null, selectionMode === 'single' && /*#__PURE__*/React.createElement(RowRadioButton, { value: this.props.rowData, checked: this.props.selected, onChange: this.props.onRadioChange, tabIndex: this.props.tabIndex, tableSelector: this.props.tableSelector }), selectionMode === 'multiple' && /*#__PURE__*/React.createElement(RowCheckbox, { value: this.props.rowData, checked: this.props.selected, onChange: this.props.onCheckboxChange, tabIndex: this.props.tabIndex })); } else if (rowReorder) { var showReorder = this.props.showRowReorderElement ? this.props.showRowReorderElement(this.props.rowData, { rowIndex: this.props.rowIndex, props: this.props.tableProps }) : true; content = showReorder && /*#__PURE__*/React.createElement("i", { className: classNames('p-datatable-reorderablerow-handle', this.getColumnProp('rowReorderIcon')) }); } else if (expander) { var iconClassName = classNames('p-row-toggler-icon', this.props.expanded ? this.props.expandedRowIcon : this.props.collapsedRowIcon); var ariaControls = "".concat(this.props.tableSelector, "_content_").concat(this.props.rowIndex, "_expanded"); var expanderProps = { onClick: this.onRowToggle, className: 'p-row-toggler p-link', iconClassName: iconClassName }; content = /*#__PURE__*/React.createElement("button", { className: expanderProps.className, onClick: expanderProps.onClick, type: "button", "aria-expanded": this.props.expanded, "aria-controls": ariaControls, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: expanderProps.iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (body) { expanderProps['element'] = content; content = ObjectUtils.getJSXElement(body, this.props.rowData, { column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps, expander: expanderProps }); } } else if (isRowEditor && rowEditor) { var rowEditorProps = {}; if (this.state.editing) { rowEditorProps = { editing: true, onSaveClick: this.onRowEditSave, saveClassName: 'p-row-editor-save p-link', saveIconClassName: 'p-row-editor-save-icon pi pi-fw pi-check', onCancelClick: this.onRowEditCancel, cancelClassName: 'p-row-editor-cancel p-link', cancelIconClassName: 'p-row-editor-cancel-icon pi pi-fw pi-times' }; content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onSaveClick, className: rowEditorProps.saveClassName, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.saveIconClassName }), /*#__PURE__*/React.createElement(Ripple, null)), /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onCancelClick, className: rowEditorProps.cancelClassName, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.cancelIconClassName }), /*#__PURE__*/React.createElement(Ripple, null))); } else { rowEditorProps = { editing: false, onInitClick: this.onRowEditInit, initClassName: 'p-row-editor-init p-link', initIconClassName: 'p-row-editor-init-icon pi pi-fw pi-pencil' }; content = /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onInitClick, className: rowEditorProps.initClassName, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.initIconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } if (body) { rowEditorProps['element'] = content; content = ObjectUtils.getJSXElement(body, this.props.rowData, { column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps, rowEditor: rowEditorProps }); } } else { content = value; } if (!isRowEditor && editor) { /* eslint-disable */ editorKeyHelper = /*#__PURE__*/React.createElement("a", { tabIndex: "0", ref: function ref(el) { return _this7.keyHelper = el; }, className: "p-cell-editor-key-helper p-hidden-accessible", onFocus: this.onEditorFocus }, /*#__PURE__*/React.createElement("span", null)); /* eslint-enable */ } return /*#__PURE__*/React.createElement("td", { ref: function ref(el) { return _this7.el = el; }, style: style, className: className, rowSpan: this.props.rowSpan, tabIndex: tabIndex, role: "cell", onClick: this.onClick, onKeyDown: this.onKeyDown, onBlur: this.onBlur, onMouseDown: this.onMouseDown, onMouseUp: this.onMouseUp }, editorKeyHelper, title, content); } }, { key: "render", value: function render() { return this.getVirtualScrollerOption('loading') ? this.renderLoading() : this.renderElement(); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (nextProps.editMode === 'row' && nextProps.editing !== prevState.editing) { return { editing: nextProps.editing }; } return null; } }]); return BodyCell; }(Component); function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var BodyRow = /*#__PURE__*/function (_Component) { _inherits(BodyRow, _Component); var _super = _createSuper$9(BodyRow); function BodyRow(props) { var _this; _classCallCheck(this, BodyRow); _this = _super.call(this, props); if (!_this.props.onRowEditChange) { _this.state = { editing: false }; } _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onDoubleClick = _this.onDoubleClick.bind(_assertThisInitialized(_this)); _this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onMouseUp = _this.onMouseUp.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onEditInit = _this.onEditInit.bind(_assertThisInitialized(_this)); _this.onEditSave = _this.onEditSave.bind(_assertThisInitialized(_this)); _this.onEditCancel = _this.onEditCancel.bind(_assertThisInitialized(_this)); return _this; } _createClass(BodyRow, [{ key: "isFocusable", value: function isFocusable() { return this.props.selectionMode && this.props.selectionModeInColumn !== 'single' && this.props.selectionModeInColumn !== 'multiple'; } }, { key: "isGrouped", value: function isGrouped(column) { if (this.props.groupRowsBy && this.getColumnProp(column, 'field')) { if (Array.isArray(this.props.groupRowsBy)) return this.props.groupRowsBy.indexOf(column.props.field) > -1;else return this.props.groupRowsBy === column.props.field; } return false; } }, { key: "equals", value: function equals(data1, data2) { return this.props.compareSelectionBy === 'equals' ? data1 === data2 : ObjectUtils.equals(data1, data2, this.props.dataKey); } }, { key: "getColumnProp", value: function getColumnProp(col, prop) { return col ? col.props[prop] : null; } }, { key: "getEditing", value: function getEditing() { return this.props.onRowEditChange ? this.props.editing : this.state.editing; } }, { key: "getTabIndex", value: function getTabIndex() { return this.isFocusable() && !this.props.allowCellSelection ? this.props.index === 0 ? this.props.tabIndex : -1 : null; } }, { key: "findIndex", value: function findIndex(collection, rowData) { var _this2 = this; return (collection || []).findIndex(function (data) { return _this2.equals(rowData, data); }); } }, { key: "changeTabIndex", value: function changeTabIndex(currentRow, nextRow) { if (currentRow && nextRow) { currentRow.tabIndex = -1; nextRow.tabIndex = this.props.tabIndex; } } }, { key: "findNextSelectableRow", value: function findNextSelectableRow(row) { var nextRow = row.nextElementSibling; return nextRow ? DomHandler.hasClass(nextRow, 'p-selectable-row') ? nextRow : this.findNextSelectableRow(nextRow) : null; } }, { key: "findPrevSelectableRow", value: function findPrevSelectableRow(row) { var prevRow = row.previousElementSibling; return prevRow ? DomHandler.hasClass(prevRow, 'p-selectable-row') ? prevRow : this.findPrevSelectableRow(prevRow) : null; } }, { key: "shouldRenderBodyCell", value: function shouldRenderBodyCell(value, column, i) { if (this.getColumnProp(column, 'hidden')) { return false; } else if (this.props.rowGroupMode && this.props.rowGroupMode === 'rowspan' && this.isGrouped(column)) { var prevRowData = value[i - 1]; if (prevRowData) { var currentRowFieldData = ObjectUtils.resolveFieldData(value[i], this.getColumnProp(column, 'field')); var previousRowFieldData = ObjectUtils.resolveFieldData(prevRowData, this.getColumnProp(column, 'field')); return currentRowFieldData !== previousRowFieldData; } } return true; } }, { key: "calculateRowGroupSize", value: function calculateRowGroupSize(value, column, index) { if (this.isGrouped(column)) { var currentRowFieldData = ObjectUtils.resolveFieldData(value[index], this.getColumnProp(column, 'field')); var nextRowFieldData = currentRowFieldData; var groupRowSpan = 0; while (currentRowFieldData === nextRowFieldData) { groupRowSpan++; var nextRowData = value[++index]; if (nextRowData) { nextRowFieldData = ObjectUtils.resolveFieldData(nextRowData, this.getColumnProp(column, 'field')); } else { break; } } return groupRowSpan === 1 ? null : groupRowSpan; } else { return null; } } }, { key: "onClick", value: function onClick(event) { this.props.onRowClick({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDoubleClick", value: function onDoubleClick(event) { this.props.onRowDoubleClick({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onRightClick", value: function onRightClick(event) { this.props.onRowRightClick({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onTouchEnd", value: function onTouchEnd(event) { this.props.onRowTouchEnd(event); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.isFocusable() && !this.props.allowCellSelection) { var target = event.target, row = event.currentTarget; switch (event.which) { //down arrow case 40: var nextRow = this.findNextSelectableRow(row); if (nextRow) { this.changeTabIndex(row, nextRow); nextRow.focus(); } event.preventDefault(); break; //up arrow case 38: var prevRow = this.findPrevSelectableRow(row); if (prevRow) { this.changeTabIndex(row, prevRow); prevRow.focus(); } event.preventDefault(); break; //enter case 13: // @deprecated if (!DomHandler.isClickable(target)) { this.onClick(event); event.preventDefault(); } break; //space case 32: if (!DomHandler.isClickable(target) && !target.readOnly) { this.onClick(event); event.preventDefault(); } break; } } } }, { key: "onMouseDown", value: function onMouseDown(event) { this.props.onRowMouseDown({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onMouseUp", value: function onMouseUp(event) { this.props.onRowMouseUp({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragStart", value: function onDragStart(event) { this.props.onRowDragStart({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragOver", value: function onDragOver(event) { this.props.onRowDragOver({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragLeave", value: function onDragLeave(event) { this.props.onRowDragLeave({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragEnd", value: function onDragEnd(event) { this.props.onRowDragEnd({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDrop", value: function onDrop(event) { this.props.onRowDrop({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onEditChange", value: function onEditChange(e, editing) { if (this.props.onRowEditChange) { var editingRows; var dataKey = this.props.dataKey; var originalEvent = e.originalEvent, data = e.data, index = e.index; if (dataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(data, dataKey)); editingRows = this.props.editingRows ? _objectSpread$6({}, this.props.editingRows) : {}; if (editingRows[dataKeyValue] != null) delete editingRows[dataKeyValue];else editingRows[dataKeyValue] = true; } else { var editingRowIndex = this.findIndex(this.props.editingRows, data); editingRows = this.props.editingRows ? _toConsumableArray(this.props.editingRows) : []; if (editingRowIndex !== -1) editingRows = editingRows.filter(function (val, i) { return i !== editingRowIndex; });else editingRows.push(data); } this.props.onRowEditChange({ originalEvent: originalEvent, data: editingRows, index: index }); } else { this.setState({ editing: editing }); } } }, { key: "onEditInit", value: function onEditInit(e) { var event = e.originalEvent; if (this.props.onRowEditInit) { this.props.onRowEditInit({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } this.onEditChange(e, true); event.preventDefault(); } }, { key: "onEditSave", value: function onEditSave(e) { var event = e.originalEvent; var valid = this.props.rowEditValidator ? this.props.rowEditValidator(this.props.rowData, { props: this.props.tableProps }) : true; if (this.props.onRowEditSave) { this.props.onRowEditSave({ originalEvent: event, data: this.props.rowData, index: this.props.index, valid: valid }); } if (valid) { if (this.props.onRowEditComplete) { this.props.onRowEditComplete(e); } this.onEditChange(e, false); } event.preventDefault(); } }, { key: "onEditCancel", value: function onEditCancel(e) { var event = e.originalEvent; if (this.props.onRowEditCancel) { this.props.onRowEditCancel({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } this.onEditChange(e, false); event.preventDefault(); } }, { key: "renderContent", value: function renderContent() { var _this3 = this; return this.props.columns.map(function (col, i) { if (_this3.shouldRenderBodyCell(_this3.props.value, col, _this3.props.index)) { var key = "".concat(_this3.getColumnProp(col, 'columnKey') || _this3.getColumnProp(col, 'field'), "_").concat(i); var rowSpan = _this3.props.rowGroupMode === 'rowspan' ? _this3.calculateRowGroupSize(_this3.props.value, col, _this3.props.index) : null; var editing = _this3.getEditing(); return /*#__PURE__*/React.createElement(BodyCell, { key: key, value: _this3.props.value, tableProps: _this3.props.tableProps, tableSelector: _this3.props.tableSelector, column: col, rowData: _this3.props.rowData, rowIndex: _this3.props.index, index: i, rowSpan: rowSpan, dataKey: _this3.props.dataKey, editing: editing, editingMeta: _this3.props.editingMeta, editMode: _this3.props.editMode, onRowEditInit: _this3.onEditInit, onRowEditSave: _this3.onEditSave, onRowEditCancel: _this3.onEditCancel, onEditingMetaChange: _this3.props.onEditingMetaChange, onRowToggle: _this3.props.onRowToggle, selection: _this3.props.selection, allowCellSelection: _this3.props.allowCellSelection, compareSelectionBy: _this3.props.compareSelectionBy, selectOnEdit: _this3.props.selectOnEdit, selected: _this3.props.selected, onClick: _this3.props.onCellClick, onMouseDown: _this3.props.onCellMouseDown, onMouseUp: _this3.props.onCellMouseUp, tabIndex: _this3.props.tabIndex, cellClassName: _this3.props.cellClassName, responsiveLayout: _this3.props.responsiveLayout, frozenRow: _this3.props.frozenRow, showSelectionElement: _this3.props.showSelectionElement, showRowReorderElement: _this3.props.showRowReorderElement, onRadioChange: _this3.props.onRadioChange, onCheckboxChange: _this3.props.onCheckboxChange, expanded: _this3.props.expanded, expandedRowIcon: _this3.props.expandedRowIcon, collapsedRowIcon: _this3.props.collapsedRowIcon, virtualScrollerOptions: _this3.props.virtualScrollerOptions }); } return null; }); } }, { key: "render", value: function render() { var _this4 = this; var rowClassName = ObjectUtils.getPropValue(this.props.rowClassName, this.props.rowData, { props: this.props.tableProps }); var className = classNames(rowClassName, { 'p-highlight': !this.props.allowCellSelection && this.props.selected, 'p-highlight-contextmenu': this.props.contextMenuSelected, 'p-selectable-row': this.props.allowRowSelection, 'p-row-odd': this.props.index % 2 !== 0 }); var content = this.renderContent(); var tabIndex = this.getTabIndex(); return /*#__PURE__*/React.createElement("tr", { ref: function ref(el) { return _this4.el = el; }, role: "row", tabIndex: tabIndex, className: className, onMouseDown: this.onMouseDown, onMouseUp: this.onMouseUp, onClick: this.onClick, onDoubleClick: this.onDoubleClick, onContextMenu: this.onRightClick, onTouchEnd: this.onTouchEnd, onKeyDown: this.onKeyDown, onDragStart: this.onDragStart, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDragEnd: this.onDragEnd, onDrop: this.onDrop }, content); } }]); return BodyRow; }(Component); function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowTogglerButton = /*#__PURE__*/function (_Component) { _inherits(RowTogglerButton, _Component); var _super = _createSuper$8(RowTogglerButton); function RowTogglerButton(props) { var _this; _classCallCheck(this, RowTogglerButton); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowTogglerButton, [{ key: "onClick", value: function onClick(event) { this.props.onClick({ originalEvent: event, data: this.props.rowData }); } }, { key: "render", value: function render() { var iconClassName = classNames('p-row-toggler-icon', this.props.expanded ? this.props.expandedRowIcon : this.props.collapsedRowIcon); return /*#__PURE__*/React.createElement("button", { type: "button", onClick: this.onClick, className: "p-row-toggler p-link", tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } }]); return RowTogglerButton; }(Component); var _excluded = ["originalEvent"]; function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TableBody = /*#__PURE__*/function (_Component) { _inherits(TableBody, _Component); var _super = _createSuper$7(TableBody); function TableBody(props) { var _this; _classCallCheck(this, TableBody); _this = _super.call(this, props); _this.state = { rowGroupHeaderStyleObject: {} }; // row _this.onRowClick = _this.onRowClick.bind(_assertThisInitialized(_this)); _this.onRowDoubleClick = _this.onRowDoubleClick.bind(_assertThisInitialized(_this)); _this.onRowRightClick = _this.onRowRightClick.bind(_assertThisInitialized(_this)); _this.onRowTouchEnd = _this.onRowTouchEnd.bind(_assertThisInitialized(_this)); _this.onRowMouseDown = _this.onRowMouseDown.bind(_assertThisInitialized(_this)); _this.onRowMouseUp = _this.onRowMouseUp.bind(_assertThisInitialized(_this)); _this.onRowToggle = _this.onRowToggle.bind(_assertThisInitialized(_this)); // drag _this.onRowDragStart = _this.onRowDragStart.bind(_assertThisInitialized(_this)); _this.onRowDragOver = _this.onRowDragOver.bind(_assertThisInitialized(_this)); _this.onRowDragLeave = _this.onRowDragLeave.bind(_assertThisInitialized(_this)); _this.onRowDragEnd = _this.onRowDragEnd.bind(_assertThisInitialized(_this)); _this.onRowDrop = _this.onRowDrop.bind(_assertThisInitialized(_this)); // selection _this.onRadioChange = _this.onRadioChange.bind(_assertThisInitialized(_this)); _this.onCheckboxChange = _this.onCheckboxChange.bind(_assertThisInitialized(_this)); _this.onDragSelectionMouseMove = _this.onDragSelectionMouseMove.bind(_assertThisInitialized(_this)); _this.onDragSelectionMouseUp = _this.onDragSelectionMouseUp.bind(_assertThisInitialized(_this)); // cell _this.onCellClick = _this.onCellClick.bind(_assertThisInitialized(_this)); _this.onCellMouseDown = _this.onCellMouseDown.bind(_assertThisInitialized(_this)); _this.onCellMouseUp = _this.onCellMouseUp.bind(_assertThisInitialized(_this)); _this.ref = _this.ref.bind(_assertThisInitialized(_this)); return _this; } _createClass(TableBody, [{ key: "ref", value: function ref(el) { this.el = el; this.props.virtualScrollerContentRef && this.props.virtualScrollerContentRef(el); } }, { key: "equals", value: function equals(data1, data2) { if (this.allowCellSelection()) return (data1.rowIndex === data2.rowIndex || data1.rowData === data2.rowData) && (data1.field === data2.field || data1.cellIndex === data2.cellIndex);else return this.compareSelectionBy === 'equals' ? data1 === data2 : ObjectUtils.equals(data1, data2, this.props.dataKey); } }, { key: "isSubheaderGrouping", value: function isSubheaderGrouping() { return this.props.rowGroupMode && this.props.rowGroupMode === 'subheader'; } }, { key: "isSelectionEnabled", value: function isSelectionEnabled() { return this.props.selectionMode || this.props.selectionModeInColumn !== null || this.props.columns && this.props.columns.some(function (col) { return col && !!col.props.selectionMode; }); } }, { key: "isRadioSelectionMode", value: function isRadioSelectionMode() { return this.props.selectionMode === 'radiobutton'; } }, { key: "isCheckboxSelectionMode", value: function isCheckboxSelectionMode() { return this.props.selectionMode === 'checkbox'; } }, { key: "isRadioSelectionModeInColumn", value: function isRadioSelectionModeInColumn() { return this.props.selectionModeInColumn === 'single'; } }, { key: "isCheckboxSelectionModeInColumn", value: function isCheckboxSelectionModeInColumn() { return this.props.selectionModeInColumn === 'multiple'; } }, { key: "isSingleSelection", value: function isSingleSelection() { return this.props.selectionMode === 'single' && !this.isCheckboxSelectionModeInColumn() || !this.isRadioSelectionMode() && this.isRadioSelectionModeInColumn(); } }, { key: "isMultipleSelection", value: function isMultipleSelection() { return this.props.selectionMode === 'multiple' && !this.isRadioSelectionModeInColumn() || this.isCheckboxSelectionModeInColumn(); } }, { key: "isRadioOnlySelection", value: function isRadioOnlySelection() { return this.isRadioSelectionMode() && this.isRadioSelectionModeInColumn(); } }, { key: "isCheckboxOnlySelection", value: function isCheckboxOnlySelection() { return this.isCheckboxSelectionMode() && this.isCheckboxSelectionModeInColumn(); } }, { key: "isSelected", value: function isSelected(rowData) { if (rowData && this.props.selection) { return this.props.selection instanceof Array ? this.findIndex(this.props.selection, rowData) > -1 : this.equals(rowData, this.props.selection); } return false; } }, { key: "isContextMenuSelected", value: function isContextMenuSelected(rowData) { if (rowData && this.props.contextMenuSelection) { return this.equals(rowData, this.props.contextMenuSelection); } return false; } }, { key: "isRowExpanded", value: function isRowExpanded(rowData) { if (rowData && this.props.expandedRows) { if (this.isSubheaderGrouping() && this.props.expandableRowGroups) { return this.isRowGroupExpanded(rowData); } else { if (this.props.dataKey) return this.props.expandedRows ? this.props.expandedRows[ObjectUtils.resolveFieldData(rowData, this.props.dataKey)] !== undefined : false;else return this.findIndex(this.props.expandedRows, rowData) !== -1; } } return false; } }, { key: "isRowGroupExpanded", value: function isRowGroupExpanded(rowData) { var _this2 = this; if (this.props.dataKey === this.props.groupRowsBy) return Object.keys(this.props.expandedRows).some(function (data) { return ObjectUtils.equals(data, ObjectUtils.resolveFieldData(rowData, _this2.props.dataKey)); });else return this.props.expandedRows.some(function (data) { return ObjectUtils.equals(data, rowData, _this2.props.groupRowsBy); }); } }, { key: "isRowEditing", value: function isRowEditing(rowData) { if (this.props.editMode === 'row' && rowData && this.props.editingRows) { if (this.props.dataKey) return this.props.editingRows ? this.props.editingRows[ObjectUtils.resolveFieldData(rowData, this.props.dataKey)] !== undefined : false;else return this.findIndex(this.props.editingRows, rowData) !== -1; } return false; } }, { key: "allowDrag", value: function allowDrag(event) { return this.props.dragSelection && this.isMultipleSelection() && !event.originalEvent.shiftKey; } }, { key: "allowRowDrag", value: function allowRowDrag(event) { return !this.allowCellSelection() && this.allowDrag(event); } }, { key: "allowCellDrag", value: function allowCellDrag(event) { return this.allowCellSelection() && this.allowDrag(event); } }, { key: "allowSelection", value: function allowSelection(event) { return !DomHandler.isClickable(event.originalEvent.target); } }, { key: "allowMetaKeySelection", value: function allowMetaKeySelection(event) { return !this.rowTouched && (!this.props.metaKeySelection || this.props.metaKeySelection && (event.originalEvent.metaKey || event.originalEvent.ctrlKey)); } }, { key: "allowRangeSelection", value: function allowRangeSelection(event) { return this.isMultipleSelection() && event.originalEvent.shiftKey && this.anchorRowIndex !== null; } }, { key: "allowRowSelection", value: function allowRowSelection() { return (this.props.selectionMode || this.props.selectionModeInColumn) && !this.isRadioOnlySelection() && !this.isCheckboxOnlySelection(); } }, { key: "allowCellSelection", value: function allowCellSelection() { return this.props.cellSelection && !this.isRadioSelectionModeInColumn() && !this.isCheckboxSelectionModeInColumn(); } }, { key: "getColumnsLength", value: function getColumnsLength() { return this.props.columns ? this.props.columns.length : 0; } }, { key: "getVirtualScrollerOption", value: function getVirtualScrollerOption(option, options) { options = options || this.props.virtualScrollerOptions; return options ? options[option] : null; } }, { key: "findIndex", value: function findIndex(collection, rowData) { var _this3 = this; return (collection || []).findIndex(function (data) { return _this3.equals(rowData, data); }); } }, { key: "rowGroupHeaderStyle", value: function rowGroupHeaderStyle() { if (this.props.scrollable) { return { top: this.state.rowGroupHeaderStyleObject['top'] }; } return null; } }, { key: "getRowKey", value: function getRowKey(rowData, index) { return this.props.dataKey ? ObjectUtils.resolveFieldData(rowData, this.props.dataKey) + '_' + index : index; } }, { key: "shouldRenderRowGroupHeader", value: function shouldRenderRowGroupHeader(value, rowData, i) { var currentRowFieldData = ObjectUtils.resolveFieldData(rowData, this.props.groupRowsBy); var prevRowData = value[i - 1]; if (prevRowData) { var previousRowFieldData = ObjectUtils.resolveFieldData(prevRowData, this.props.groupRowsBy); return currentRowFieldData !== previousRowFieldData; } else { return true; } } }, { key: "shouldRenderRowGroupFooter", value: function shouldRenderRowGroupFooter(value, rowData, i, expanded) { if (this.props.expandableRowGroups && !expanded) { return false; } else { var currentRowFieldData = ObjectUtils.resolveFieldData(rowData, this.props.groupRowsBy); var nextRowData = value[i + 1]; if (nextRowData) { var nextRowFieldData = ObjectUtils.resolveFieldData(nextRowData, this.props.groupRowsBy); return currentRowFieldData !== nextRowFieldData; } else { return true; } } } }, { key: "updateFrozenRowStickyPosition", value: function updateFrozenRowStickyPosition() { this.el.style.top = DomHandler.getOuterHeight(this.el.previousElementSibling) + 'px'; } }, { key: "updateFrozenRowGroupHeaderStickyPosition", value: function updateFrozenRowGroupHeaderStickyPosition() { var tableHeaderHeight = DomHandler.getOuterHeight(this.el.previousElementSibling); var top = tableHeaderHeight + 'px'; if (this.state.rowGroupHeaderStyleObject && this.state.rowGroupHeaderStyleObject.top !== top) { this.setState({ rowGroupHeaderStyleObject: { top: top } }); } } }, { key: "updateVirtualScrollerPosition", value: function updateVirtualScrollerPosition() { var tableHeaderHeight = DomHandler.getOuterHeight(this.el.previousElementSibling); this.el.style.top = (this.el.style.top || 0) + tableHeaderHeight + 'px'; } }, { key: "onSingleSelection", value: function onSingleSelection(_ref) { var originalEvent = _ref.originalEvent, data = _ref.data, toggleable = _ref.toggleable, type = _ref.type; var selected = this.isSelected(data); var selection = this.props.selection; if (selected) { if (toggleable) { selection = null; this.onUnselect({ originalEvent: originalEvent, data: data, type: type }); } } else { selection = data; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } this.focusOnElement(originalEvent, true); if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onMultipleSelection", value: function onMultipleSelection(_ref2) { var _this4 = this; var originalEvent = _ref2.originalEvent, data = _ref2.data, toggleable = _ref2.toggleable, type = _ref2.type; var selected = this.isSelected(data); var selection = this.props.selection || []; if (selected) { if (toggleable) { var selectionIndex = this.findIndex(selection, data); selection = this.props.selection.filter(function (val, i) { return i !== selectionIndex; }); this.onUnselect({ originalEvent: originalEvent, data: data, type: type }); } else if (selection.length) { this.props.selection.forEach(function (d) { return _this4.onUnselect({ originalEvent: originalEvent, data: d, type: type }); }); selection = [data]; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } } else { selection = toggleable && this.isMultipleSelection() ? [].concat(_toConsumableArray(selection), [data]) : [data]; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } this.focusOnElement(originalEvent, true); if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onRangeSelection", value: function onRangeSelection(event) { DomHandler.clearSelection(); this.rangeRowIndex = this.allowCellSelection() ? event.rowIndex : event.index; var selectionInRange = this.selectRange(event); var selection = this.isMultipleSelection() ? _toConsumableArray(new Set([].concat(_toConsumableArray(this.props.selection || []), _toConsumableArray(selectionInRange)))) : selectionInRange; if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: event.originalEvent, value: selection }); } this.anchorRowIndex = this.rangeRowIndex; this.anchorCellIndex = event.cellIndex; this.focusOnElement(event.originalEvent, false); } }, { key: "selectRange", value: function selectRange(event) { var rangeStart, rangeEnd; var isLazyAndPaginator = this.props.lazy && this.props.paginator; if (isLazyAndPaginator) { this.anchorRowIndex += this.anchorRowFirst; this.rangeRowIndex += this.props.first; } if (this.rangeRowIndex > this.anchorRowIndex) { rangeStart = this.anchorRowIndex; rangeEnd = this.rangeRowIndex; } else if (this.rangeRowIndex < this.anchorRowIndex) { rangeStart = this.rangeRowIndex; rangeEnd = this.anchorRowIndex; } else { rangeStart = rangeEnd = this.rangeRowIndex; } if (isLazyAndPaginator) { rangeStart = Math.max(rangeStart - this.props.first, 0); rangeEnd -= this.props.first; } return this.allowCellSelection() ? this.selectRangeOnCell(event, rangeStart, rangeEnd) : this.selectRangeOnRow(event, rangeStart, rangeEnd); } }, { key: "selectRangeOnRow", value: function selectRangeOnRow(event, rowRangeStart, rowRangeEnd) { var value = this.props.value; var selection = []; for (var i = rowRangeStart; i <= rowRangeEnd; i++) { var rangeRowData = value[i]; selection.push(rangeRowData); this.onSelect({ originalEvent: event.originalEvent, data: rangeRowData, type: 'row' }); } return selection; } }, { key: "selectRangeOnCell", value: function selectRangeOnCell(event, rowRangeStart, rowRangeEnd) { var cellRangeStart, cellRangeEnd, cellIndex = event.cellIndex; if (cellIndex > this.anchorCellIndex) { cellRangeStart = this.anchorCellIndex; cellRangeEnd = cellIndex; } else if (cellIndex < this.anchorCellIndex) { cellRangeStart = cellIndex; cellRangeEnd = this.anchorCellIndex; } else { cellRangeStart = cellRangeEnd = cellIndex; } var value = this.props.value; var selection = []; for (var i = rowRangeStart; i <= rowRangeEnd; i++) { var rowData = value[i]; var columns = this.props.columns; for (var j = cellRangeStart; j <= cellRangeEnd; j++) { var field = columns[j].props.field; var rangeRowData = { value: ObjectUtils.resolveFieldData(rowData, field), field: field, rowData: rowData, rowIndex: i, cellIndex: j, selected: true }; selection.push(rangeRowData); this.onSelect({ originalEvent: event.originalEvent, data: rangeRowData, type: 'cell' }); } } return selection; } }, { key: "onSelect", value: function onSelect(event) { if (this.allowCellSelection()) this.props.onCellSelect && this.props.onCellSelect(_objectSpread$5(_objectSpread$5({ originalEvent: event.originalEvent }, event.data), {}, { type: event.type }));else this.props.onRowSelect && this.props.onRowSelect(event); } }, { key: "onUnselect", value: function onUnselect(event) { if (this.allowCellSelection()) this.props.onCellUnselect && this.props.onCellUnselect(_objectSpread$5(_objectSpread$5({ originalEvent: event.originalEvent }, event.data), {}, { type: event.type }));else this.props.onRowUnselect && this.props.onRowUnselect(event); } }, { key: "enableDragSelection", value: function enableDragSelection(event) { if (this.props.dragSelection && !this.dragSelectionHelper) { this.dragSelectionHelper = document.createElement('div'); DomHandler.addClass(this.dragSelectionHelper, 'p-datatable-drag-selection-helper'); this.initialDragPosition = { x: event.clientX, y: event.clientY }; this.dragSelectionHelper.style.top = "".concat(event.pageY, "px"); this.dragSelectionHelper.style.left = "".concat(event.pageX, "px"); this.bindDragSelectionEvents(); } } }, { key: "focusOnElement", value: function focusOnElement(event, isFocused) { var target = event.currentTarget; if (!this.allowCellSelection()) { if (this.isCheckboxSelectionModeInColumn()) { var checkbox = DomHandler.findSingle(target, 'td.p-selection-column .p-checkbox-box'); checkbox && checkbox.focus(); } else if (this.isRadioSelectionModeInColumn()) { var radio = DomHandler.findSingle(target, 'td.p-selection-column input[type="radio"]'); radio && radio.focus(); } } !isFocused && target && target.focus(); } }, { key: "onRowClick", value: function onRowClick(event) { if (this.allowCellSelection() || !this.allowSelection(event)) { return; } this.props.onRowClick && this.props.onRowClick(event); if (this.allowRowSelection()) { if (this.allowRangeSelection(event)) { this.onRangeSelection(event); } else { var toggleable = this.isRadioSelectionModeInColumn() || this.isCheckboxSelectionModeInColumn() || this.allowMetaKeySelection(event); this.anchorRowIndex = event.index; this.rangeRowIndex = event.index; this.anchorRowFirst = this.props.first; if (this.isSingleSelection()) { this.onSingleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: toggleable, type: 'row' })); } else { this.onMultipleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: toggleable, type: 'row' })); } } } else { this.focusOnElement(event.originalEvent); } this.rowTouched = false; } }, { key: "onRowDoubleClick", value: function onRowDoubleClick(e) { var event = e.originalEvent; if (DomHandler.isClickable(event.target)) { return; } if (this.props.onRowDoubleClick) { this.props.onRowDoubleClick(e); } } }, { key: "onRowRightClick", value: function onRowRightClick(event) { if (this.props.onContextMenu || this.props.onContextMenuSelectionChange) { DomHandler.clearSelection(); if (this.props.onContextMenuSelectionChange) { this.props.onContextMenuSelectionChange({ originalEvent: event.originalEvent, value: event.data }); } if (this.props.onContextMenu) { this.props.onContextMenu({ originalEvent: event.originalEvent, data: event.data }); } event.originalEvent.preventDefault(); } } }, { key: "onRowTouchEnd", value: function onRowTouchEnd() { this.rowTouched = true; } }, { key: "onRowMouseDown", value: function onRowMouseDown(e) { DomHandler.clearSelection(); var event = e.originalEvent; if (DomHandler.hasClass(event.target, 'p-datatable-reorderablerow-handle')) event.currentTarget.draggable = true;else event.currentTarget.draggable = false; if (this.allowRowDrag(e)) { this.enableDragSelection(event); this.anchorRowIndex = e.index; this.rangeRowIndex = e.index; this.anchorRowFirst = this.props.first; } } }, { key: "onRowMouseUp", value: function onRowMouseUp(event) { var isSameRow = event.index === this.anchorRowIndex; if (this.allowRowDrag(event) && !isSameRow) { this.onRangeSelection(event); } } }, { key: "onRowToggle", value: function onRowToggle(event) { var expandedRows; var dataKey = this.props.dataKey; var hasDataKey = this.props.groupRowsBy ? dataKey === this.props.groupRowsBy : !!dataKey; if (hasDataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(event.data, dataKey)); expandedRows = this.props.expandedRows ? _objectSpread$5({}, this.props.expandedRows) : {}; if (expandedRows[dataKeyValue] != null) { delete expandedRows[dataKeyValue]; if (this.props.onRowCollapse) { this.props.onRowCollapse({ originalEvent: event, data: event.data }); } } else { expandedRows[dataKeyValue] = true; if (this.props.onRowExpand) { this.props.onRowExpand({ originalEvent: event, data: event.data }); } } } else { var expandedRowIndex = this.findIndex(this.props.expandedRows, event.data); expandedRows = this.props.expandedRows ? _toConsumableArray(this.props.expandedRows) : []; if (expandedRowIndex !== -1) { expandedRows = expandedRows.filter(function (val, i) { return i !== expandedRowIndex; }); if (this.props.onRowCollapse) { this.props.onRowCollapse({ originalEvent: event, data: event.data }); } } else { expandedRows.push(event.data); if (this.props.onRowExpand) { this.props.onRowExpand({ originalEvent: event, data: event.data }); } } } if (this.props.onRowToggle) { this.props.onRowToggle({ data: expandedRows }); } } }, { key: "onRowDragStart", value: function onRowDragStart(e) { var event = e.originalEvent, index = e.index; this.rowDragging = true; this.draggedRowIndex = index; event.dataTransfer.setData('text', 'b'); // For firefox } }, { key: "onRowDragOver", value: function onRowDragOver(e) { var event = e.originalEvent, index = e.index; if (this.rowDragging && this.draggedRowIndex !== index) { var rowElement = event.currentTarget; var rowY = DomHandler.getOffset(rowElement).top + DomHandler.getWindowScrollTop(); var pageY = event.pageY; var rowMidY = rowY + DomHandler.getOuterHeight(rowElement) / 2; var prevRowElement = rowElement.previousElementSibling; if (pageY < rowMidY) { DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-bottom'); this.droppedRowIndex = index; if (prevRowElement) DomHandler.addClass(prevRowElement, 'p-datatable-dragpoint-bottom');else DomHandler.addClass(rowElement, 'p-datatable-dragpoint-top'); } else { if (prevRowElement) DomHandler.removeClass(prevRowElement, 'p-datatable-dragpoint-bottom');else DomHandler.addClass(rowElement, 'p-datatable-dragpoint-top'); this.droppedRowIndex = index + 1; DomHandler.addClass(rowElement, 'p-datatable-dragpoint-bottom'); } } event.preventDefault(); } }, { key: "onRowDragLeave", value: function onRowDragLeave(e) { var event = e.originalEvent; var rowElement = event.currentTarget; var prevRowElement = rowElement.previousElementSibling; if (prevRowElement) { DomHandler.removeClass(prevRowElement, 'p-datatable-dragpoint-bottom'); } DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-bottom'); DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-top'); } }, { key: "onRowDragEnd", value: function onRowDragEnd(e) { var event = e.originalEvent; this.rowDragging = false; this.draggedRowIndex = null; this.droppedRowIndex = null; event.currentTarget.draggable = false; } }, { key: "onRowDrop", value: function onRowDrop(e) { var event = e.originalEvent; if (this.droppedRowIndex != null) { var dropIndex = this.draggedRowIndex > this.droppedRowIndex ? this.droppedRowIndex : this.droppedRowIndex === 0 ? 0 : this.droppedRowIndex - 1; var val = _toConsumableArray(this.props.value); ObjectUtils.reorderArray(val, this.draggedRowIndex, dropIndex); if (this.props.onRowReorder) { this.props.onRowReorder({ originalEvent: event, value: val, dragIndex: this.draggedRowIndex, dropIndex: this.droppedRowIndex }); } } //cleanup this.onRowDragLeave(e); this.onRowDragEnd(e); event.preventDefault(); } }, { key: "onRadioChange", value: function onRadioChange(event) { this.onSingleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: true, type: 'radio' })); } }, { key: "onCheckboxChange", value: function onCheckboxChange(event) { this.onMultipleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: true, type: 'checkbox' })); } }, { key: "onDragSelectionMouseMove", value: function onDragSelectionMouseMove(event) { var _this$initialDragPosi = this.initialDragPosition, x = _this$initialDragPosi.x, y = _this$initialDragPosi.y; var dx = event.clientX - x; var dy = event.clientY - y; if (dy < 0) this.dragSelectionHelper.style.top = "".concat(event.pageY + 5, "px"); if (dx < 0) this.dragSelectionHelper.style.left = "".concat(event.pageX + 5, "px"); this.dragSelectionHelper.style.height = "".concat(Math.abs(dy), "px"); this.dragSelectionHelper.style.width = "".concat(Math.abs(dx), "px"); event.preventDefault(); } }, { key: "onDragSelectionMouseUp", value: function onDragSelectionMouseUp() { if (this.dragSelectionHelper) { this.dragSelectionHelper.remove(); this.dragSelectionHelper = null; } document.removeEventListener('mousemove', this.onDragSelectionMouseMove); document.removeEventListener('mouseup', this.onDragSelectionMouseUp); } }, { key: "onCellClick", value: function onCellClick(event) { if (!this.allowSelection(event)) { return; } this.props.onCellClick && this.props.onCellClick(event); if (this.allowCellSelection()) { if (this.allowRangeSelection(event)) { this.onRangeSelection(event); } else { var toggleable = this.allowMetaKeySelection(event); var originalEvent = event.originalEvent, data = _objectWithoutProperties(event, _excluded); this.anchorRowIndex = event.rowIndex; this.rangeRowIndex = event.rowIndex; this.anchorRowFirst = this.props.first; this.anchorCellIndex = event.cellIndex; if (this.isSingleSelection()) { this.onSingleSelection({ originalEvent: originalEvent, data: data, toggleable: toggleable, type: 'cell' }); } else { this.onMultipleSelection({ originalEvent: originalEvent, data: data, toggleable: toggleable, type: 'cell' }); } } } this.rowTouched = false; } }, { key: "onCellMouseDown", value: function onCellMouseDown(event) { if (this.allowCellDrag(event)) { this.enableDragSelection(event.originalEvent); this.anchorRowIndex = event.rowIndex; this.rangeRowIndex = event.rowIndex; this.anchorRowFirst = this.props.first; this.anchorCellIndex = event.cellIndex; } } }, { key: "onCellMouseUp", value: function onCellMouseUp(event) { var isSameCell = event.rowIndex === this.anchorRowIndex && event.cellIndex === this.anchorCellIndex; if (this.allowCellDrag(event) && !isSameCell) { this.onRangeSelection(event); } } }, { key: "bindDragSelectionEvents", value: function bindDragSelectionEvents() { document.addEventListener('mousemove', this.onDragSelectionMouseMove); document.addEventListener('mouseup', this.onDragSelectionMouseUp); document.body.appendChild(this.dragSelectionHelper); } }, { key: "unbindDragSelectionEvents", value: function unbindDragSelectionEvents() { this.onDragSelectionMouseUp(); } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.frozenRow) { this.updateFrozenRowStickyPosition(); } if (this.props.scrollable && this.props.rowGroupMode === 'subheader') { this.updateFrozenRowGroupHeaderStickyPosition(); } if (!this.props.isVirtualScrollerDisabled && this.getVirtualScrollerOption('vertical')) { this.updateVirtualScrollerPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.props.frozenRow) { this.updateFrozenRowStickyPosition(); } if (this.props.scrollable && this.props.rowGroupMode === 'subheader') { this.updateFrozenRowGroupHeaderStickyPosition(); } if (!this.props.isVirtualScrollerDisabled && this.getVirtualScrollerOption('vertical') && this.getVirtualScrollerOption('itemSize', prevProps.virtualScrollerOptions) !== this.getVirtualScrollerOption('itemSize')) { this.updateVirtualScrollerPosition(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.props.dragSelection) { this.unbindDragSelectionEvents(); } } }, { key: "renderEmptyContent", value: function renderEmptyContent() { if (!this.props.loading) { var colSpan = this.getColumnsLength(); var content = ObjectUtils.getJSXElement(this.props.emptyMessage, { props: this.props, frozen: this.props.frozenRow }) || localeOption('emptyMessage'); return /*#__PURE__*/React.createElement("tr", { className: "p-datatable-emptymessage", role: "row" }, /*#__PURE__*/React.createElement("td", { colSpan: colSpan, role: "cell" }, content)); } return null; } }, { key: "renderGroupHeader", value: function renderGroupHeader(rowData, index, expanded, isSubheaderGrouping, colSpan) { if (isSubheaderGrouping && this.shouldRenderRowGroupHeader(this.props.value, rowData, index)) { var style = this.rowGroupHeaderStyle(); var toggler = this.props.expandableRowGroups && /*#__PURE__*/React.createElement(RowTogglerButton, { onClick: this.onRowToggle, rowData: rowData, expanded: expanded, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon }); var content = ObjectUtils.getJSXElement(this.props.rowGroupHeaderTemplate, rowData, { index: index, props: this.props.tableProps }); return /*#__PURE__*/React.createElement("tr", { className: "p-rowgroup-header", style: style, role: "row" }, /*#__PURE__*/React.createElement("td", { colSpan: colSpan }, toggler, /*#__PURE__*/React.createElement("span", { className: "p-rowgroup-header-name" }, content))); } return null; } }, { key: "renderRow", value: function renderRow(rowData, index, expanded) { if (!this.props.expandableRowGroups || expanded) { var selected = this.isSelectionEnabled() ? this.isSelected(rowData) : false; var contextMenuSelected = this.isContextMenuSelected(rowData); var allowRowSelection = this.allowRowSelection(); var allowCellSelection = this.allowCellSelection(); var editing = this.isRowEditing(rowData); return /*#__PURE__*/React.createElement(BodyRow, { tableProps: this.props.tableProps, tableSelector: this.props.tableSelector, value: this.props.value, columns: this.props.columns, rowData: rowData, index: index, selected: selected, contextMenuSelected: contextMenuSelected, onRowClick: this.onRowClick, onRowDoubleClick: this.onRowDoubleClick, onRowRightClick: this.onRowRightClick, tabIndex: this.props.tabIndex, onRowTouchEnd: this.onRowTouchEnd, onRowMouseDown: this.onRowMouseDown, onRowMouseUp: this.onRowMouseUp, onRowToggle: this.onRowToggle, onRowDragStart: this.onRowDragStart, onRowDragOver: this.onRowDragOver, onRowDragLeave: this.onRowDragLeave, onRowDragEnd: this.onRowDragEnd, onRowDrop: this.onRowDrop, onRadioChange: this.onRadioChange, onCheckboxChange: this.onCheckboxChange, onCellClick: this.onCellClick, onCellMouseDown: this.onCellMouseDown, onCellMouseUp: this.onCellMouseUp, editing: editing, editingRows: this.props.editingRows, editingMeta: this.props.editingMeta, editMode: this.props.editMode, onRowEditChange: this.props.onRowEditChange, onEditingMetaChange: this.props.onEditingMetaChange, groupRowsBy: this.props.groupRowsBy, compareSelectionBy: this.props.compareSelectionBy, dataKey: this.props.dataKey, rowGroupMode: this.props.rowGroupMode, onRowEditInit: this.props.onRowEditInit, rowEditValidator: this.props.rowEditValidator, onRowEditSave: this.props.onRowEditSave, onRowEditComplete: this.props.onRowEditComplete, onRowEditCancel: this.props.onRowEditCancel, selection: this.props.selection, allowRowSelection: allowRowSelection, allowCellSelection: allowCellSelection, selectOnEdit: this.props.selectOnEdit, selectionMode: this.props.selectionMode, selectionModeInColumn: this.props.selectionModeInColumn, cellClassName: this.props.cellClassName, responsiveLayout: this.props.responsiveLayout, frozenRow: this.props.frozenRow, showSelectionElement: this.props.showSelectionElement, showRowReorderElement: this.props.showRowReorderElement, expanded: expanded, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon, rowClassName: this.props.rowClassName, virtualScrollerOptions: this.props.virtualScrollerOptions }); } } }, { key: "renderExpansion", value: function renderExpansion(rowData, index, expanded, isSubheaderGrouping, colSpan) { if (expanded && !(isSubheaderGrouping && this.props.expandableRowGroups)) { var content = ObjectUtils.getJSXElement(this.props.rowExpansionTemplate, rowData, { index: index }); var id = "".concat(this.props.tableSelector, "_content_").concat(index, "_expanded"); return /*#__PURE__*/React.createElement("tr", { id: id, className: "p-datatable-row-expansion", role: "row" }, /*#__PURE__*/React.createElement("td", { role: "cell", colSpan: colSpan }, content)); } return null; } }, { key: "renderGroupFooter", value: function renderGroupFooter(rowData, index, expanded, isSubheaderGrouping, colSpan) { if (isSubheaderGrouping && this.shouldRenderRowGroupFooter(this.props.value, rowData, index, expanded)) { var content = ObjectUtils.getJSXElement(this.props.rowGroupFooterTemplate, rowData, { index: index, colSpan: colSpan, props: this.props.tableProps }); return /*#__PURE__*/React.createElement("tr", { className: "p-rowgroup-footer", role: "row" }, content); } return null; } }, { key: "renderContent", value: function renderContent() { var _this5 = this; return this.props.value.map(function (rowData, i) { var index = _this5.getVirtualScrollerOption('getItemOptions') ? _this5.getVirtualScrollerOption('getItemOptions')(i).index : _this5.props.first + i; var key = _this5.getRowKey(rowData, index); var expanded = _this5.isRowExpanded(rowData); var isSubheaderGrouping = _this5.isSubheaderGrouping(); var colSpan = _this5.getColumnsLength(); var groupHeader = _this5.renderGroupHeader(rowData, index, expanded, isSubheaderGrouping, colSpan); var row = _this5.renderRow(rowData, index, expanded); var expansion = _this5.renderExpansion(rowData, index, expanded, isSubheaderGrouping, colSpan); var groupFooter = _this5.renderGroupFooter(rowData, index, expanded, isSubheaderGrouping, colSpan); return /*#__PURE__*/React.createElement(React.Fragment, { key: key }, groupHeader, row, expansion, groupFooter); }); } }, { key: "render", value: function render() { var className = classNames('p-datatable-tbody', this.props.className); var content = this.props.empty ? this.renderEmptyContent() : this.renderContent(); return /*#__PURE__*/React.createElement("tbody", { ref: this.ref, className: className }, content); } }]); return TableBody; }(Component); function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var FooterCell = /*#__PURE__*/function (_Component) { _inherits(FooterCell, _Component); var _super = _createSuper$6(FooterCell); function FooterCell(props) { var _this; _classCallCheck(this, FooterCell); _this = _super.call(this, props); _this.state = { styleObject: {} }; return _this; } _createClass(FooterCell, [{ key: "getColumnProp", value: function getColumnProp(prop) { return this.props.column.props[prop]; } }, { key: "getStyle", value: function getStyle() { var footerStyle = this.getColumnProp('footerStyle'); var columnStyle = this.getColumnProp('style'); return this.getColumnProp('frozen') ? Object.assign({}, columnStyle, footerStyle, this.state.styleObject) : Object.assign({}, columnStyle, footerStyle); } }, { key: "updateStickyPosition", value: function updateStickyPosition() { if (this.getColumnProp('frozen')) { var styleObject = _objectSpread$4({}, this.state.styleObject); var align = this.getColumnProp('alignFrozen'); if (align === 'right') { var right = 0; var next = this.el.nextElementSibling; if (next) { right = DomHandler.getOuterWidth(next) + parseFloat(next.style.right || 0); } styleObject['right'] = right + 'px'; } else { var left = 0; var prev = this.el.previousElementSibling; if (prev) { left = DomHandler.getOuterWidth(prev) + parseFloat(prev.style.left || 0); } styleObject['left'] = left + 'px'; } this.setState({ styleObject: styleObject }); } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "render", value: function render() { var _this2 = this; var style = this.getStyle(); var className = classNames(this.getColumnProp('footerClassName'), this.getColumnProp('className'), { 'p-frozen-column': this.getColumnProp('frozen') }); var colSpan = this.getColumnProp('colSpan'); var rowSpan = this.getColumnProp('rowSpan'); var content = ObjectUtils.getJSXElement(this.getColumnProp('footer'), { props: this.props.tableProps }); return /*#__PURE__*/React.createElement("td", { ref: function ref(el) { return _this2.el = el; }, style: style, className: className, role: "cell", colSpan: colSpan, rowSpan: rowSpan }, content); } }]); return FooterCell; }(Component); function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TableFooter = /*#__PURE__*/function (_Component) { _inherits(TableFooter, _Component); var _super = _createSuper$5(TableFooter); function TableFooter() { _classCallCheck(this, TableFooter); return _super.apply(this, arguments); } _createClass(TableFooter, [{ key: "hasFooter", value: function hasFooter() { return this.props.footerColumnGroup ? true : this.props.columns ? this.props.columns.some(function (col) { return col && col.props.footer; }) : false; } }, { key: "renderGroupFooterCells", value: function renderGroupFooterCells(row) { var columns = React.Children.toArray(row.props.children); return this.renderFooterCells(columns); } }, { key: "renderFooterCells", value: function renderFooterCells(columns) { var _this = this; return React.Children.map(columns, function (col, i) { var isVisible = col ? !col.props.hidden : true; var key = col ? col.props.columnKey || col.props.field || i : i; return isVisible && /*#__PURE__*/React.createElement(FooterCell, { key: key, tableProps: _this.props.tableProps, column: col }); }); } }, { key: "renderContent", value: function renderContent() { var _this2 = this; if (this.props.footerColumnGroup) { var rows = React.Children.toArray(this.props.footerColumnGroup.props.children); return rows.map(function (row, i) { return /*#__PURE__*/React.createElement("tr", { key: i, role: "row" }, _this2.renderGroupFooterCells(row)); }); } return /*#__PURE__*/React.createElement("tr", { role: "row" }, this.renderFooterCells(this.props.columns)); } }, { key: "render", value: function render() { if (this.hasFooter()) { var content = this.renderContent(); return /*#__PURE__*/React.createElement("tfoot", { className: "p-datatable-tfoot" }, content); } return null; } }]); return TableFooter; }(Component); function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var HeaderCheckbox = /*#__PURE__*/function (_Component) { _inherits(HeaderCheckbox, _Component); var _super = _createSuper$4(HeaderCheckbox); function HeaderCheckbox(props) { var _this; _classCallCheck(this, HeaderCheckbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(HeaderCheckbox, [{ key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onClick", value: function onClick(event) { if (!this.props.disabled) { this.setState({ focused: true }); this.props.onChange({ originalEvent: event, checked: this.props.checked }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var boxClassName = classNames('p-checkbox-box p-component', { 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClassName = classNames('p-checkbox-icon', { 'pi pi-check': this.props.checked }); var tabIndex = this.props.disabled ? null : 0; return /*#__PURE__*/React.createElement("div", { className: "p-checkbox p-component", onClick: this.onClick }, /*#__PURE__*/React.createElement("div", { className: boxClassName, role: "checkbox", "aria-checked": this.props.checked, tabIndex: tabIndex, onFocus: this.onFocus, onBlur: this.onBlur, onKeyDown: this.onKeyDown }, /*#__PURE__*/React.createElement("span", { className: iconClassName }))); } }]); return HeaderCheckbox; }(Component); var FilterMatchMode = Object.freeze({ STARTS_WITH: 'startsWith', CONTAINS: 'contains', NOT_CONTAINS: 'notContains', ENDS_WITH: 'endsWith', EQUALS: 'equals', NOT_EQUALS: 'notEquals', IN: 'in', LESS_THAN: 'lt', LESS_THAN_OR_EQUAL_TO: 'lte', GREATER_THAN: 'gt', GREATER_THAN_OR_EQUAL_TO: 'gte', BETWEEN: 'between', DATE_IS: 'dateIs', DATE_IS_NOT: 'dateIsNot', DATE_BEFORE: 'dateBefore', DATE_AFTER: 'dateAfter', CUSTOM: 'custom' }); function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ColumnFilter = /*#__PURE__*/function (_Component) { _inherits(ColumnFilter, _Component); var _super = _createSuper$3(ColumnFilter); function ColumnFilter(props) { var _this; _classCallCheck(this, ColumnFilter); _this = _super.call(this, props); _this.state = { overlayVisible: false }; _this.overlayRef = /*#__PURE__*/React.createRef(); _this.filterCallback = _this.filterCallback.bind(_assertThisInitialized(_this)); _this.filterApplyCallback = _this.filterApplyCallback.bind(_assertThisInitialized(_this)); _this.onOperatorChange = _this.onOperatorChange.bind(_assertThisInitialized(_this)); _this.addConstraint = _this.addConstraint.bind(_assertThisInitialized(_this)); _this.clearFilter = _this.clearFilter.bind(_assertThisInitialized(_this)); _this.applyFilter = _this.applyFilter.bind(_assertThisInitialized(_this)); _this.onInputChange = _this.onInputChange.bind(_assertThisInitialized(_this)); _this.toggleMenu = _this.toggleMenu.bind(_assertThisInitialized(_this)); _this.onOverlayEnter = _this.onOverlayEnter.bind(_assertThisInitialized(_this)); _this.onOverlayExit = _this.onOverlayExit.bind(_assertThisInitialized(_this)); _this.onOverlayExited = _this.onOverlayExited.bind(_assertThisInitialized(_this)); _this.onContentKeyDown = _this.onContentKeyDown.bind(_assertThisInitialized(_this)); _this.onContentClick = _this.onContentClick.bind(_assertThisInitialized(_this)); _this.onContentMouseDown = _this.onContentMouseDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(ColumnFilter, [{ key: "field", get: function get() { return this.getColumnProp('filterField') || this.getColumnProp('field'); } }, { key: "overlay", get: function get() { return this.overlayRef ? this.overlayRef.current : null; } }, { key: "filterModel", get: function get() { return this.props.filters[this.field]; } }, { key: "filterStoreModel", get: function get() { return this.props.filtersStore[this.field]; } }, { key: "hasFilter", value: function hasFilter() { if (this.props.filtersStore) { var fieldFilter = this.props.filtersStore[this.field]; return fieldFilter && (fieldFilter.operator ? !this.isFilterBlank(fieldFilter.constraints[0].value) : !this.isFilterBlank(fieldFilter.value)); } return false; } }, { key: "hasRowFilter", value: function hasRowFilter() { return this.filterModel && !this.isFilterBlank(this.filterModel.value); } }, { key: "isFilterBlank", value: function isFilterBlank(filter) { return ObjectUtils.isEmpty(filter); } }, { key: "isRowMatchModeSelected", value: function isRowMatchModeSelected(matchMode) { return this.filterModel.matchMode === matchMode; } }, { key: "showMenuButton", value: function showMenuButton() { return this.getColumnProp('showFilterMenu') && (this.props.display === 'row' ? this.getColumnProp('dataType') !== 'boolean' : true); } }, { key: "matchModes", value: function matchModes() { return this.getColumnProp('filterMatchModeOptions') || PrimeReact.filterMatchModeOptions[this.findDataType()].map(function (key) { return { label: localeOption(key), value: key }; }); } }, { key: "isShowMatchModes", value: function isShowMatchModes() { return this.getColumnProp('dataType') !== 'boolean' && this.getColumnProp('showFilterMatchModes') && this.matchModes() && this.getColumnProp('showFilterMenuOptions'); } }, { key: "isShowOperator", value: function isShowOperator() { return this.getColumnProp('showFilterOperator') && this.filterModel && this.filterModel.operator && this.getColumnProp('showFilterMenuOptions'); } }, { key: "showRemoveIcon", value: function showRemoveIcon() { return this.fieldConstraints().length > 1; } }, { key: "isShowAddConstraint", value: function isShowAddConstraint() { return this.getColumnProp('showAddButton') && this.filterModel && this.filterModel.operator && this.fieldConstraints() && this.fieldConstraints().length < this.getColumnProp('maxConstraints') && this.getColumnProp('showFilterMenuOptions'); } }, { key: "isOutsideClicked", value: function isOutsideClicked(target) { return !this.isTargetClicked(target) && this.overlayRef && this.overlayRef.current && !(this.overlayRef.current.isSameNode(target) || this.overlayRef.current.contains(target)); } }, { key: "isTargetClicked", value: function isTargetClicked(target) { return this.icon && (this.icon.isSameNode(target) || this.icon.contains(target)); } }, { key: "getColumnProp", value: function getColumnProp(prop) { return this.props.column.props[prop]; } }, { key: "getDefaultConstraint", value: function getDefaultConstraint() { if (this.props.filtersStore && this.filterStoreModel) { if (this.filterStoreModel.operator) { return { matchMode: this.filterStoreModel.constraints[0].matchMode, operator: this.filterStoreModel.operator }; } else { return { matchMode: this.filterStoreModel.matchMode }; } } } }, { key: "findDataType", value: function findDataType() { var dataType = this.getColumnProp('dataType'); var matchMode = this.getColumnProp('filterMatchMode'); var hasMatchMode = function hasMatchMode(key) { return PrimeReact.filterMatchModeOptions[key].some(function (mode) { return mode === matchMode; }); }; if (matchMode === 'custom' && !hasMatchMode(dataType)) { PrimeReact.filterMatchModeOptions[dataType].push(FilterMatchMode.CUSTOM); return dataType; } else if (matchMode) { return Object.keys(PrimeReact.filterMatchModeOptions).find(function (key) { return hasMatchMode(key); }) || dataType; } return dataType; } }, { key: "clearFilter", value: function clearFilter() { var field = this.field; var filterClearCallback = this.getColumnProp('onFilterClear'); var defaultConstraint = this.getDefaultConstraint(); var filters = _objectSpread$3({}, this.props.filters); if (filters[field].operator) { filters[field].constraints.splice(1); filters[field].operator = defaultConstraint.operator; filters[field].constraints[0] = { value: null, matchMode: defaultConstraint.matchMode }; } else { filters[field].value = null; filters[field].matchMode = defaultConstraint.matchMode; } filterClearCallback && filterClearCallback(); this.props.onFilterChange(filters); this.props.onFilterApply(); this.hide(); } }, { key: "applyFilter", value: function applyFilter() { var filterApplyClickCallback = this.getColumnProp('onFilterApplyClick'); filterApplyClickCallback && filterApplyClickCallback({ field: this.field, constraints: this.filterModel }); this.props.onFilterApply(); this.hide(); } }, { key: "toggleMenu", value: function toggleMenu() { this.setState(function (prevState) { return { overlayVisible: !prevState.overlayVisible }; }); } }, { key: "onToggleButtonKeyDown", value: function onToggleButtonKeyDown(event) { switch (event.key) { case 'Escape': case 'Tab': this.hide(); break; case 'ArrowDown': if (this.state.overlayVisible) { var focusable = DomHandler.getFirstFocusableElement(this.overlay); focusable && focusable.focus(); event.preventDefault(); } else if (event.altKey) { this.setState({ overlayVisible: true }); event.preventDefault(); } break; } } }, { key: "onContentKeyDown", value: function onContentKeyDown(event) { if (event.key === 'Escape') { this.hide(); this.icon && this.icon.focus(); } } }, { key: "onInputChange", value: function onInputChange(event, index) { var filters = _objectSpread$3({}, this.props.filters); var value = event.target.value; if (this.props.display === 'menu') { filters[this.field].constraints[index].value = value; } else { filters[this.field].value = value; } this.props.onFilterChange(filters); if (!this.getColumnProp('showApplyButton') || this.props.display === 'row') { this.props.onFilterApply(); } } }, { key: "onRowMatchModeChange", value: function onRowMatchModeChange(matchMode) { var filterMatchModeChangeCallback = this.getColumnProp('onFilterMatchModeChange'); var filters = _objectSpread$3({}, this.props.filters); filters[this.field].matchMode = matchMode; filterMatchModeChangeCallback && filterMatchModeChangeCallback({ field: this.field, matchMode: matchMode }); this.props.onFilterChange(filters); this.props.onFilterApply(); this.hide(); } }, { key: "onRowMatchModeKeyDown", value: function onRowMatchModeKeyDown(event, matchMode, clear) { var item = event.target; switch (event.key) { case 'ArrowDown': var nextItem = this.findNextItem(item); if (nextItem) { item.removeAttribute('tabindex'); nextItem.tabIndex = 0; nextItem.focus(); } event.preventDefault(); break; case 'ArrowUp': var prevItem = this.findPrevItem(item); if (prevItem) { item.removeAttribute('tabindex'); prevItem.tabIndex = 0; prevItem.focus(); } event.preventDefault(); break; case 'Enter': clear ? this.clearFilter() : this.onRowMatchModeChange(matchMode.value); event.preventDefault(); break; } } }, { key: "onOperatorChange", value: function onOperatorChange(e) { var filterOperationChangeCallback = this.getColumnProp('onFilterOperatorChange'); var value = e.value; var filters = _objectSpread$3({}, this.props.filters); filters[this.field].operator = value; this.props.onFilterChange(filters); filterOperationChangeCallback && filterOperationChangeCallback({ field: this.field, operator: value }); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "onMenuMatchModeChange", value: function onMenuMatchModeChange(value, index) { var filterMatchModeChangeCallback = this.getColumnProp('onFilterMatchModeChange'); var filters = _objectSpread$3({}, this.props.filters); filters[this.field].constraints[index].matchMode = value; this.props.onFilterChange(filters); filterMatchModeChangeCallback && filterMatchModeChangeCallback({ field: this.field, matchMode: value, index: index }); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "addConstraint", value: function addConstraint() { var filterConstraintAddCallback = this.getColumnProp('onFilterConstraintAdd'); var defaultConstraint = this.getDefaultConstraint(); var filters = _objectSpread$3({}, this.props.filters); var newConstraint = { value: null, matchMode: defaultConstraint.matchMode }; filters[this.field].constraints.push(newConstraint); filterConstraintAddCallback && filterConstraintAddCallback({ field: this.field, constraing: newConstraint }); this.props.onFilterChange(filters); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "removeConstraint", value: function removeConstraint(index) { var filterConstraintRemoveCallback = this.getColumnProp('onFilterConstraintRemove'); var filters = _objectSpread$3({}, this.props.filters); var removedConstraint = filters[this.field].constraints.splice(index, 1); filterConstraintRemoveCallback && filterConstraintRemoveCallback({ field: this.field, constraing: removedConstraint }); this.props.onFilterChange(filters); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return DomHandler.hasClass(nextItem, 'p-column-filter-separator') ? this.findNextItem(nextItem) : nextItem;else return item.parentElement.firstElementChild; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return DomHandler.hasClass(prevItem, 'p-column-filter-separator') ? this.findPrevItem(prevItem) : prevItem;else return item.parentElement.lastElementChild; } }, { key: "hide", value: function hide() { this.setState({ overlayVisible: false }); } }, { key: "onContentClick", value: function onContentClick(event) { this.selfClick = true; OverlayService.emit('overlay-click', { originalEvent: event, target: this.overlay }); } }, { key: "onContentMouseDown", value: function onContentMouseDown() { this.selfClick = true; } }, { key: "onOverlayEnter", value: function onOverlayEnter() { var _this2 = this; ZIndexUtils.set('overlay', this.overlay, PrimeReact.autoZIndex, PrimeReact.zIndex['overlay']); DomHandler.alignOverlay(this.overlay, this.icon, PrimeReact.appendTo, false); this.bindOutsideClickListener(); this.bindScrollListener(); this.bindResizeListener(); this.overlayEventListener = function (e) { if (!_this2.isOutsideClicked(e.target)) { _this2.selfClick = true; } }; OverlayService.on('overlay-click', this.overlayEventListener); } }, { key: "onOverlayExit", value: function onOverlayExit() { this.onOverlayHide(); } }, { key: "onOverlayExited", value: function onOverlayExited() { ZIndexUtils.clear(this.overlay); } }, { key: "onOverlayHide", value: function onOverlayHide() { this.unbindOutsideClickListener(); this.unbindResizeListener(); this.unbindScrollListener(); OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } }, { key: "bindOutsideClickListener", value: function bindOutsideClickListener() { var _this3 = this; if (!this.outsideClickListener) { this.outsideClickListener = function (event) { if (!_this3.selfClick && _this3.isOutsideClicked(event.target)) { _this3.hide(); } _this3.selfClick = false; }; document.addEventListener('click', this.outsideClickListener); } } }, { key: "unbindOutsideClickListener", value: function unbindOutsideClickListener() { if (this.outsideClickListener) { document.removeEventListener('click', this.outsideClickListener); this.outsideClickListener = null; this.selfClick = false; } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this4 = this; if (!this.scrollHandler) { this.scrollHandler = new ConnectedOverlayScrollHandler(this.icon, function () { if (_this4.state.overlayVisible) { _this4.hide(); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindResizeListener", value: function bindResizeListener() { var _this5 = this; if (!this.resizeListener) { this.resizeListener = function () { if (_this5.state.overlayVisible) { _this5.hide(); } }; window.addEventListener('resize', this.resizeListener); } } }, { key: "unbindResizeListener", value: function unbindResizeListener() { if (this.resizeListener) { window.removeEventListener('resize', this.resizeListener); this.resizeListener = null; } } }, { key: "fieldConstraints", value: function fieldConstraints() { return this.filterModel ? this.filterModel.constraints || [this.filterModel] : []; } }, { key: "operator", value: function operator() { return this.filterModel.operator; } }, { key: "operatorOptions", value: function operatorOptions() { return [{ label: localeOption('matchAll'), value: FilterOperator.AND }, { label: localeOption('matchAny'), value: FilterOperator.OR }]; } }, { key: "noFilterLabel", value: function noFilterLabel() { return localeOption('noFilter'); } }, { key: "removeRuleButtonLabel", value: function removeRuleButtonLabel() { return localeOption('removeRule'); } }, { key: "addRuleButtonLabel", value: function addRuleButtonLabel() { return localeOption('addRule'); } }, { key: "clearButtonLabel", value: function clearButtonLabel() { return localeOption('clear'); } }, { key: "applyButtonLabel", value: function applyButtonLabel() { return localeOption('apply'); } }, { key: "filterCallback", value: function filterCallback(value) { var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var filters = _objectSpread$3({}, this.props.filters); var meta = filters[this.field]; this.props.display === 'menu' && meta && meta.operator ? filters[this.field].constraints[index].value = value : filters[this.field].value = value; this.props.onFilterChange(filters); } }, { key: "filterApplyCallback", value: function filterApplyCallback() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args && this.filterCallback(args[0], args[1]); this.props.onFilterApply(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.props.display === 'menu' && this.state.overlayVisible) { DomHandler.alignOverlay(this.overlay, this.icon, PrimeReact.appendTo, false); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.overlayEventListener) { OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } if (this.overlay) { ZIndexUtils.clear(this.overlay); this.onOverlayHide(); } } }, { key: "renderFilterElement", value: function renderFilterElement(model, index) { var _this6 = this; return this.getColumnProp('filterElement') ? ObjectUtils.getJSXElement(this.getColumnProp('filterElement'), { field: this.field, index: index, filterModel: model, value: model.value, filterApplyCallback: this.filterApplyCallback, filterCallback: this.filterCallback }) : /*#__PURE__*/React.createElement(InputText, { type: this.getColumnProp('filterType'), value: model.value || '', onChange: function onChange(e) { return _this6.onInputChange(e, index); }, className: "p-column-filter", placeholder: this.getColumnProp('filterPlaceholder'), maxLength: this.getColumnProp('filterMaxLength') }); } }, { key: "renderRowFilterElement", value: function renderRowFilterElement() { if (this.props.display === 'row') { var content = this.renderFilterElement(this.filterModel, 0); return /*#__PURE__*/React.createElement("div", { className: "p-fluid p-column-filter-element" }, content); } return null; } }, { key: "renderMenuFilterElement", value: function renderMenuFilterElement(fieldConstraint, index) { if (this.props.display === 'menu') { return this.renderFilterElement(fieldConstraint, index); } return null; } }, { key: "renderMenuButton", value: function renderMenuButton() { var _this7 = this; if (this.showMenuButton()) { var className = classNames('p-column-filter-menu-button p-link', { 'p-column-filter-menu-button-open': this.state.overlayVisible, 'p-column-filter-menu-button-active': this.hasFilter() }); return /*#__PURE__*/React.createElement("button", { ref: function ref(el) { return _this7.icon = el; }, type: "button", className: className, "aria-haspopup": true, "aria-expanded": this.state.overlayVisible, onClick: this.toggleMenu, onKeyDown: this.onToggleButtonKeyDown }, /*#__PURE__*/React.createElement("span", { className: "pi pi-filter-icon pi-filter" })); } return null; } }, { key: "renderClearButton", value: function renderClearButton() { if (this.getColumnProp('showClearButton') && this.props.display === 'row') { var className = classNames('p-column-filter-clear-button p-link', { 'p-hidden-space': !this.hasRowFilter() }); return /*#__PURE__*/React.createElement("button", { className: className, type: "button", onClick: this.clearFilter }, /*#__PURE__*/React.createElement("span", { className: "pi pi-filter-slash" })); } return null; } }, { key: "renderRowItems", value: function renderRowItems() { var _this8 = this; if (this.isShowMatchModes()) { var matchModes = this.matchModes(); var noFilterLabel = this.noFilterLabel(); return /*#__PURE__*/React.createElement("ul", { className: "p-column-filter-row-items" }, matchModes.map(function (matchMode, i) { var value = matchMode.value, label = matchMode.label; var className = classNames('p-column-filter-row-item', { 'p-highlight': _this8.isRowMatchModeSelected(value) }); var tabIndex = i === 0 ? 0 : null; return /*#__PURE__*/React.createElement("li", { className: className, key: label, onClick: function onClick() { return _this8.onRowMatchModeChange(value); }, onKeyDown: function onKeyDown(e) { return _this8.onRowMatchModeKeyDown(e, matchMode); }, tabIndex: tabIndex }, label); }), /*#__PURE__*/React.createElement("li", { className: "p-column-filter-separator" }), /*#__PURE__*/React.createElement("li", { className: "p-column-filter-row-item", onClick: this.clearFilter, onKeyDown: function onKeyDown(e) { return _this8.onRowMatchModeKeyDown(e, null, true); } }, noFilterLabel)); } return null; } }, { key: "renderOperator", value: function renderOperator() { if (this.isShowOperator()) { var options = this.operatorOptions(); var value = this.operator(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-operator" }, /*#__PURE__*/React.createElement(Dropdown, { options: options, value: value, onChange: this.onOperatorChange, className: "p-column-filter-operator-dropdown" })); } return null; } }, { key: "renderMatchModeDropdown", value: function renderMatchModeDropdown(constraint, index) { var _this9 = this; if (this.isShowMatchModes()) { var options = this.matchModes(); return /*#__PURE__*/React.createElement(Dropdown, { options: options, value: constraint.matchMode, onChange: function onChange(e) { return _this9.onMenuMatchModeChange(e.value, index); }, className: "p-column-filter-matchmode-dropdown" }); } return null; } }, { key: "renderRemoveButton", value: function renderRemoveButton(index) { var _this10 = this; if (this.showRemoveIcon()) { var removeRuleLabel = this.removeRuleButtonLabel(); return /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-trash", className: "p-column-filter-remove-button p-button-text p-button-danger p-button-sm", onClick: function onClick() { return _this10.removeConstraint(index); }, label: removeRuleLabel }); } return null; } }, { key: "renderConstraints", value: function renderConstraints() { var _this11 = this; var fieldConstraints = this.fieldConstraints(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-constraints" }, fieldConstraints.map(function (fieldConstraint, i) { var matchModeDropdown = _this11.renderMatchModeDropdown(fieldConstraint, i); var menuFilterElement = _this11.renderMenuFilterElement(fieldConstraint, i); var removeButton = _this11.renderRemoveButton(i); return /*#__PURE__*/React.createElement("div", { key: i, className: "p-column-filter-constraint" }, matchModeDropdown, menuFilterElement, /*#__PURE__*/React.createElement("div", null, removeButton)); })); } }, { key: "renderAddRule", value: function renderAddRule() { if (this.isShowAddConstraint()) { var addRuleLabel = this.addRuleButtonLabel(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-add-rule" }, /*#__PURE__*/React.createElement(Button, { type: "button", label: addRuleLabel, icon: "pi pi-plus", className: "p-column-filter-add-button p-button-text p-button-sm", onClick: this.addConstraint })); } return null; } }, { key: "renderFilterClearButton", value: function renderFilterClearButton() { if (this.getColumnProp('showClearButton')) { if (!this.getColumnProp('filterClear')) { var clearLabel = this.clearButtonLabel(); return /*#__PURE__*/React.createElement(Button, { type: "button", className: "p-button-outlined p-button-sm", onClick: this.clearFilter, label: clearLabel }); } return ObjectUtils.getJSXElement(this.getColumnProp('filterClear'), { field: this.field, filterModel: this.filterModel, filterClearCallback: this.clearFilter }); } return null; } }, { key: "renderFilterApplyButton", value: function renderFilterApplyButton() { if (this.getColumnProp('showApplyButton')) { if (!this.getColumnProp('filterApply')) { var applyLabel = this.applyButtonLabel(); return /*#__PURE__*/React.createElement(Button, { type: "button", className: "p-button-sm", onClick: this.applyFilter, label: applyLabel }); } return ObjectUtils.getJSXElement(this.getColumnProp('filterApply'), { field: this.field, filterModel: this.filterModel, filterApplyCallback: this.applyFilter }); } return null; } }, { key: "renderButtonBar", value: function renderButtonBar() { var clearButton = this.renderFilterClearButton(); var applyButton = this.renderFilterApplyButton(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-buttonbar" }, clearButton, applyButton); } }, { key: "renderItems", value: function renderItems() { var operator = this.renderOperator(); var constraints = this.renderConstraints(); var addRule = this.renderAddRule(); var buttonBar = this.renderButtonBar(); return /*#__PURE__*/React.createElement(React.Fragment, null, operator, constraints, addRule, buttonBar); } }, { key: "renderOverlay", value: function renderOverlay() { var style = this.getColumnProp('filterMenuStyle'); var className = classNames('p-column-filter-overlay p-component p-fluid', this.getColumnProp('filterMenuClassName'), { 'p-column-filter-overlay-menu': this.props.display === 'menu', 'p-input-filled': PrimeReact.inputStyle === 'filled', 'p-ripple-disabled': PrimeReact.ripple === false }); var filterHeader = ObjectUtils.getJSXElement(this.getColumnProp('filterHeader'), { field: this.field, filterModel: this.filterModel, filterApplyCallback: this.filterApplyCallback }); var filterFooter = ObjectUtils.getJSXElement(this.getColumnProp('filterFooter'), { field: this.field, filterModel: this.filterModel, filterApplyCallback: this.filterApplyCallback }); var items = this.props.display === 'row' ? this.renderRowItems() : this.renderItems(); return /*#__PURE__*/React.createElement(Portal, null, /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.overlayRef, classNames: "p-connected-overlay", in: this.state.overlayVisible, timeout: { enter: 120, exit: 100 }, unmountOnExit: true, onEnter: this.onOverlayEnter, onExit: this.onOverlayExit, onExited: this.onOverlayExited }, /*#__PURE__*/React.createElement("div", { ref: this.overlayRef, style: style, className: className, onKeyDown: this.onContentKeyDown, onClick: this.onContentClick, onMouseDown: this.onContentMouseDown }, filterHeader, items, filterFooter))); } }, { key: "render", value: function render() { var className = classNames('p-column-filter p-fluid', { 'p-column-filter-row': this.props.display === 'row', 'p-column-filter-menu': this.props.display === 'menu' }); var rowFilterElement = this.renderRowFilterElement(); var menuButton = this.renderMenuButton(); var clearButton = this.renderClearButton(); var overlay = this.renderOverlay(); return /*#__PURE__*/React.createElement("div", { className: className }, rowFilterElement, menuButton, clearButton, overlay); } }]); return ColumnFilter; }(Component); function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var HeaderCell = /*#__PURE__*/function (_Component) { _inherits(HeaderCell, _Component); var _super = _createSuper$2(HeaderCell); function HeaderCell(props) { var _this; _classCallCheck(this, HeaderCell); _this = _super.call(this, props); _this.state = { styleObject: {} }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); // drag _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); // resize _this.onResizerMouseDown = _this.onResizerMouseDown.bind(_assertThisInitialized(_this)); _this.onResizerClick = _this.onResizerClick.bind(_assertThisInitialized(_this)); _this.onResizerDoubleClick = _this.onResizerDoubleClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(HeaderCell, [{ key: "isBadgeVisible", value: function isBadgeVisible() { return this.props.multiSortMeta && this.props.multiSortMeta.length > 1; } }, { key: "isSortableDisabled", value: function isSortableDisabled() { return !this.getColumnProp('sortable') || this.getColumnProp('sortable') && (this.props.allSortableDisabled || this.getColumnProp('sortableDisabled')); } }, { key: "getColumnProp", value: function getColumnProp() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return this.props.column ? typeof args[0] === 'string' ? this.props.column.props[args[0]] : (args[0] || this.props.column).props[args[1]] : null; } }, { key: "getStyle", value: function getStyle() { var headerStyle = this.getColumnProp('headerStyle'); var columnStyle = this.getColumnProp('style'); return this.getColumnProp('frozen') ? Object.assign({}, columnStyle, headerStyle, this.state.styleObject) : Object.assign({}, columnStyle, headerStyle); } }, { key: "getMultiSortMetaIndex", value: function getMultiSortMetaIndex() { var _this2 = this; return this.props.multiSortMeta.findIndex(function (meta) { return meta.field === _this2.getColumnProp('field') || meta.field === _this2.getColumnProp('sortField'); }); } }, { key: "getSortMeta", value: function getSortMeta() { var sorted = false; var sortOrder = 0; var metaIndex = -1; if (this.props.sortMode === 'single') { sorted = this.props.sortField && (this.props.sortField === this.getColumnProp('field') || this.props.sortField === this.getColumnProp('sortField')); sortOrder = sorted ? this.props.sortOrder : 0; } else if (this.props.sortMode === 'multiple') { metaIndex = this.getMultiSortMetaIndex(); if (metaIndex > -1) { sorted = true; sortOrder = this.props.multiSortMeta[metaIndex].order; } } return { sorted: sorted, sortOrder: sortOrder, metaIndex: metaIndex }; } }, { key: "getAriaSort", value: function getAriaSort(_ref) { var sorted = _ref.sorted, sortOrder = _ref.sortOrder; if (this.getColumnProp('sortable')) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-amount-down' : 'pi-sort-amount-up-alt' : 'pi-sort-alt'; if (sortIcon === 'pi-sort-amount-down') return 'descending';else if (sortIcon === 'pi-sort-amount-up-alt') return 'ascending';else return 'none'; } return null; } }, { key: "updateStickyPosition", value: function updateStickyPosition() { if (this.getColumnProp('frozen')) { var styleObject = _objectSpread$2({}, this.state.styleObject); var align = this.getColumnProp('alignFrozen'); if (align === 'right') { var right = 0; var next = this.el.nextElementSibling; if (next) { right = DomHandler.getOuterWidth(next) + parseFloat(next.style.right || 0); } styleObject['right'] = right + 'px'; } else { var left = 0; var prev = this.el.previousElementSibling; if (prev) { left = DomHandler.getOuterWidth(prev) + parseFloat(prev.style.left || 0); } styleObject['left'] = left + 'px'; } var filterRow = this.el.parentElement.nextElementSibling; if (filterRow) { var index = DomHandler.index(this.el); filterRow.children[index].style.left = styleObject['left']; filterRow.children[index].style.right = styleObject['right']; } var isSameStyle = this.state.styleObject['left'] === styleObject['left'] && this.state.styleObject['right'] === styleObject['right']; !isSameStyle && this.setState({ styleObject: styleObject }); } } }, { key: "updateSortableDisabled", value: function updateSortableDisabled(prevColumn) { if (this.getColumnProp(prevColumn, 'sortableDisabled') !== this.getColumnProp('sortableDisabled') || this.getColumnProp(prevColumn, 'sortable') !== this.getColumnProp('sortable')) { this.props.onSortableChange(); } } }, { key: "onClick", value: function onClick(event) { if (!this.isSortableDisabled()) { var targetNode = event.target; if (DomHandler.hasClass(targetNode, 'p-sortable-column') || DomHandler.hasClass(targetNode, 'p-column-title') || DomHandler.hasClass(targetNode, 'p-column-header-content') || DomHandler.hasClass(targetNode, 'p-sortable-column-icon') || DomHandler.hasClass(targetNode.parentElement, 'p-sortable-column-icon')) { DomHandler.clearSelection(); this.props.onSortChange({ originalEvent: event, column: this.props.column, sortableDisabledFields: this.props.sortableDisabledFields }); } } } }, { key: "onMouseDown", value: function onMouseDown(event) { this.props.onColumnMouseDown({ originalEvent: event, column: this.props.column }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter' && event.currentTarget === this.el && DomHandler.hasClass(event.currentTarget, 'p-sortable-column')) { this.onClick(event); event.preventDefault(); } } }, { key: "onDragStart", value: function onDragStart(event) { this.props.onColumnDragStart({ originalEvent: event, column: this.props.column }); } }, { key: "onDragOver", value: function onDragOver(event) { this.props.onColumnDragOver({ originalEvent: event, column: this.props.column }); } }, { key: "onDragLeave", value: function onDragLeave(event) { this.props.onColumnDragLeave({ originalEvent: event, column: this.props.column }); } }, { key: "onDrop", value: function onDrop(event) { this.props.onColumnDrop({ originalEvent: event, column: this.props.column }); } }, { key: "onResizerMouseDown", value: function onResizerMouseDown(event) { this.props.onColumnResizeStart({ originalEvent: event, column: this.props.column }); } }, { key: "onResizerClick", value: function onResizerClick(event) { if (this.props.onColumnResizerClick) { this.props.onColumnResizerClick({ originalEvent: event, element: event.currentTarget.parentElement, column: this.props.column }); event.preventDefault(); } } }, { key: "onResizerDoubleClick", value: function onResizerDoubleClick(event) { if (this.props.onColumnResizerDoubleClick) { this.props.onColumnResizerDoubleClick({ originalEvent: event, element: event.currentTarget.parentElement, column: this.props.column }); event.preventDefault(); } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } this.updateSortableDisabled(prevProps.column); } }, { key: "renderResizer", value: function renderResizer() { if (this.props.resizableColumns && !this.getColumnProp('frozen')) { return /*#__PURE__*/React.createElement("span", { className: "p-column-resizer", onMouseDown: this.onResizerMouseDown, onClick: this.onResizerClick, onDoubleClick: this.onResizerDoubleClick }); } return null; } }, { key: "renderTitle", value: function renderTitle() { var title = ObjectUtils.getJSXElement(this.getColumnProp('header'), { props: this.props.tableProps }); return /*#__PURE__*/React.createElement("span", { className: "p-column-title" }, title); } }, { key: "renderSortIcon", value: function renderSortIcon(_ref2) { var sorted = _ref2.sorted, sortOrder = _ref2.sortOrder; if (this.getColumnProp('sortable')) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-amount-down' : 'pi-sort-amount-up-alt' : 'pi-sort-alt'; var className = classNames('p-sortable-column-icon pi pi-fw', sortIcon); return /*#__PURE__*/React.createElement("span", { className: className }); } return null; } }, { key: "renderBadge", value: function renderBadge(_ref3) { var metaIndex = _ref3.metaIndex; if (metaIndex !== -1 && this.isBadgeVisible()) { var value = this.props.groupRowsBy && this.props.groupRowsBy === this.props.groupRowSortField ? metaIndex : metaIndex + 1; return /*#__PURE__*/React.createElement("span", { className: "p-sortable-column-badge" }, value); } return null; } }, { key: "renderCheckbox", value: function renderCheckbox() { if (this.getColumnProp('selectionMode') === 'multiple' && this.props.filterDisplay !== 'row') { var allRowsSelected = this.props.allRowsSelected(this.props.value); return /*#__PURE__*/React.createElement(HeaderCheckbox, { checked: allRowsSelected, onChange: this.props.onColumnCheckboxChange, disabled: this.props.empty }); } return null; } }, { key: "renderFilter", value: function renderFilter() { if (this.props.filterDisplay === 'menu' && this.getColumnProp('filter')) { return /*#__PURE__*/React.createElement(ColumnFilter, { display: "menu", column: this.props.column, filters: this.props.filters, onFilterChange: this.props.onFilterChange, onFilterApply: this.props.onFilterApply, filtersStore: this.props.filtersStore }); } return null; } }, { key: "renderHeader", value: function renderHeader(sortMeta) { var title = this.renderTitle(); var sortIcon = this.renderSortIcon(sortMeta); var badge = this.renderBadge(sortMeta); var checkbox = this.renderCheckbox(); var filter = this.renderFilter(); return /*#__PURE__*/React.createElement("div", { className: "p-column-header-content" }, title, sortIcon, badge, checkbox, filter); } }, { key: "renderElement", value: function renderElement() { var _this3 = this; var isSortableDisabled = this.isSortableDisabled(); var sortMeta = this.getSortMeta(); var style = this.getStyle(); var className = classNames(this.getColumnProp('headerClassName'), this.getColumnProp('className'), { 'p-sortable-column': this.getColumnProp('sortable'), 'p-resizable-column': this.props.resizableColumns, 'p-highlight': sortMeta.sorted, 'p-frozen-column': this.getColumnProp('frozen'), 'p-selection-column': this.getColumnProp('selectionMode'), 'p-sortable-disabled': this.getColumnProp('sortable') && isSortableDisabled, 'p-reorderable-column': this.props.reorderableColumns && this.getColumnProp('reorderable') }); var tabIndex = this.getColumnProp('sortable') && !isSortableDisabled ? this.props.tabIndex : null; var colSpan = this.getColumnProp('colSpan'); var rowSpan = this.getColumnProp('rowSpan'); var ariaSort = this.getAriaSort(sortMeta); var resizer = this.renderResizer(); var header = this.renderHeader(sortMeta); return /*#__PURE__*/React.createElement("th", { ref: function ref(el) { return _this3.el = el; }, style: style, className: className, tabIndex: tabIndex, role: "columnheader", onClick: this.onClick, onKeyDown: this.onKeyDown, onMouseDown: this.onMouseDown, onDragStart: this.onDragStart, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDrop: this.onDrop, colSpan: colSpan, rowSpan: rowSpan, "aria-sort": ariaSort }, resizer, header); } }, { key: "render", value: function render() { return this.renderElement(); } }]); return HeaderCell; }(Component); function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TableHeader = /*#__PURE__*/function (_Component) { _inherits(TableHeader, _Component); var _super = _createSuper$1(TableHeader); function TableHeader(props) { var _this; _classCallCheck(this, TableHeader); _this = _super.call(this, props); _this.state = { sortableDisabledFields: [], allSortableDisabled: false, styleObject: {} }; _this.onSortableChange = _this.onSortableChange.bind(_assertThisInitialized(_this)); _this.onCheckboxChange = _this.onCheckboxChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(TableHeader, [{ key: "isSingleSort", value: function isSingleSort() { return this.props.sortMode === 'single'; } }, { key: "isMultipleSort", value: function isMultipleSort() { return this.props.sortMode === 'multiple'; } }, { key: "isAllSortableDisabled", value: function isAllSortableDisabled() { return this.isSingleSort() && this.state.allSortableDisabled; } }, { key: "isColumnSorted", value: function isColumnSorted(column) { return this.props.sortField !== null ? column.props.field === this.props.sortField || column.props.sortField === this.props.sortField : false; } }, { key: "updateSortableDisabled", value: function updateSortableDisabled() { var _this2 = this; if (this.isSingleSort() || this.isMultipleSort() && this.props.onSortChange) { var sortableDisabledFields = []; var allSortableDisabled = false; this.props.columns.forEach(function (column) { if (column.props.sortableDisabled) { sortableDisabledFields.push(column.props.sortField || column.props.field); if (!allSortableDisabled && _this2.isColumnSorted(column)) { allSortableDisabled = true; } } }); this.setState({ sortableDisabledFields: sortableDisabledFields, allSortableDisabled: allSortableDisabled }); } } }, { key: "onSortableChange", value: function onSortableChange() { this.updateSortableDisabled(); } }, { key: "onCheckboxChange", value: function onCheckboxChange(e) { this.props.onColumnCheckboxChange(e, this.props.value); } }, { key: "componentDidMount", value: function componentDidMount() { this.updateSortableDisabled(); } }, { key: "renderGroupHeaderCells", value: function renderGroupHeaderCells(row) { var columns = React.Children.toArray(row.props.children); return this.renderHeaderCells(columns); } }, { key: "renderHeaderCells", value: function renderHeaderCells(columns) { var _this3 = this; return React.Children.map(columns, function (col, i) { var isVisible = col ? !col.props.hidden : true; var key = col ? col.props.columnKey || col.props.field || i : i; return isVisible && /*#__PURE__*/React.createElement(HeaderCell, { key: key, value: _this3.props.value, tableProps: _this3.props.tableProps, column: col, tabIndex: _this3.props.tabIndex, empty: _this3.props.empty, resizableColumns: _this3.props.resizableColumns, groupRowsBy: _this3.props.groupRowsBy, groupRowSortField: _this3.props.groupRowSortField, sortMode: _this3.props.sortMode, sortField: _this3.props.sortField, sortOrder: _this3.props.sortOrder, multiSortMeta: _this3.props.multiSortMeta, allSortableDisabled: _this3.isAllSortableDisabled(), onSortableChange: _this3.onSortableChange, sortableDisabledFields: _this3.state.sortableDisabledFields, filterDisplay: _this3.props.filterDisplay, filters: _this3.props.filters, filtersStore: _this3.props.filtersStore, onFilterChange: _this3.props.onFilterChange, onFilterApply: _this3.props.onFilterApply, onColumnMouseDown: _this3.props.onColumnMouseDown, onColumnDragStart: _this3.props.onColumnDragStart, onColumnDragOver: _this3.props.onColumnDragOver, onColumnDragLeave: _this3.props.onColumnDragLeave, onColumnDrop: _this3.props.onColumnDrop, onColumnResizeStart: _this3.props.onColumnResizeStart, onColumnResizerClick: _this3.props.onColumnResizerClick, onColumnResizerDoubleClick: _this3.props.onColumnResizerDoubleClick, allRowsSelected: _this3.props.allRowsSelected, onColumnCheckboxChange: _this3.onCheckboxChange, reorderableColumns: _this3.props.reorderableColumns, onSortChange: _this3.props.onSortChange }); }); } }, { key: "renderFilterCells", value: function renderFilterCells() { var _this4 = this; return React.Children.map(this.props.columns, function (col, i) { var isVisible = !col.props.hidden; if (isVisible) { var _col$props = col.props, filterHeaderStyle = _col$props.filterHeaderStyle, style = _col$props.style, filterHeaderClassName = _col$props.filterHeaderClassName, className = _col$props.className, frozen = _col$props.frozen, columnKey = _col$props.columnKey, field = _col$props.field, selectionMode = _col$props.selectionMode, filter = _col$props.filter; var colStyle = _objectSpread$1(_objectSpread$1({}, filterHeaderStyle || {}), style || {}); var colClassName = classNames('p-filter-column', filterHeaderClassName, className, { 'p-frozen-column': frozen }); var colKey = columnKey || field || i; var allRowsSelected = selectionMode === 'multiple' && _this4.props.allRowsSelected(_this4.props.value); return /*#__PURE__*/React.createElement("th", { key: colKey, style: colStyle, className: colClassName }, selectionMode === 'multiple' && /*#__PURE__*/React.createElement(HeaderCheckbox, { checked: allRowsSelected, onChange: _this4.onCheckboxChange, disabled: _this4.props.empty }), filter && /*#__PURE__*/React.createElement(ColumnFilter, { display: "row", column: col, filters: _this4.props.filters, filtersStore: _this4.props.filtersStore, onFilterChange: _this4.props.onFilterChange, onFilterApply: _this4.props.onFilterApply })); } return null; }); } }, { key: "renderContent", value: function renderContent() { var _this5 = this; if (this.props.headerColumnGroup) { var rows = React.Children.toArray(this.props.headerColumnGroup.props.children); return rows.map(function (row, i) { return /*#__PURE__*/React.createElement("tr", { key: i, role: "row" }, _this5.renderGroupHeaderCells(row)); }); } else { var headerRow = /*#__PURE__*/React.createElement("tr", { role: "row" }, this.renderHeaderCells(this.props.columns)); var filterRow = this.props.filterDisplay === 'row' && /*#__PURE__*/React.createElement("tr", { role: "row" }, this.renderFilterCells()); return /*#__PURE__*/React.createElement(React.Fragment, null, headerRow, filterRow); } } }, { key: "render", value: function render() { var content = this.renderContent(); return /*#__PURE__*/React.createElement("thead", { className: "p-datatable-thead" }, content); } }]); return TableHeader; }(Component); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var DataTable = /*#__PURE__*/function (_Component) { _inherits(DataTable, _Component); var _super = _createSuper(DataTable); function DataTable(props) { var _this; _classCallCheck(this, DataTable); _this = _super.call(this, props); _this.state = { d_rows: props.rows, columnOrder: [], groupRowsSortMeta: null, editingMeta: {} }; if (!_this.props.onPage) { _this.state.first = props.first; _this.state.rows = props.rows; } if (!_this.props.onSort) { _this.state.sortField = props.sortField; _this.state.sortOrder = props.sortOrder; _this.state.multiSortMeta = props.multiSortMeta; } _this.state.d_filters = _this.cloneFilters(props.filters); if (!_this.props.onFilter) { _this.state.filters = props.filters; } if (_this.isStateful()) { _this.restoreState(_this.state); } _this.attributeSelector = UniqueComponentId(); // header _this.onSortChange = _this.onSortChange.bind(_assertThisInitialized(_this)); _this.onFilterChange = _this.onFilterChange.bind(_assertThisInitialized(_this)); _this.onFilterApply = _this.onFilterApply.bind(_assertThisInitialized(_this)); _this.onColumnHeaderMouseDown = _this.onColumnHeaderMouseDown.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDragStart = _this.onColumnHeaderDragStart.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDragOver = _this.onColumnHeaderDragOver.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDragLeave = _this.onColumnHeaderDragLeave.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDrop = _this.onColumnHeaderDrop.bind(_assertThisInitialized(_this)); _this.onColumnResizeStart = _this.onColumnResizeStart.bind(_assertThisInitialized(_this)); _this.onColumnHeaderCheckboxChange = _this.onColumnHeaderCheckboxChange.bind(_assertThisInitialized(_this)); _this.allRowsSelected = _this.allRowsSelected.bind(_assertThisInitialized(_this)); // body _this.onEditingMetaChange = _this.onEditingMetaChange.bind(_assertThisInitialized(_this)); //paginator _this.onPageChange = _this.onPageChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(DataTable, [{ key: "isCustomStateStorage", value: function isCustomStateStorage() { return this.props.stateStorage === 'custom'; } }, { key: "isStateful", value: function isStateful() { return this.props.stateKey != null || this.isCustomStateStorage(); } }, { key: "isVirtualScrollerDisabled", value: function isVirtualScrollerDisabled() { return ObjectUtils.isEmpty(this.props.virtualScrollerOptions) || !this.props.scrollable; } }, { key: "hasFilter", value: function hasFilter() { return ObjectUtils.isNotEmpty(this.getFilters()) || this.props.globalFilter; } }, { key: "getFirst", value: function getFirst() { return this.props.onPage ? this.props.first : this.state.first; } }, { key: "getRows", value: function getRows() { return this.props.onPage ? this.props.rows : this.state.rows; } }, { key: "getSortField", value: function getSortField() { return this.props.onSort ? this.props.sortField : this.state.sortField; } }, { key: "getSortOrder", value: function getSortOrder() { return this.props.onSort ? this.props.sortOrder : this.state.sortOrder; } }, { key: "getMultiSortMeta", value: function getMultiSortMeta() { return (this.props.onSort ? this.props.multiSortMeta : this.state.multiSortMeta) || []; } }, { key: "getFilters", value: function getFilters() { return this.props.onFilter ? this.props.filters : this.state.filters; } }, { key: "getColumnProp", value: function getColumnProp(col, prop) { return col.props[prop]; } }, { key: "getColumns", value: function getColumns(ignoreReorderable) { var _this2 = this; var columns = React.Children.toArray(this.props.children); if (!columns) { return null; } if (!ignoreReorderable && this.props.reorderableColumns && this.state.columnOrder) { var orderedColumns = this.state.columnOrder.reduce(function (arr, columnKey) { var column = _this2.findColumnByKey(columns, columnKey); column && arr.push(column); return arr; }, []); return [].concat(_toConsumableArray(orderedColumns), _toConsumableArray(columns.filter(function (col) { return orderedColumns.indexOf(col) < 0; }))); } return columns; } }, { key: "getStorage", value: function getStorage() { switch (this.props.stateStorage) { case 'local': return window.localStorage; case 'session': return window.sessionStorage; case 'custom': return null; default: throw new Error(this.props.stateStorage + ' is not a valid value for the state storage, supported values are "local", "session" and "custom".'); } } }, { key: "saveState", value: function saveState() { var state = {}; if (this.props.paginator) { state.first = this.getFirst(); state.rows = this.getRows(); } var sortField = this.getSortField(); if (sortField) { state.sortField = sortField; state.sortOrder = this.getSortOrder(); } var multiSortMeta = this.getMultiSortMeta(); if (multiSortMeta) { state.multiSortMeta = multiSortMeta; } if (this.hasFilter()) { state.filters = this.getFilters(); } if (this.props.resizableColumns) { this.saveColumnWidths(state); } if (this.props.reorderableColumns) { state.columnOrder = this.state.columnOrder; } if (this.props.expandedRows) { state.expandedRows = this.props.expandedRows; } if (this.props.selection && this.props.onSelectionChange) { state.selection = this.props.selection; } if (this.isCustomStateStorage()) { if (this.props.customSaveState) { this.props.customSaveState(state); } } else { var storage = this.getStorage(); if (ObjectUtils.isNotEmpty(state)) { storage.setItem(this.props.stateKey, JSON.stringify(state)); } } if (this.props.onStateSave) { this.props.onStateSave(state); } } }, { key: "clearState", value: function clearState() { var storage = this.getStorage(); if (storage && this.props.stateKey) { storage.removeItem(this.props.stateKey); } } }, { key: "restoreState", value: function restoreState(state) { var restoredState = {}; if (this.isCustomStateStorage()) { if (this.props.customRestoreState) { restoredState = this.props.customRestoreState(); } } else { var storage = this.getStorage(); var stateString = storage.getItem(this.props.stateKey); var dateFormat = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/; var reviver = function reviver(key, value) { return typeof value === "string" && dateFormat.test(value) ? new Date(value) : value; }; if (stateString) { restoredState = JSON.parse(stateString, reviver); } } this._restoreState(restoredState, state); } }, { key: "restoreTableState", value: function restoreTableState(restoredState) { var state = this._restoreState(restoredState); if (ObjectUtils.isNotEmpty(state)) { this.setState(state); } } }, { key: "_restoreState", value: function _restoreState(restoredState) { var _this3 = this; var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (ObjectUtils.isNotEmpty(restoredState)) { if (this.props.paginator) { if (this.props.onPage) { var getOnPageParams = function getOnPageParams(first, rows) { var totalRecords = _this3.getTotalRecords(_this3.processedData()); var pageCount = Math.ceil(totalRecords / rows) || 1; var page = Math.floor(first / rows); return { first: first, rows: rows, page: page, pageCount: pageCount }; }; this.props.onPage(getOnPageParams(restoredState.first, restoredState.rows)); } else { state.first = restoredState.first; state.rows = restoredState.rows; } } if (restoredState.sortField) { if (this.props.onSort) { this.props.onSort({ sortField: restoredState.sortField, sortOrder: restoredState.sortOrder }); } else { state.sortField = restoredState.sortField; state.sortOrder = restoredState.sortOrder; } } if (restoredState.multiSortMeta) { if (this.props.onSort) { this.props.onSort({ multiSortMeta: restoredState.multiSortMeta }); } else { state.multiSortMeta = restoredState.multiSortMeta; } } if (restoredState.filters) { state.d_filters = this.cloneFilters(restoredState.filters); if (this.props.onFilter) { this.props.onFilter({ filters: restoredState.filters }); } else { state.filters = this.cloneFilters(restoredState.filters); } } if (this.props.resizableColumns) { this.columnWidthsState = restoredState.columnWidths; this.tableWidthState = restoredState.tableWidth; } if (this.props.reorderableColumns) { state.columnOrder = restoredState.columnOrder; } if (restoredState.expandedRows && this.props.onRowToggle) { this.props.onRowToggle({ data: restoredState.expandedRows }); } if (restoredState.selection && this.props.onSelectionChange) { this.props.onSelectionChange({ value: restoredState.selection }); } if (this.props.onStateRestore) { this.props.onStateRestore(restoredState); } } return state; } }, { key: "saveColumnWidths", value: function saveColumnWidths(state) { var widths = []; var headers = DomHandler.find(this.el, '.p-datatable-thead > tr > th'); headers.forEach(function (header) { return widths.push(DomHandler.getOuterWidth(header)); }); state.columnWidths = widths.join(','); if (this.props.columnResizeMode === 'expand') { state.tableWidth = DomHandler.getOuterWidth(this.table) + 'px'; } } }, { key: "restoreColumnWidths", value: function restoreColumnWidths() { var _this4 = this; if (this.columnWidthsState) { var widths = this.columnWidthsState.split(','); if (this.props.columnResizeMode === 'expand' && this.tableWidthState) { this.table.style.width = this.tableWidthState; this.table.style.minWidth = this.tableWidthState; this.el.style.width = this.tableWidthState; } this.createStyleElement(); if (this.props.scrollable && widths && widths.length > 0) { var innerHTML = ''; widths.forEach(function (width, index) { innerHTML += "\n .p-datatable[".concat(_this4.attributeSelector, "] .p-datatable-thead > tr > th:nth-child(").concat(index + 1, ") {\n flex: 0 0 ").concat(width, "px;\n }\n\n .p-datatable[").concat(_this4.attributeSelector, "] .p-datatable-tbody > tr > td:nth-child(").concat(index + 1, ") {\n flex: 0 0 ").concat(width, "px;\n }\n "); }); this.styleElement.innerHTML = innerHTML; } else { DomHandler.find(this.table, '.p-datatable-thead > tr > th').forEach(function (header, index) { return header.style.width = widths[index] + 'px'; }); } } } }, { key: "findParentHeader", value: function findParentHeader(element) { if (element.nodeName === 'TH') { return element; } else { var parent = element.parentElement; while (parent.nodeName !== 'TH') { parent = parent.parentElement; if (!parent) break; } return parent; } } }, { key: "getGroupRowSortField", value: function getGroupRowSortField() { return this.props.sortMode === 'single' ? this.props.sortField : this.state.groupRowsSortMeta ? this.state.groupRowsSortMeta.field : null; } }, { key: "allRowsSelected", value: function allRowsSelected(processedData) { var _this5 = this; var val = this.props.frozenValue ? [].concat(_toConsumableArray(this.props.frozenValue), _toConsumableArray(processedData)) : processedData; var selectableVal = this.props.showSelectionElement ? val.filter(function (data, index) { return _this5.props.showSelectionElement(data, { rowIndex: index, props: _this5.props }); }) : val; var length = this.props.lazy ? this.props.totalRecords : selectableVal ? selectableVal.length : 0; return selectableVal && length > 0 && this.props.selection && this.props.selection.length > 0 && this.props.selection.length === length; } }, { key: "getSelectionModeInColumn", value: function getSelectionModeInColumn(columns) { if (columns) { var col = columns.find(function (c) { return !!c.props.selectionMode; }); return col ? col.props.selectionMode : null; } return null; } }, { key: "findColumnByKey", value: function findColumnByKey(columns, key) { return ObjectUtils.isNotEmpty(columns) ? columns.find(function (col) { return col.props.columnKey === key || col.props.field === key; }) : null; } }, { key: "getTotalRecords", value: function getTotalRecords(data) { return this.props.lazy ? this.props.totalRecords : data ? data.length : 0; } }, { key: "onEditingMetaChange", value: function onEditingMetaChange(e) { var rowData = e.rowData, field = e.field, rowIndex = e.rowIndex, editing = e.editing; var editingMeta = _objectSpread({}, this.state.editingMeta); var meta = editingMeta[rowIndex]; if (editing) { !meta && (meta = editingMeta[rowIndex] = { data: _objectSpread({}, rowData), fields: [] }); meta['fields'].push(field); } else if (meta) { var fields = meta['fields'].filter(function (f) { return f !== field; }); !fields.length ? delete editingMeta[rowIndex] : meta['fields'] = fields; } this.setState({ editingMeta: editingMeta }); } }, { key: "clearEditingMetaData", value: function clearEditingMetaData() { if (this.props.editMode && ObjectUtils.isNotEmpty(this.state.editingMeta)) { this.setState({ editingMeta: {} }); } } }, { key: "onColumnResizeStart", value: function onColumnResizeStart(e) { var event = e.originalEvent, column = e.column; var containerLeft = DomHandler.getOffset(this.el).left; this.resizeColumn = column; this.resizeColumnElement = event.currentTarget.parentElement; this.columnResizing = true; this.lastResizeHelperX = event.pageX - containerLeft + this.el.scrollLeft; this.bindColumnResizeEvents(); } }, { key: "onColumnResize", value: function onColumnResize(event) { var containerLeft = DomHandler.getOffset(this.el).left; DomHandler.addClass(this.el, 'p-unselectable-text'); this.resizeHelper.style.height = this.el.offsetHeight + 'px'; this.resizeHelper.style.top = 0 + 'px'; this.resizeHelper.style.left = event.pageX - containerLeft + this.el.scrollLeft + 'px'; this.resizeHelper.style.display = 'block'; } }, { key: "onColumnResizeEnd", value: function onColumnResizeEnd() { var delta = this.resizeHelper.offsetLeft - this.lastResizeHelperX; var columnWidth = this.resizeColumnElement.offsetWidth; var newColumnWidth = columnWidth + delta; var minWidth = this.resizeColumnElement.style.minWidth || 15; if (columnWidth + delta > parseInt(minWidth, 10)) { if (this.props.columnResizeMode === 'fit') { var nextColumn = this.resizeColumnElement.nextElementSibling; var nextColumnWidth = nextColumn.offsetWidth - delta; if (newColumnWidth > 15 && nextColumnWidth > 15) { this.resizeTableCells(newColumnWidth, nextColumnWidth); } } else if (this.props.columnResizeMode === 'expand') { var tableWidth = this.table.offsetWidth + delta + 'px'; this.table.style.width = tableWidth; this.table.style.minWidth = tableWidth; this.resizeTableCells(newColumnWidth); } if (this.props.onColumnResizeEnd) { this.props.onColumnResizeEnd({ element: this.resizeColumnElement, column: this.resizeColumn, delta: delta }); } if (this.isStateful()) { this.saveState(); } } this.resizeHelper.style.display = 'none'; this.resizeColumn = null; this.resizeColumnElement = null; DomHandler.removeClass(this.el, 'p-unselectable-text'); this.unbindColumnResizeEvents(); } }, { key: "resizeTableCells", value: function resizeTableCells(newColumnWidth, nextColumnWidth) { var _this6 = this; var widths = []; var colIndex = DomHandler.index(this.resizeColumnElement); var headers = DomHandler.find(this.table, '.p-datatable-thead > tr > th'); headers.forEach(function (header) { return widths.push(DomHandler.getOuterWidth(header)); }); this.destroyStyleElement(); this.createStyleElement(); var innerHTML = ''; widths.forEach(function (width, index) { var colWidth = index === colIndex ? newColumnWidth : nextColumnWidth && index === colIndex + 1 ? nextColumnWidth : width; var style = _this6.props.scrollable ? "flex: 0 0 ".concat(colWidth, "px !important") : "width: ".concat(colWidth, "px !important"); innerHTML += "\n .p-datatable[".concat(_this6.attributeSelector, "] .p-datatable-thead > tr > th:nth-child(").concat(index + 1, "),\n .p-datatable[").concat(_this6.attributeSelector, "] .p-datatable-tbody > tr > td:nth-child(").concat(index + 1, "),\n .p-datatable[").concat(_this6.attributeSelector, "] .p-datatable-tfoot > tr > td:nth-child(").concat(index + 1, ") {\n ").concat(style, "\n }\n "); }); this.styleElement.innerHTML = innerHTML; } }, { key: "bindColumnResizeEvents", value: function bindColumnResizeEvents() { var _this7 = this; if (!this.documentColumnResizeListener) { this.documentColumnResizeListener = document.addEventListener('mousemove', function (event) { if (_this7.columnResizing) { _this7.onColumnResize(event); } }); } if (!this.documentColumnResizeEndListener) { this.documentColumnResizeEndListener = document.addEventListener('mouseup', function () { if (_this7.columnResizing) { _this7.columnResizing = false; _this7.onColumnResizeEnd(); } }); } } }, { key: "unbindColumnResizeEvents", value: function unbindColumnResizeEvents() { if (this.documentColumnResizeListener) { document.removeEventListener('document', this.documentColumnResizeListener); this.documentColumnResizeListener = null; } if (this.documentColumnResizeEndListener) { document.removeEventListener('document', this.documentColumnResizeEndListener); this.documentColumnResizeEndListener = null; } } }, { key: "onColumnHeaderMouseDown", value: function onColumnHeaderMouseDown(e) { DomHandler.clearSelection(); var event = e.originalEvent, column = e.column; if (this.props.reorderableColumns && this.getColumnProp(column, 'reorderable') !== false) { if (event.target.nodeName === 'INPUT' || event.target.nodeName === 'TEXTAREA' || DomHandler.hasClass(event.target, 'p-column-resizer')) event.currentTarget.draggable = false;else event.currentTarget.draggable = true; } } }, { key: "onColumnHeaderCheckboxChange", value: function onColumnHeaderCheckboxChange(e, processedData) { var _this8 = this; var originalEvent = e.originalEvent, checked = e.checked; var selection; if (!checked) { selection = this.props.frozenValue ? [].concat(_toConsumableArray(this.props.frozenValue), _toConsumableArray(processedData)) : processedData; selection = this.props.showSelectionElement ? selection.filter(function (data, index) { return _this8.props.showSelectionElement(data, { rowIndex: index, props: _this8.props }); }) : selection; this.props.onAllRowsSelect && this.props.onAllRowsSelect({ originalEvent: originalEvent, data: selection, type: 'all' }); } else { selection = []; this.props.onAllRowsUnselect && this.props.onAllRowsUnselect({ originalEvent: originalEvent, data: selection, type: 'all' }); } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onColumnHeaderDragStart", value: function onColumnHeaderDragStart(e) { var event = e.originalEvent, column = e.column; if (this.columnResizing) { event.preventDefault(); return; } this.colReorderIconWidth = DomHandler.getHiddenElementOuterWidth(this.reorderIndicatorUp); this.colReorderIconHeight = DomHandler.getHiddenElementOuterHeight(this.reorderIndicatorUp); this.draggedColumn = column; this.draggedColumnElement = this.findParentHeader(event.currentTarget); event.dataTransfer.setData('text', 'b'); // Firefox requires this to make dragging possible } }, { key: "onColumnHeaderDragOver", value: function onColumnHeaderDragOver(e) { var event = e.originalEvent; var dropHeader = this.findParentHeader(event.currentTarget); if (this.props.reorderableColumns && this.draggedColumnElement && dropHeader) { event.preventDefault(); if (this.draggedColumnElement !== dropHeader) { var containerOffset = DomHandler.getOffset(this.el); var dropHeaderOffset = DomHandler.getOffset(dropHeader); var targetLeft = dropHeaderOffset.left - containerOffset.left; var columnCenter = dropHeaderOffset.left + dropHeader.offsetWidth / 2; this.reorderIndicatorUp.style.top = dropHeaderOffset.top - containerOffset.top - (this.colReorderIconHeight - 1) + 'px'; this.reorderIndicatorDown.style.top = dropHeaderOffset.top - containerOffset.top + dropHeader.offsetHeight + 'px'; if (event.pageX > columnCenter) { this.reorderIndicatorUp.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.reorderIndicatorDown.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.dropPosition = 1; } else { this.reorderIndicatorUp.style.left = targetLeft - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.reorderIndicatorDown.style.left = targetLeft - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.dropPosition = -1; } this.reorderIndicatorUp.style.display = 'block'; this.reorderIndicatorDown.style.display = 'block'; } } } }, { key: "onColumnHeaderDragLeave", value: function onColumnHeaderDragLeave(e) { var event = e.originalEvent; if (this.props.reorderableColumns && this.draggedColumnElement) { event.preventDefault(); this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; } } }, { key: "onColumnHeaderDrop", value: function onColumnHeaderDrop(e) { var _this9 = this; var event = e.originalEvent, column = e.column; event.preventDefault(); if (this.draggedColumnElement) { var dragIndex = DomHandler.index(this.draggedColumnElement); var dropIndex = DomHandler.index(this.findParentHeader(event.currentTarget)); var allowDrop = dragIndex !== dropIndex; if (allowDrop && (dropIndex - dragIndex === 1 && this.dropPosition === -1 || dragIndex - dropIndex === 1 && this.dropPosition === 1)) { allowDrop = false; } if (allowDrop) { var columns = this.getColumns(); var isSameColumn = function isSameColumn(col1, col2) { return col1.props.columnKey || col2.props.columnKey ? ObjectUtils.equals(col1.props, col2.props, 'columnKey') : ObjectUtils.equals(col1.props, col2.props, 'field'); }; var dragColIndex = columns.findIndex(function (child) { return isSameColumn(child, _this9.draggedColumn); }); var dropColIndex = columns.findIndex(function (child) { return isSameColumn(child, column); }); if (dropColIndex < dragColIndex && this.dropPosition === 1) { dropColIndex++; } if (dropColIndex > dragColIndex && this.dropPosition === -1) { dropColIndex--; } ObjectUtils.reorderArray(columns, dragColIndex, dropColIndex); var columnOrder = columns.reduce(function (orders, col) { orders.push(col.props.columnKey || col.props.field); return orders; }, []); this.setState({ columnOrder: columnOrder }); if (this.props.onColReorder) { this.props.onColReorder({ originalEvent: event, dragIndex: dragColIndex, dropIndex: dropColIndex, columns: columns }); } } this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; this.draggedColumnElement.draggable = false; this.draggedColumnElement = null; this.draggedColumn = null; this.dropPosition = null; } } }, { key: "createStyleElement", value: function createStyleElement() { this.styleElement = document.createElement('style'); document.head.appendChild(this.styleElement); } }, { key: "createResponsiveStyle", value: function createResponsiveStyle() { if (!this.responsiveStyleElement) { this.responsiveStyleElement = document.createElement('style'); document.head.appendChild(this.responsiveStyleElement); var innerHTML = "\n@media screen and (max-width: ".concat(this.props.breakpoint, ") {\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-thead > tr > th,\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tfoot > tr > td {\n display: none !important;\n }\n\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tbody > tr > td {\n display: flex;\n width: 100% !important;\n align-items: center;\n justify-content: space-between;\n }\n\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tbody > tr > td:not(:last-child) {\n border: 0 none;\n }\n\n .p-datatable[").concat(this.attributeSelector, "].p-datatable-gridlines .p-datatable-tbody > tr > td:last-child {\n border-top: 0;\n border-right: 0;\n border-left: 0;\n }\n\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tbody > tr > td > .p-column-title {\n display: block;\n }\n}\n"); this.responsiveStyleElement.innerHTML = innerHTML; } } }, { key: "destroyResponsiveStyle", value: function destroyResponsiveStyle() { if (this.responsiveStyleElement) { document.head.removeChild(this.responsiveStyleElement); this.responsiveStyleElement = null; } } }, { key: "destroyStyleElement", value: function destroyStyleElement() { if (this.styleElement) { document.head.removeChild(this.styleElement); this.styleElement = null; } } }, { key: "onPageChange", value: function onPageChange(e) { this.clearEditingMetaData(); if (this.props.onPage) this.props.onPage(e);else this.setState({ first: e.first, rows: e.rows }); if (this.props.onValueChange) { this.props.onValueChange(this.processedData()); } } }, { key: "onSortChange", value: function onSortChange(e) { this.clearEditingMetaData(); var event = e.originalEvent, column = e.column, sortableDisabledFields = e.sortableDisabledFields; var sortField = column.props.sortField || column.props.field; var sortOrder = this.props.defaultSortOrder; var multiSortMeta; var eventMeta; this.columnSortable = column.props.sortable; this.columnSortFunction = column.props.sortFunction; this.columnField = column.props.sortField; if (this.props.sortMode === 'multiple') { var metaKey = event.metaKey || event.ctrlKey; multiSortMeta = _toConsumableArray(this.getMultiSortMeta()); var sortMeta = multiSortMeta.find(function (sortMeta) { return sortMeta.field === sortField; }); sortOrder = sortMeta ? this.getCalculatedSortOrder(sortMeta.order) : sortOrder; var newMetaData = { field: sortField, order: sortOrder }; if (sortOrder) { multiSortMeta = metaKey ? multiSortMeta : multiSortMeta.filter(function (meta) { return sortableDisabledFields.some(function (field) { return field === meta.field; }); }); this.addSortMeta(newMetaData, multiSortMeta); } else if (this.props.removableSort) { this.removeSortMeta(newMetaData, multiSortMeta); } eventMeta = { multiSortMeta: multiSortMeta }; } else { sortOrder = this.getSortField() === sortField ? this.getCalculatedSortOrder(this.getSortOrder()) : sortOrder; if (this.props.removableSort) { sortField = sortOrder ? sortField : null; } eventMeta = { sortField: sortField, sortOrder: sortOrder }; } if (this.props.onSort) { this.props.onSort(eventMeta); } else { eventMeta.first = 0; this.setState(eventMeta); } if (this.props.onValueChange) { this.props.onValueChange(this.processedData({ sortField: sortField, sortOrder: sortOrder, multiSortMeta: multiSortMeta })); } } }, { key: "getCalculatedSortOrder", value: function getCalculatedSortOrder(currentOrder) { return this.props.removableSort ? this.props.defaultSortOrder === currentOrder ? currentOrder * -1 : 0 : currentOrder * -1; } }, { key: "addSortMeta", value: function addSortMeta(meta, multiSortMeta) { var index = multiSortMeta.findIndex(function (sortMeta) { return sortMeta.field === meta.field; }); if (index >= 0) multiSortMeta[index] = meta;else multiSortMeta.push(meta); } }, { key: "removeSortMeta", value: function removeSortMeta(meta, multiSortMeta) { var index = multiSortMeta.findIndex(function (sortMeta) { return sortMeta.field === meta.field; }); if (index >= 0) { multiSortMeta.splice(index, 1); } multiSortMeta = multiSortMeta.length > 0 ? multiSortMeta : null; } }, { key: "sortSingle", value: function sortSingle(data, field, order) { if (this.props.groupRowsBy && this.props.groupRowsBy === this.props.sortField) { var multiSortMeta = [{ field: this.props.sortField, order: this.props.sortOrder || this.props.defaultSortOrder }]; this.props.sortField !== field && multiSortMeta.push({ field: field, order: order }); return this.sortMultiple(data, multiSortMeta); } var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortFunction) { value = this.columnSortFunction({ field: field, order: order }); } else { value.sort(function (data1, data2) { var value1 = ObjectUtils.resolveFieldData(data1, field); var value2 = ObjectUtils.resolveFieldData(data2, field); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return order * result; }); } return value; } }, { key: "sortMultiple", value: function sortMultiple(data) { var _this10 = this; var multiSortMeta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (this.props.groupRowsBy && (this.groupRowsSortMeta || multiSortMeta.length && this.props.groupRowsBy === multiSortMeta[0].field)) { var firstSortMeta = multiSortMeta[0]; !this.groupRowsSortMeta && (this.groupRowsSortMeta = firstSortMeta); if (firstSortMeta.field !== this.groupRowsSortMeta.field) { multiSortMeta = [this.groupRowsSortMeta].concat(_toConsumableArray(multiSortMeta)); } } var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortFunction) { var meta = multiSortMeta.find(function (meta) { return meta.field === _this10.columnField; }); var field = this.columnField; var order = meta ? meta.order : this.defaultSortOrder; value = this.columnSortFunction({ field: field, order: order }); } else { value.sort(function (data1, data2) { return _this10.multisortField(data1, data2, multiSortMeta, 0); }); } return value; } }, { key: "multisortField", value: function multisortField(data1, data2, multiSortMeta, index) { var value1 = ObjectUtils.resolveFieldData(data1, multiSortMeta[index].field); var value2 = ObjectUtils.resolveFieldData(data2, multiSortMeta[index].field); var result = null; if (typeof value1 === 'string' || value1 instanceof String) { if (value1.localeCompare && value1 !== value2) { return multiSortMeta[index].order * value1.localeCompare(value2, undefined, { numeric: true }); } } else { result = value1 < value2 ? -1 : 1; } if (value1 === value2) { return multiSortMeta.length - 1 > index ? this.multisortField(data1, data2, multiSortMeta, index + 1) : 0; } return multiSortMeta[index].order * result; } }, { key: "onFilterChange", value: function onFilterChange(filters) { this.clearEditingMetaData(); this.setState({ d_filters: filters }); } }, { key: "onFilterApply", value: function onFilterApply() { var _this11 = this; clearTimeout(this.filterTimeout); this.filterTimeout = setTimeout(function () { var filters = _this11.cloneFilters(_this11.state.d_filters); if (_this11.props.onFilter) { _this11.props.onFilter({ filters: filters }); } else { _this11.setState({ first: 0, filters: filters }); } if (_this11.props.onValueChange) { _this11.props.onValueChange(_this11.processedData({ filters: filters })); } }, this.props.filterDelay); } }, { key: "filterLocal", value: function filterLocal(data, filters) { if (!data) return; filters = filters || {}; var columns = this.getColumns(); var filteredValue = []; var isGlobalFilter = filters['global'] || this.props.globalFilter; var globalFilterFieldsArray; if (isGlobalFilter) { globalFilterFieldsArray = this.props.globalFilterFields || columns.filter(function (col) { return !col.props.excludeGlobalFilter; }).map(function (col) { return col.props.filterField || col.props.field; }); } for (var i = 0; i < data.length; i++) { var localMatch = true; var globalMatch = false; var localFiltered = false; for (var prop in filters) { if (Object.prototype.hasOwnProperty.call(filters, prop) && prop !== 'global') { localFiltered = true; var filterField = prop; var filterMeta = filters[filterField]; if (filterMeta.operator) { for (var j = 0; j < filterMeta.constraints.length; j++) { var filterConstraint = filterMeta.constraints[j]; localMatch = this.executeLocalFilter(filterField, data[i], filterConstraint, j); if (filterMeta.operator === FilterOperator.OR && localMatch || filterMeta.operator === FilterOperator.AND && !localMatch) { break; } } } else { localMatch = this.executeLocalFilter(filterField, data[i], filterMeta, 0); } if (!localMatch) { break; } } } if (isGlobalFilter && !globalMatch && globalFilterFieldsArray) { for (var _j = 0; _j < globalFilterFieldsArray.length; _j++) { var globalFilterField = globalFilterFieldsArray[_j]; var matchMode = filters['global'] ? filters['global'].matchMode : FilterMatchMode$1.CONTAINS; var value = filters['global'] ? filters['global'].value : this.props.globalFilter; globalMatch = FilterService.filters[matchMode](ObjectUtils.resolveFieldData(data[i], globalFilterField), value, this.props.filterLocale); if (globalMatch) { break; } } } var matches = void 0; if (isGlobalFilter) { matches = localFiltered ? localFiltered && localMatch && globalMatch : globalMatch; } else { matches = localFiltered && localMatch; } if (matches) { filteredValue.push(data[i]); } } if (filteredValue.length === this.props.value.length) { filteredValue = data; } return filteredValue; } }, { key: "executeLocalFilter", value: function executeLocalFilter(field, rowData, filterMeta, index) { var filterValue = filterMeta.value; var filterMatchMode = filterMeta.matchMode === 'custom' ? "custom_".concat(field) : filterMeta.matchMode || FilterMatchMode$1.STARTS_WITH; var dataFieldValue = ObjectUtils.resolveFieldData(rowData, field); var filterConstraint = FilterService.filters[filterMatchMode]; return filterConstraint(dataFieldValue, filterValue, this.props.filterLocale, index); } }, { key: "cloneFilters", value: function cloneFilters(filters) { var _this12 = this; filters = filters || this.props.filters; var cloned = {}; if (filters) { Object.entries(filters).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), prop = _ref2[0], value = _ref2[1]; cloned[prop] = value.operator ? { operator: value.operator, constraints: value.constraints.map(function (constraint) { return _objectSpread({}, constraint); }) } : _objectSpread({}, value); }); } else { var columns = this.getColumns(); cloned = columns.reduce(function (_filters, col) { if (col.props.filter) { var field = col.props.filterField || col.props.field; var filterFunction = col.props.filterFunction; var dataType = col.props.dataType; var matchMode = col.props.filterMatchMode || (PrimeReact.filterMatchModeOptions[dataType] ? PrimeReact.filterMatchModeOptions[dataType][0] : FilterMatchMode$1.STARTS_WITH); var constraint = { value: null, matchMode: matchMode }; if (filterFunction) { FilterService.register("custom_".concat(field), function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return filterFunction.apply(void 0, args.concat([{ column: col }])); }); } _filters[field] = _this12.props.filterDisplay === 'menu' ? { operator: FilterOperator.AND, constraints: [constraint] } : constraint; } return _filters; }, {}); } return cloned; } }, { key: "filter", value: function filter(value, field, matchMode) { var index = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var filters = _objectSpread({}, this.state.d_filters); var meta = filters[field]; var constraint = meta && meta.operator ? meta.constraints[index] : meta; constraint = meta ? { value: value, matchMode: matchMode || constraint.matchMode } : { value: value, matchMode: matchMode }; this.props.filterDisplay === 'menu' && meta && meta.operator ? filters[field].constraints[index] = constraint : filters[field] = constraint; this.setState({ d_filters: filters }, this.onFilterApply); } }, { key: "reset", value: function reset() { var state = { d_rows: this.props.rows, d_filters: this.cloneFilters(this.props.filters), groupRowsSortMeta: null, editingMeta: {} }; if (!this.props.onPage) { state.first = this.props.first; state.rows = this.props.rows; } if (!this.props.onSort) { state.sortField = this.props.sortField; state.sortOrder = this.props.sortOrder; state.multiSortMeta = this.props.multiSortMeta; } if (!this.props.onFilter) { state.filters = this.props.filters; } this.resetColumnOrder(); this.setState(state); } }, { key: "resetColumnOrder", value: function resetColumnOrder() { var columns = this.getColumns(true); var columnOrder = []; if (columns) { columnOrder = columns.reduce(function (orders, col) { orders.push(col.props.columnKey || col.props.field); return orders; }, []); } this.setState({ columnOrder: columnOrder }); } }, { key: "exportCSV", value: function exportCSV(options) { var _this13 = this; var data; var csv = "\uFEFF"; var columns = this.getColumns(); if (options && options.selectionOnly) { data = this.props.selection || []; } else { data = [].concat(_toConsumableArray(this.props.frozenValue || []), _toConsumableArray(this.processedData() || [])); } //headers columns.forEach(function (column, i) { var _column$props = column.props, field = _column$props.field, header = _column$props.header, exportable = _column$props.exportable; if (exportable && field) { csv += '"' + (header || field) + '"'; if (i < columns.length - 1) { csv += _this13.props.csvSeparator; } } }); //body data.forEach(function (record) { csv += '\n'; columns.forEach(function (column, i) { var _column$props2 = column.props, field = _column$props2.field, exportable = _column$props2.exportable; if (exportable && field) { var cellData = ObjectUtils.resolveFieldData(record, field); if (cellData != null) { cellData = _this13.props.exportFunction ? _this13.props.exportFunction({ data: cellData, field: field, rowData: record, column: column }) : String(cellData).replace(/"/g, '""'); } else cellData = ''; csv += '"' + cellData + '"'; if (i < columns.length - 1) { csv += _this13.props.csvSeparator; } } }); }); DomHandler.exportCSV(csv, this.props.exportFilename); } }, { key: "closeEditingCell", value: function closeEditingCell() { if (this.props.editMode !== "row") { document.body.click(); } } }, { key: "processedData", value: function processedData(localState) { var data = this.props.value || []; if (!this.props.lazy) { if (data && data.length) { var filters = localState && localState.filters || this.getFilters(); var sortField = localState && localState.sortField || this.getSortField(); var sortOrder = localState && localState.sortOrder || this.getSortOrder(); var multiSortMeta = localState && localState.multiSortMeta || this.getMultiSortMeta(); if (ObjectUtils.isNotEmpty(filters) || this.props.globalFilter) { data = this.filterLocal(data, filters); } if (sortField || ObjectUtils.isNotEmpty(multiSortMeta)) { if (this.props.sortMode === 'single') data = this.sortSingle(data, sortField, sortOrder);else if (this.props.sortMode === 'multiple') data = this.sortMultiple(data, multiSortMeta); } } } return data; } }, { key: "dataToRender", value: function dataToRender(data) { if (data && this.props.paginator) { var first = this.props.lazy ? 0 : this.getFirst(); return data.slice(first, first + this.getRows()); } return data; } }, { key: "componentDidMount", value: function componentDidMount() { this.el.setAttribute(this.attributeSelector, ''); if (this.props.responsiveLayout === 'stack' && !this.props.scrollable) { this.createResponsiveStyle(); } if (this.isStateful() && this.props.resizableColumns) { this.restoreColumnWidths(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.isStateful()) { this.saveState(); } if (prevProps.responsiveLayout !== this.props.responsiveLayout) { this.destroyResponsiveStyle(); if (this.props.responsiveLayout === 'stack' && !this.props.scrollable) { this.createResponsiveStyle(); } } if (prevProps.filters !== this.props.filters) { this.setState({ filters: this.cloneFilters(this.props.filters), d_filters: this.cloneFilters(this.props.filters) }); } if (prevProps.globalFilter !== this.props.globalFilter) { this.filter(this.props.globalFilter, 'global', 'contains'); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindColumnResizeEvents(); this.destroyStyleElement(); this.destroyResponsiveStyle(); } }, { key: "renderLoader", value: function renderLoader() { if (this.props.loading) { var iconClassName = classNames('p-datatable-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-datatable-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: iconClassName })); } return null; } }, { key: "renderHeader", value: function renderHeader() { if (this.props.header) { var content = ObjectUtils.getJSXElement(this.props.header, { props: this.props }); return /*#__PURE__*/React.createElement("div", { className: "p-datatable-header" }, content); } return null; } }, { key: "renderTableHeader", value: function renderTableHeader(options, empty) { var sortField = this.getSortField(); var sortOrder = this.getSortOrder(); var multiSortMeta = _toConsumableArray(this.getMultiSortMeta()); var groupRowSortField = this.getGroupRowSortField(); var filters = this.state.d_filters; var filtersStore = this.getFilters(); var processedData = options.items, columns = options.columns; return /*#__PURE__*/React.createElement(TableHeader, { value: processedData, tableProps: this.props, columns: columns, tabIndex: this.props.tabIndex, empty: empty, headerColumnGroup: this.props.headerColumnGroup, resizableColumns: this.props.resizableColumns, onColumnResizeStart: this.onColumnResizeStart, onColumnResizerClick: this.props.onColumnResizerClick, onColumnResizerDoubleClick: this.props.onColumnResizerDoubleClick, sortMode: this.props.sortMode, sortField: sortField, sortOrder: sortOrder, multiSortMeta: multiSortMeta, groupRowsBy: this.props.groupRowsBy, groupRowSortField: groupRowSortField, onSortChange: this.onSortChange, filterDisplay: this.props.filterDisplay, filters: filters, filtersStore: filtersStore, onFilterChange: this.onFilterChange, onFilterApply: this.onFilterApply, allRowsSelected: this.allRowsSelected, onColumnCheckboxChange: this.onColumnHeaderCheckboxChange, onColumnMouseDown: this.onColumnHeaderMouseDown, onColumnDragStart: this.onColumnHeaderDragStart, onColumnDragOver: this.onColumnHeaderDragOver, onColumnDragLeave: this.onColumnHeaderDragLeave, onColumnDrop: this.onColumnHeaderDrop, rowGroupMode: this.props.rowGroupMode, reorderableColumns: this.props.reorderableColumns }); } }, { key: "renderTableBody", value: function renderTableBody(options, selectionModeInColumn, empty, isVirtualScrollerDisabled) { var tableSelector = this.attributeSelector; var first = this.getFirst(); var editingMeta = this.state.editingMeta; var rows = options.rows, columns = options.columns, contentRef = options.contentRef, className = options.className; var frozenBody = this.props.frozenValue && /*#__PURE__*/React.createElement(TableBody, { value: this.props.frozenValue, className: "p-datatable-frozen-tbody", frozenRow: true, tableProps: this.props, tableSelector: tableSelector, columns: columns, selectionModeInColumn: selectionModeInColumn, first: first, editingMeta: editingMeta, onEditingMetaChange: this.onEditingMetaChange, tabIndex: this.props.tabIndex, onRowClick: this.props.onRowClick, onRowDoubleClick: this.props.onRowDoubleClick, onCellClick: this.props.onCellClick, selection: this.props.selection, onSelectionChange: this.props.onSelectionChange, lazy: this.props.lazy, paginator: this.props.paginator, onCellSelect: this.props.onCellSelect, onCellUnselect: this.props.onCellUnselect, onRowSelect: this.props.onRowSelect, onRowUnselect: this.props.onRowUnselect, dragSelection: this.props.dragSelection, onContextMenu: this.props.onContextMenu, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, metaKeySelection: this.props.metaKeySelection, selectionMode: this.props.selectionMode, cellSelection: this.props.cellSelection, contextMenuSelection: this.props.contextMenuSelection, dataKey: this.props.dataKey, expandedRows: this.props.expandedRows, onRowCollapse: this.props.onRowCollapse, onRowExpand: this.props.onRowExpand, onRowToggle: this.props.onRowToggle, editMode: this.props.editMode, editingRows: this.props.editingRows, onRowReorder: this.props.onRowReorder, scrollable: this.props.scrollable, rowGroupMode: this.props.rowGroupMode, groupRowsBy: this.props.groupRowsBy, expandableRowGroups: this.props.expandableRowGroups, loading: this.props.loading, emptyMessage: this.props.emptyMessage, rowGroupHeaderTemplate: this.props.rowGroupHeaderTemplate, rowExpansionTemplate: this.props.rowExpansionTemplate, rowGroupFooterTemplate: this.props.rowGroupFooterTemplate, onRowEditChange: this.props.onRowEditChange, compareSelectionBy: this.props.compareSelectionBy, selectOnEdit: this.props.selectOnEdit, onRowEditInit: this.props.onRowEditInit, rowEditValidator: this.props.rowEditValidator, onRowEditSave: this.props.onRowEditSave, onRowEditComplete: this.props.onRowEditComplete, onRowEditCancel: this.props.onRowEditCancel, cellClassName: this.props.cellClassName, responsiveLayout: this.props.responsiveLayout, showSelectionElement: this.props.showSelectionElement, showRowReorderElement: this.props.showRowReorderElement, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon, rowClassName: this.props.rowClassName, isVirtualScrollerDisabled: true }); var body = /*#__PURE__*/React.createElement(TableBody, { value: this.dataToRender(rows), className: className, empty: empty, frozenRow: false, tableProps: this.props, tableSelector: tableSelector, columns: columns, selectionModeInColumn: selectionModeInColumn, first: first, editingMeta: editingMeta, onEditingMetaChange: this.onEditingMetaChange, tabIndex: this.props.tabIndex, onRowClick: this.props.onRowClick, onRowDoubleClick: this.props.onRowDoubleClick, onCellClick: this.props.onCellClick, selection: this.props.selection, onSelectionChange: this.props.onSelectionChange, lazy: this.props.lazy, paginator: this.props.paginator, onCellSelect: this.props.onCellSelect, onCellUnselect: this.props.onCellUnselect, onRowSelect: this.props.onRowSelect, onRowUnselect: this.props.onRowUnselect, dragSelection: this.props.dragSelection, onContextMenu: this.props.onContextMenu, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, metaKeySelection: this.props.metaKeySelection, selectionMode: this.props.selectionMode, cellSelection: this.props.cellSelection, contextMenuSelection: this.props.contextMenuSelection, dataKey: this.props.dataKey, expandedRows: this.props.expandedRows, onRowCollapse: this.props.onRowCollapse, onRowExpand: this.props.onRowExpand, onRowToggle: this.props.onRowToggle, editMode: this.props.editMode, editingRows: this.props.editingRows, onRowReorder: this.props.onRowReorder, scrollable: this.props.scrollable, rowGroupMode: this.props.rowGroupMode, groupRowsBy: this.props.groupRowsBy, expandableRowGroups: this.props.expandableRowGroups, loading: this.props.loading, emptyMessage: this.props.emptyMessage, rowGroupHeaderTemplate: this.props.rowGroupHeaderTemplate, rowExpansionTemplate: this.props.rowExpansionTemplate, rowGroupFooterTemplate: this.props.rowGroupFooterTemplate, onRowEditChange: this.props.onRowEditChange, compareSelectionBy: this.props.compareSelectionBy, selectOnEdit: this.props.selectOnEdit, onRowEditInit: this.props.onRowEditInit, rowEditValidator: this.props.rowEditValidator, onRowEditSave: this.props.onRowEditSave, onRowEditComplete: this.props.onRowEditComplete, onRowEditCancel: this.props.onRowEditCancel, cellClassName: this.props.cellClassName, responsiveLayout: this.props.responsiveLayout, showSelectionElement: this.props.showSelectionElement, showRowReorderElement: this.props.showRowReorderElement, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon, rowClassName: this.props.rowClassName, virtualScrollerContentRef: contentRef, virtualScrollerOptions: options, isVirtualScrollerDisabled: isVirtualScrollerDisabled }); return /*#__PURE__*/React.createElement(React.Fragment, null, frozenBody, body); } }, { key: "renderTableFooter", value: function renderTableFooter(options) { var columns = options.columns; return /*#__PURE__*/React.createElement(TableFooter, { tableProps: this.props, columns: columns, footerColumnGroup: this.props.footerColumnGroup }); } }, { key: "renderContent", value: function renderContent(processedData, columns, selectionModeInColumn, empty) { var _this14 = this; if (!columns) return; var isVirtualScrollerDisabled = this.isVirtualScrollerDisabled(); var virtualScrollerOptions = this.props.virtualScrollerOptions || {}; return /*#__PURE__*/React.createElement("div", { className: "p-datatable-wrapper", style: { maxHeight: isVirtualScrollerDisabled ? this.props.scrollHeight : '' } }, /*#__PURE__*/React.createElement(VirtualScroller, _extends({}, virtualScrollerOptions, { items: processedData, columns: columns, style: { height: this.props.scrollHeight }, disabled: isVirtualScrollerDisabled, loaderDisabled: true, showSpacer: false, contentTemplate: function contentTemplate(options) { var ref = function ref(el) { _this14.table = el; options.spacerRef && options.spacerRef(el); }; var tableClassName = classNames('p-datatable-table', _this14.props.tableClassName); var tableHeader = _this14.renderTableHeader(options, empty); var tableBody = _this14.renderTableBody(options, selectionModeInColumn, empty, isVirtualScrollerDisabled); var tableFooter = _this14.renderTableFooter(options); return /*#__PURE__*/React.createElement("table", { ref: ref, style: _this14.props.tableStyle, className: tableClassName, role: "table" }, tableHeader, tableBody, tableFooter); } }))); } }, { key: "renderFooter", value: function renderFooter() { if (this.props.footer) { var content = ObjectUtils.getJSXElement(this.props.footer, { props: this.props }); return /*#__PURE__*/React.createElement("div", { className: "p-datatable-footer" }, content); } return null; } }, { key: "renderPaginator", value: function renderPaginator(position, totalRecords) { var className = classNames('p-paginator-' + position, this.props.paginatorClassName); return /*#__PURE__*/React.createElement(Paginator, { first: this.getFirst(), rows: this.getRows(), pageLinkSize: this.props.pageLinkSize, className: className, onPageChange: this.onPageChange, template: this.props.paginatorTemplate, totalRecords: totalRecords, rowsPerPageOptions: this.props.rowsPerPageOptions, currentPageReportTemplate: this.props.currentPageReportTemplate, leftContent: this.props.paginatorLeft, rightContent: this.props.paginatorRight, alwaysShow: this.props.alwaysShowPaginator, dropdownAppendTo: this.props.paginatorDropdownAppendTo }); } }, { key: "renderPaginatorTop", value: function renderPaginatorTop(totalRecords) { if (this.props.paginator && this.props.paginatorPosition !== 'bottom') { return this.renderPaginator('top', totalRecords); } return null; } }, { key: "renderPaginatorBottom", value: function renderPaginatorBottom(totalRecords) { if (this.props.paginator && this.props.paginatorPosition !== 'top') { return this.renderPaginator('bottom', totalRecords); } return null; } }, { key: "renderResizeHelper", value: function renderResizeHelper() { var _this15 = this; if (this.props.resizableColumns) { return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this15.resizeHelper = el; }, className: "p-column-resizer-helper", style: { display: 'none' } }); } return null; } }, { key: "renderReorderIndicators", value: function renderReorderIndicators() { var _this16 = this; if (this.props.reorderableColumns) { var style = { position: 'absolute', display: 'none' }; return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this16.reorderIndicatorUp = el; }, className: "pi pi-arrow-down p-datatable-reorder-indicator-up", style: style }), /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this16.reorderIndicatorDown = el; }, className: "pi pi-arrow-up p-datatable-reorder-indicator-down", style: style })); } return null; } }, { key: "render", value: function render() { var _this17 = this; var processedData = this.processedData(); var columns = this.getColumns(); var totalRecords = this.getTotalRecords(processedData); var empty = ObjectUtils.isEmpty(processedData); var selectionModeInColumn = this.getSelectionModeInColumn(columns); var className = classNames('p-datatable p-component', { 'p-datatable-hoverable-rows': this.props.rowHover || this.props.selectionMode || selectionModeInColumn, 'p-datatable-auto-layout': this.props.autoLayout, 'p-datatable-resizable': this.props.resizableColumns, 'p-datatable-resizable-fit': this.props.resizableColumns && this.props.columnResizeMode === 'fit', 'p-datatable-scrollable': this.props.scrollable, 'p-datatable-scrollable-vertical': this.props.scrollable && this.props.scrollDirection === 'vertical', 'p-datatable-scrollable-horizontal': this.props.scrollable && this.props.scrollDirection === 'horizontal', 'p-datatable-scrollable-both': this.props.scrollable && this.props.scrollDirection === 'both', 'p-datatable-flex-scrollable': this.props.scrollable && this.props.scrollHeight === 'flex', 'p-datatable-responsive-stack': this.props.responsiveLayout === 'stack', 'p-datatable-responsive-scroll': this.props.responsiveLayout === 'scroll', 'p-datatable-striped': this.props.stripedRows, 'p-datatable-gridlines': this.props.showGridlines, 'p-datatable-grouped-header': this.props.headerColumnGroup != null, 'p-datatable-grouped-footer': this.props.footerColumnGroup != null, 'p-datatable-sm': this.props.size === 'small', 'p-datatable-lg': this.props.size === 'large' }, this.props.className); var loader = this.renderLoader(); var header = this.renderHeader(); var paginatorTop = this.renderPaginatorTop(totalRecords); var content = this.renderContent(processedData, columns, selectionModeInColumn, empty); var paginatorBottom = this.renderPaginatorBottom(totalRecords); var footer = this.renderFooter(); var resizeHelper = this.renderResizeHelper(); var reorderIndicators = this.renderReorderIndicators(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this17.el = el; }, id: this.props.id, className: className, style: this.props.style, "data-scrollselectors": ".p-datatable-wrapper" }, loader, header, paginatorTop, content, paginatorBottom, footer, resizeHelper, reorderIndicators); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (nextProps.rows !== prevState.d_rows && !nextProps.onPage) { return { rows: nextProps.rows, d_rows: nextProps.rows }; } return null; } }]); return DataTable; }(Component); _defineProperty(DataTable, "defaultProps", { id: null, value: null, header: null, footer: null, style: null, className: null, tableStyle: null, tableClassName: null, paginator: false, paginatorPosition: 'bottom', alwaysShowPaginator: true, paginatorClassName: null, paginatorTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', paginatorLeft: null, paginatorRight: null, paginatorDropdownAppendTo: null, pageLinkSize: 5, rowsPerPageOptions: null, currentPageReportTemplate: '({currentPage} of {totalPages})', first: 0, rows: null, totalRecords: null, lazy: false, sortField: null, sortOrder: null, multiSortMeta: null, sortMode: 'single', defaultSortOrder: 1, removableSort: false, emptyMessage: null, selectionMode: null, dragSelection: false, cellSelection: false, selection: null, onSelectionChange: null, contextMenuSelection: null, onContextMenuSelectionChange: null, compareSelectionBy: 'deepEquals', dataKey: null, metaKeySelection: true, selectOnEdit: true, headerColumnGroup: null, footerColumnGroup: null, rowExpansionTemplate: null, expandedRows: null, onRowToggle: null, resizableColumns: false, columnResizeMode: 'fit', reorderableColumns: false, filters: null, globalFilter: null, filterDelay: 300, filterLocale: undefined, scrollable: false, scrollHeight: null, scrollDirection: 'vertical', virtualScrollerOptions: null, frozenWidth: null, frozenValue: null, csvSeparator: ',', exportFilename: 'download', rowGroupMode: null, autoLayout: false, rowClassName: null, cellClassName: null, rowGroupHeaderTemplate: null, rowGroupFooterTemplate: null, loading: false, loadingIcon: 'pi pi-spinner', tabIndex: 0, stateKey: null, stateStorage: 'session', groupRowsBy: null, editMode: 'cell', editingRows: null, expandableRowGroups: false, rowHover: false, showGridlines: false, stripedRows: false, size: 'normal', responsiveLayout: 'stack', breakpoint: '960px', filterDisplay: 'menu', expandedRowIcon: 'pi pi-chevron-down', collapsedRowIcon: 'pi pi-chevron-right', onRowEditComplete: null, globalFilterFields: null, showSelectionElement: null, showRowReorderElement: null, onColumnResizeEnd: null, onColumnResizerClick: null, onColumnResizerDoubleClick: null, onSort: null, onPage: null, onFilter: null, onAllRowsSelect: null, onAllRowsUnselect: null, onRowClick: null, onRowDoubleClick: null, onRowSelect: null, onRowUnselect: null, onRowExpand: null, onRowCollapse: null, onContextMenu: null, onColReorder: null, onCellClick: null, onCellSelect: null, onCellUnselect: null, onRowReorder: null, onValueChange: null, rowEditValidator: null, onRowEditInit: null, onRowEditSave: null, onRowEditCancel: null, onRowEditChange: null, exportFunction: null, customSaveState: null, customRestoreState: null, onStateSave: null, onStateRestore: null }); export { DataTable };
ajax/libs/react-instantsearch/4.0.0-beta.3/Dom.js
cdnjs/cdnjs
/*! ReactInstantSearch 4.0.0-beta.3 | © Algolia, inc. | https://community.algolia.com/react-instantsearch/ */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["Dom"] = factory(require("react"), require("react-dom")); else root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Dom"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_429__) { 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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // 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 = 432); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if (false) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(208)(); } /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEqual2 = __webpack_require__(104); var _isEqual3 = _interopRequireDefault(_isEqual2); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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; }; }(); exports.default = createConnector; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); 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; } /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = (0, _has3.default)(connectorDesc, 'refine'); var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters'); var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata'); var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState'); var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { _inherits(Connector, _Component); function Connector(props, context) { _classCallCheck(this, Connector); var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais; var store = _context$ais.store; var widgetsManager = _context$ais.widgetsManager; var multiIndexContext = context.multiIndexContext; _this.state = { props: _this.getProvidedProps(props) }; _this.unsubscribe = store.subscribe(function () { _this.setState({ props: _this.getProvidedProps(_this.props) }); }); var getSearchParameters = hasSearchParameters ? function (searchParameters) { return connectorDesc.getSearchParameters.call(_this, searchParameters, _this.props, store.getState().widgets); } : null; var getMetadata = hasMetadata ? function (nextWidgetsState) { return connectorDesc.getMetadata.call(_this, _this.props, nextWidgetsState); } : null; var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) { return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState); } : null; if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget({ getSearchParameters: getSearchParameters, getMetadata: getMetadata, transitionState: transitionState, multiIndexContext: multiIndexContext }); } return _this; } _createClass(Connector, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!(0, _isEqual3.default)(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); //will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange((0, _utils.removeEmptyKey)(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props); } }, { key: 'render', value: function render() { var _this2 = this; if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues, searchForFacetValues: function searchForFacetValues(facetName, query) { if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.'); } _this2.searchForFacetValues(facetName, query); } } : {}; return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: _propTypes2.default.object.isRequired, multiIndexContext: _propTypes2.default.object }, _initialiseProps = function _initialiseProps() { var _this3 = this; this.getProvidedProps = function (props) { var store = _this3.context.ais.store; var _store$getState = store.getState(); var results = _store$getState.results; var searching = _store$getState.searching; var error = _store$getState.error; var widgets = _store$getState.widgets; var metadata = _store$getState.metadata; var resultsFacetValues = _store$getState.resultsFacetValues; var searchState = { results: results, searching: searching, error: error }; return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args)); }; }, _temp; }; } /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(78); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }), /* 4 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _get2 = __webpack_require__(73); var _get3 = _interopRequireDefault(_get2); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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; }; exports.getIndex = getIndex; exports.getResults = getResults; exports.hasMultipleIndex = hasMultipleIndex; exports.refineValue = refineValue; exports.getCurrentRefinementValue = getCurrentRefinementValue; exports.cleanUpValue = cleanUpValue; 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 getIndex(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (hasMultipleIndex(context)) { return searchResults.results && searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndex(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndex(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var index = getIndex(context); var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, nextRefinement, page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) { var _extends4; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], (_extends4 = {}, _defineProperty(_extends4, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), _defineProperty(_extends4, 'page', 1), _extends4)))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends(_defineProperty({}, namespace, nextRefinement), page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page); } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) { var index = getIndex(context); var refinements = hasMultipleIndex(context) && (0, _has3.default)(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && (0, _has3.default)(searchState, id); if (refinements) { var currentRefinement = hasMultipleIndex(context) ? (0, _get3.default)(searchState.indices[index], id) : (0, _get3.default)(searchState, id); return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var index = getIndex(context); return hasMultipleIndex(context) ? (0, _omit3.default)(searchState, 'indices.' + index + '.' + id) : (0, _omit3.default)(searchState, '' + id); } /***/ }), /* 6 */ /***/ (function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }), /* 7 */ /***/ (function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), getRawTag = __webpack_require__(157), objectToString = __webpack_require__(184); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(88), baseKeys = __webpack_require__(76), isArrayLike = __webpack_require__(11); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(136), getValue = __webpack_require__(159); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isLength = __webpack_require__(48); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; /***/ }), /* 12 */ /***/ (function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(265), baseMatchesProperty = __webpack_require__(266), identity = __webpack_require__(24), isArray = __webpack_require__(0), property = __webpack_require__(335); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNames; var _classnames = __webpack_require__(418); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var prefix = 'ais'; function classNames(block) { return function () { for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } return { className: (0, _classnames2.default)(elements.filter(function (element) { return element !== undefined && element !== false; }).map(function (element) { return prefix + '-' + block + '__' + element; })) }; }; } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { var baseKeys = __webpack_require__(76), getTag = __webpack_require__(56), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isArrayLike = __webpack_require__(11), isBuffer = __webpack_require__(26), isPrototype = __webpack_require__(37), isTypedArray = __webpack_require__(36); /** `Object#toString` result references. */ var mapTag = '[object Map]', setTag = '[object Set]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } module.exports = isEmpty; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), baseMap = __webpack_require__(138), isArray = __webpack_require__(0); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, baseIteratee(iteratee, 3)); } module.exports = map; /***/ }), /* 18 */ /***/ (function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObject = __webpack_require__(6); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24), overRest = __webpack_require__(185), setToString = __webpack_require__(100); /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } module.exports = baseRest; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isKey = __webpack_require__(72), stringToPath = __webpack_require__(196), toString = __webpack_require__(75); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(90), baseAssignValue = __webpack_require__(42); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }), /* 24 */ /***/ (function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(134), isObjectLike = __webpack_require__(7); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3), stubFalse = __webpack_require__(206); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(169), listCacheDelete = __webpack_require__(170), listCacheGet = __webpack_require__(171), listCacheHas = __webpack_require__(172), listCacheSet = __webpack_require__(173); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(166); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }), /* 31 */ /***/ (function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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; }; exports.default = translatable; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); var _propTypes = __webpack_require__(403); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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 translatable(defaultTranslations) { return function (Composed) { function Translatable(props) { var translations = props.translations; var otherProps = _objectWithoutProperties(props, ['translations']); var translate = function translate(key) { for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } var translation = translations && (0, _has3.default)(translations, key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { return translation.apply(undefined, params); } return translation; }; return _react2.default.createElement(Composed, _extends({ translate: translate }, otherProps)); } Translatable.displayName = 'Translatable(' + (0, _utils.getDisplayName)(Composed) + ')'; Translatable.propTypes = { translations: (0, _propTypes.withKeysPropType)(Object.keys(defaultTranslations)) }; return Translatable; }; } /***/ }), /* 34 */ /***/ (function(module, exports) { /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } module.exports = replaceHolders; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(85), baseEach = __webpack_require__(63), castFunction = __webpack_require__(143), isArray = __webpack_require__(0); /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, castFunction(iteratee)); } module.exports = forEach; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(137), baseUnary = __webpack_require__(45), nodeUtil = __webpack_require__(183); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; /***/ }), /* 37 */ /***/ (function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseClone = __webpack_require__(256), baseUnset = __webpack_require__(278), castPath = __webpack_require__(21), copyObject = __webpack_require__(22), customOmitClone = __webpack_require__(302), flatRest = __webpack_require__(155), getAllKeysIn = __webpack_require__(96); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); module.exports = omit; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(174), mapCacheDelete = __webpack_require__(175), mapCacheGet = __webpack_require__(176), mapCacheHas = __webpack_require__(177), mapCacheSet = __webpack_require__(178); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), stackClear = __webpack_require__(191), stackDelete = __webpack_require__(192), stackGet = __webpack_require__(193), stackHas = __webpack_require__(194), stackSet = __webpack_require__(195); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(152); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(132), keys = __webpack_require__(9); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(130), baseIsNaN = __webpack_require__(263), strictIndexOf = __webpack_require__(317); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }), /* 45 */ /***/ (function(module, exports) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }), /* 46 */ /***/ (function(module, exports) { /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } module.exports = getHolder; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { var createFind = __webpack_require__(298), findIndex = __webpack_require__(198); /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); module.exports = find; /***/ }), /* 48 */ /***/ (function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), getPrototype = __webpack_require__(70), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isArray = __webpack_require__(0), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } module.exports = isString; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(88), baseKeysIn = __webpack_require__(264), isArrayLike = __webpack_require__(11); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(89), baseEach = __webpack_require__(63), baseIteratee = __webpack_require__(13), baseReduce = __webpack_require__(273), isArray = __webpack_require__(0); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach); } module.exports = reduce; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(219); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }), /* 54 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 55 */ /***/ (function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if(!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { var DataView = __webpack_require__(122), Map = __webpack_require__(39), Promise = __webpack_require__(125), Set = __webpack_require__(126), WeakMap = __webpack_require__(84), baseGetTag = __webpack_require__(8), toSource = __webpack_require__(80); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(133), hasPath = __webpack_require__(97); /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } module.exports = has; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defer = undefined; var _isPlainObject2 = __webpack_require__(49); var _isPlainObject3 = _interopRequireDefault(_isPlainObject2); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); exports.shallowEqual = shallowEqual; exports.isSpecialClick = isSpecialClick; exports.capitalize = capitalize; exports.assertFacetDefined = assertFacetDefined; exports.getDisplayName = getDisplayName; exports.removeEmptyKey = removeEmptyKey; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } 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. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); } function capitalize(key) { return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1); } function assertFacetDefined(searchParameters, searchResults, facet) { var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet); var wasReceived = Boolean(searchResults.getFacetByName(facet)); if (searchResults.nbHits > 0 && wasRequested && !wasReceived) { // eslint-disable-next-line no-console console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.'); } } function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; } var resolved = Promise.resolve(); var defer = exports.defer = function defer(f) { resolved.then(f); }; function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if ((0, _isEmpty3.default)(value) && (0, _isPlainObject3.default)(value)) { delete obj[key]; } else if ((0, _isPlainObject3.default)(value)) { removeEmptyKey(value); } }); return obj; } /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(40), setCacheAdd = __webpack_require__(186), setCacheHas = __webpack_require__(187); /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; module.exports = SetCache; /***/ }), /* 60 */ /***/ (function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }), /* 61 */ /***/ (function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); module.exports = baseCreate; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43), createBaseEach = __webpack_require__(294); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), toKey = __webpack_require__(23); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(135), isObjectLike = __webpack_require__(7); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), arrayMap = __webpack_require__(12), isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }), /* 67 */ /***/ (function(module, exports) { /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } module.exports = cacheHas; /***/ }), /* 68 */ /***/ (function(module, exports) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), isObject = __webpack_require__(6); /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } module.exports = createCtor; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(86), stubArray = __webpack_require__(107); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44), toInteger = __webpack_require__(53); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } module.exports = indexOf; /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(66); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(37), nativeKeys = __webpack_require__(182); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arraySome = __webpack_require__(128), cacheHas = __webpack_require__(67); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 79 */ /***/ (function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }), /* 80 */ /***/ (function(module, exports) { /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var keys = __webpack_require__(9); var intersection = __webpack_require__(328); var forOwn = __webpack_require__(326); var forEach = __webpack_require__(35); var filter = __webpack_require__(102); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var omit = __webpack_require__(38); var indexOf = __webpack_require__(74); var isNaN = __webpack_require__(218); var isArray = __webpack_require__(0); var isEmpty = __webpack_require__(16); var isEqual = __webpack_require__(104); var isUndefined = __webpack_require__(203); var isString = __webpack_require__(50); var isFunction = __webpack_require__(19); var find = __webpack_require__(47); var trim = __webpack_require__(207); var defaults = __webpack_require__(101); var merge = __webpack_require__(105); var valToNumber = __webpack_require__(246); var filterState = __webpack_require__(242); var RefinementList = __webpack_require__(241); /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find(array, function(currentValue) { return isEqual(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * seperated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each facetted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach(numberKeys, function(k) { var value = partialState[k]; if (isString(value)) { var parsedValue = parseFloat(value); numbers[k] = isNaN(parsedValue) ? value : parsedValue; } }); if (partialState.numericRefinements) { var numericRefinements = {}; forEach(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach(operators, function(values, operator) { var parsedValues = map(values, function(v) { if (isArray(v)) { return map(v, function(vPrime) { if (isString(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optionnal string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) facetting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive facetting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge({}, this.numericRefinements); mod[attribute] = merge({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optionnal string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined(attribute)) { return {}; } else if (isString(attribute)) { return omit(this.numericRefinements, attribute); } else if (isFunction(attribute)) { return reduce(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach(operators, function(values, operator) { var outValues = []; forEach(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty(outValues)) operatorList[operator] = outValues; }); if (!isEmpty(operatorList)) memo[key] = operatorList; return memo; }, {}); } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the facetting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the facetting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the facetted attribute. * @method * @param {string} facet name of the attribute used for facetting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for facetting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for facetting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value, optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for facetting * @param {string} [value] optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value optionnal, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value optionnal, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined(value) && isUndefined(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined(this.numericRefinements[attribute][operator]); if (isUndefined(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber(value); var isAttributeValueDefined = !isUndefined( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection( keys(this.numericRefinements), this.disjunctiveFacets ); return keys(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map(this.hierarchicalFacets, 'name'), keys(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter(this.disjunctiveFacets, function(f) { return indexOf(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn(this, function(paramValue, paramName) { if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys(params); forEach(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map(path, trim); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ module.exports = SearchParameters; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), baseLodash = __webpack_require__(92); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; module.exports = LazyWrapper; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }), /* 85 */ /***/ (function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }), /* 86 */ /***/ (function(module, exports) { /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(142), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isIndex = __webpack_require__(31), isTypedArray = __webpack_require__(36); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; /***/ }), /* 89 */ /***/ (function(module, exports) { /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } module.exports = arrayReduce; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), eq = __webpack_require__(18); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), isArray = __webpack_require__(0); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }), /* 92 */ /***/ (function(module, exports) { /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } module.exports = baseLodash; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { var Uint8Array = __webpack_require__(83); /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } module.exports = cloneArrayBuffer; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(140), createBind = __webpack_require__(296), createCurry = __webpack_require__(297), createHybrid = __webpack_require__(150), createPartial = __webpack_require__(300), getData = __webpack_require__(156), mergeData = __webpack_require__(312), setData = __webpack_require__(188), setWrapToString = __webpack_require__(189), toInteger = __webpack_require__(53); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } module.exports = createWrap; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(91), getSymbols = __webpack_require__(71), keys = __webpack_require__(9); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(91), getSymbolsIn = __webpack_require__(158), keysIn = __webpack_require__(51); /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } module.exports = getAllKeysIn; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isIndex = __webpack_require__(31), isLength = __webpack_require__(48), toKey = __webpack_require__(23); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; /***/ }), /* 98 */ /***/ (function(module, exports) { /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }), /* 99 */ /***/ (function(module, exports) { /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(275), shortOut = __webpack_require__(190); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), assignInWith = __webpack_require__(322), baseRest = __webpack_require__(20), customDefaultsAssignIn = __webpack_require__(301); /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, customDefaultsAssignIn); return apply(assignInWith, undefined, args); }); module.exports = defaults; /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(86), baseFilter = __webpack_require__(258), baseIteratee = __webpack_require__(13), isArray = __webpack_require__(0); /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, baseIteratee(predicate, 3)); } module.exports = filter; /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(11), isObjectLike = __webpack_require__(7); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(65); /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } module.exports = isEqual; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { var baseMerge = __webpack_require__(267), createAssigner = __webpack_require__(149); /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); module.exports = merge; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { var baseOrderBy = __webpack_require__(269), isArray = __webpack_require__(0); /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } module.exports = orderBy; /***/ }), /* 107 */ /***/ (function(module, exports) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); exports.arrayToObject = function (source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function (target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { target[source] = true; } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (Object.prototype.hasOwnProperty.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function (str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D || // - c === 0x2E || // . c === 0x5F || // _ c === 0x7E || // ~ (c >= 0x30 && c <= 0x39) || // 0-9 (c >= 0x41 && c <= 0x5A) || // a-z (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function (obj, references) { if (typeof obj !== 'object' || obj === null) { return obj; } var refs = references || []; var lookup = refs.indexOf(obj); if (lookup !== -1) { return refs[lookup]; } refs.push(obj); if (Array.isArray(obj)) { var compacted = []; for (var i = 0; i < obj.length; ++i) { if (obj[i] && typeof obj[i] === 'object') { compacted.push(exports.compact(obj[i], refs)); } else if (typeof obj[i] !== 'undefined') { compacted.push(obj[i]); } } return compacted; } var keys = Object.keys(obj); keys.forEach(function (key) { obj[key] = exports.compact(obj[key], refs); }); return obj; }; exports.isRegExp = function (obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function (obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; /***/ }), /* 109 */ /***/ (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.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; }; /***/ }), /* 110 */ /***/ (function(module, exports) { var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { var basePick = __webpack_require__(270), flatRest = __webpack_require__(155); /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); module.exports = pick; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); 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; } /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - Name of the attribute for faceting * @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied */ function getId(props) { return props.attributeName; } var namespace = 'range'; function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), {}, function (currentRefinement) { var min = currentRefinement.min; var max = currentRefinement.max; if (typeof min === 'string') { min = parseInt(min, 10); } if (typeof max === 'string') { max = parseInt(max, 10); } return { min: min, max: max }; }); } function _refine(props, searchState, nextRefinement, context) { if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) { throw new Error("You can't provide non finite values to the range connector"); } var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaRange', propTypes: { id: _propTypes2.default.string, attributeName: _propTypes2.default.string.isRequired, defaultRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number.isRequired, max: _propTypes2.default.number.isRequired }), min: _propTypes2.default.number, max: _propTypes2.default.number }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var min = props.min; var max = props.max; var hasMin = typeof min !== 'undefined'; var hasMax = typeof max !== 'undefined'; var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!hasMin || !hasMax) { if (!results) { return { canRefine: false }; } var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; if (!stats) { return { canRefine: false }; } if (!hasMin) { min = stats.min; } if (!hasMax) { max = stats.max; } } var count = results ? results.getFacetValues(attributeName).map(function (v) { return { value: v.name, count: v.count }; }) : []; var _getCurrentRefinement = getCurrentRefinement(props, searchState, this.context); var _getCurrentRefinement2 = _getCurrentRefinement.min; var valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2; var _getCurrentRefinement3 = _getCurrentRefinement.max; var valueMax = _getCurrentRefinement3 === undefined ? max : _getCurrentRefinement3; return { min: min, max: max, currentRefinement: { min: valueMin, max: valueMax }, count: count, canRefine: count.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState, this.context); params = params.addDisjunctiveFacet(attributeName); var min = currentRefinement.min; var max = currentRefinement.max; if (typeof min !== 'undefined') { params = params.addNumericRefinement(attributeName, '>=', min); } if (typeof max !== 'undefined') { params = params.addNumericRefinement(attributeName, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); var item = void 0; var hasMin = typeof currentRefinement.min !== 'undefined'; var hasMax = typeof currentRefinement.max !== 'undefined'; if (hasMin || hasMax) { var itemLabel = ''; if (hasMin) { itemLabel += currentRefinement.min + ' <= '; } itemLabel += props.attributeName; if (hasMax) { itemLabel += ' <= ' + currentRefinement.max; } item = { label: itemLabel, currentRefinement: currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _cleanUp(props, nextState, _this.context); } }; } return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: item ? [item] : [] }; } }); /***/ }), /* 113 */ /***/ (function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(239); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(238); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54), __webpack_require__(109))) /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var compact = __webpack_require__(324); var indexOf = __webpack_require__(74); var findIndex = __webpack_require__(198); var get = __webpack_require__(73); var sumBy = __webpack_require__(337); var find = __webpack_require__(47); var includes = __webpack_require__(327); var map = __webpack_require__(17); var orderBy = __webpack_require__(106); var defaults = __webpack_require__(101); var merge = __webpack_require__(105); var isArray = __webpack_require__(0); var isFunction = __webpack_require__(19); var partial = __webpack_require__(332); var partialRight = __webpack_require__(333); var formatSort = __webpack_require__(116); var generateHierarchicalTree = __webpack_require__(244); /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the facetting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objets matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} value the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric fitlers. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach(result.facets, function(facetResults, dfacet) { var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state)); this.facets = compact(this.facets); this.disjunctiveFacets = compact(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the attribute facetted * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find(this.facets, predicate) || find(this.disjunctiveFacets, predicate) || find(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the facetted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find(results.facets, predicate); if (!facet) return []; return map(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map(node.data, partial(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (isArray(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (isArray(facetValues)) { return orderBy(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight(orderBy, order[0], order[1]), facetValues); } else if (isFunction(options.sortBy)) { if (isArray(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the facetted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach(state.facetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach(state.facetsExcludes, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach(state.numericRefinements, function(operators, attributeName) { forEach(operators, function(values, operator) { forEach(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find(resultsFacets, {name: attributeName}); var count = get(facet, 'data[' + name + ']'); var exhaustive = get(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find(facet.data, {name: splitted[i]}); } var count = get(facet, 'count'); var exhaustive = get(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } module.exports = SearchResults; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var reduce = __webpack_require__(52); var find = __webpack_require__(47); var startsWith = __webpack_require__(336); /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ module.exports = function formatSort(sortBy, defaults) { return reduce(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find(defaults, function(predicate) { return startsWith(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var shortener = __webpack_require__(243); var SearchParameters = __webpack_require__(81); var qs = __webpack_require__(342); var bind = __webpack_require__(323); var forEach = __webpack_require__(35); var pick = __webpack_require__(111); var map = __webpack_require__(17); var mapKeys = __webpack_require__(329); var mapValues = __webpack_require__(330); var isString = __webpack_require__(50); var isPlainObject = __webpack_require__(49); var isArray = __webpack_require__(0); var invert = __webpack_require__(201); var encode = __webpack_require__(108).encode; function recursiveEncode(input) { if (isPlainObject(input)) { return mapValues(input, recursiveEncode); } if (isArray(input)) { return map(input, recursiveEncode); } if (isString(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ exports.getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert(mapping); var partialStateWithPrefix = qs.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState); return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ exports.getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert(mapping); var foreignConfig = {}; var config = qs.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ exports.getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (moreAttributes) { var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = qs.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return qs.stringify(encodedState, {encode: safe, sort: sort}); }; /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = '2.19.0'; /***/ }), /* 119 */ /***/ (function(module, exports) { module.exports = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 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; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * 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 (false) { 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; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(160), hashDelete = __webpack_require__(161), hashGet = __webpack_require__(162), hashHas = __webpack_require__(163), hashSet = __webpack_require__(164); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), baseLodash = __webpack_require__(92); /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; module.exports = LodashWrapper; /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }), /* 127 */ /***/ (function(module, exports) { /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } module.exports = arrayIncludesWith; /***/ }), /* 128 */ /***/ (function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }), /* 129 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), eq = __webpack_require__(18); /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignMergeValue; /***/ }), /* 130 */ /***/ (function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), isFlattenable = __webpack_require__(310); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(295); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }), /* 133 */ /***/ (function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } module.exports = baseHas; /***/ }), /* 134 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; /***/ }), /* 135 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), equalArrays = __webpack_require__(77), equalByTag = __webpack_require__(153), equalObjects = __webpack_require__(154), getTag = __webpack_require__(56), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isTypedArray = __webpack_require__(36); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isMasked = __webpack_require__(167), isObject = __webpack_require__(6), toSource = __webpack_require__(80); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; /***/ }), /* 137 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isLength = __webpack_require__(48), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(63), isArrayLike = __webpack_require__(11); /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } module.exports = baseMap; /***/ }), /* 139 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64), baseSet = __webpack_require__(274), castPath = __webpack_require__(21); /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } module.exports = basePickBy; /***/ }), /* 140 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24), metaMap = __webpack_require__(181); /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; module.exports = baseSetData; /***/ }), /* 141 */ /***/ (function(module, exports) { /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } module.exports = baseSlice; /***/ }), /* 142 */ /***/ (function(module, exports) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }), /* 143 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24); /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } module.exports = castFunction; /***/ }), /* 144 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93); /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } module.exports = cloneTypedArray; /***/ }), /* 146 */ /***/ (function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } module.exports = composeArgs; /***/ }), /* 147 */ /***/ (function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } module.exports = composeArgsRight; /***/ }), /* 148 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }), /* 149 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), isIterateeCall = __webpack_require__(217); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; /***/ }), /* 150 */ /***/ (function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(146), composeArgsRight = __webpack_require__(147), countHolders = __webpack_require__(293), createCtor = __webpack_require__(69), createRecurry = __webpack_require__(151), getHolder = __webpack_require__(46), reorder = __webpack_require__(316), replaceHolders = __webpack_require__(34), root = __webpack_require__(3); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_ARY_FLAG = 128, WRAP_FLIP_FLAG = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } module.exports = createHybrid; /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { var isLaziable = __webpack_require__(311), setData = __webpack_require__(188), setWrapToString = __webpack_require__(189); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } module.exports = createRecurry; /***/ }), /* 152 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }), /* 153 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), Uint8Array = __webpack_require__(83), eq = __webpack_require__(18), equalArrays = __webpack_require__(77), mapToArray = __webpack_require__(98), setToArray = __webpack_require__(99); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(95); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects; /***/ }), /* 155 */ /***/ (function(module, exports, __webpack_require__) { var flatten = __webpack_require__(199), overRest = __webpack_require__(185), setToString = __webpack_require__(100); /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } module.exports = flatRest; /***/ }), /* 156 */ /***/ (function(module, exports, __webpack_require__) { var metaMap = __webpack_require__(181), noop = __webpack_require__(331); /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; module.exports = getData; /***/ }), /* 157 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), getPrototype = __webpack_require__(70), getSymbols = __webpack_require__(71), stubArray = __webpack_require__(107); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; module.exports = getSymbolsIn; /***/ }), /* 159 */ /***/ (function(module, exports) { /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } module.exports = hashClear; /***/ }), /* 161 */ /***/ (function(module, exports) { /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } module.exports = hashDelete; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } module.exports = hashHas; /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), getPrototype = __webpack_require__(70), isPrototype = __webpack_require__(37); /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } module.exports = initCloneObject; /***/ }), /* 166 */ /***/ (function(module, exports) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(148); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; /***/ }), /* 168 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }), /* 169 */ /***/ (function(module, exports) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } module.exports = listCacheClear; /***/ }), /* 170 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } module.exports = listCacheDelete; /***/ }), /* 171 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }), /* 172 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }), /* 173 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }), /* 174 */ /***/ (function(module, exports, __webpack_require__) { var Hash = __webpack_require__(123), ListCache = __webpack_require__(28), Map = __webpack_require__(39); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; /***/ }), /* 175 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } module.exports = mapCacheSet; /***/ }), /* 179 */ /***/ (function(module, exports) { /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; /***/ }), /* 180 */ /***/ (function(module, exports, __webpack_require__) { var memoize = __webpack_require__(205); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }), /* 181 */ /***/ (function(module, exports, __webpack_require__) { var WeakMap = __webpack_require__(84); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; module.exports = metaMap; /***/ }), /* 182 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(78); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }), /* 184 */ /***/ (function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }), /* 185 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; /***/ }), /* 186 */ /***/ (function(module, exports) { /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; /***/ }), /* 187 */ /***/ (function(module, exports) { /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; /***/ }), /* 188 */ /***/ (function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(140), shortOut = __webpack_require__(190); /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); module.exports = setData; /***/ }), /* 189 */ /***/ (function(module, exports, __webpack_require__) { var getWrapDetails = __webpack_require__(305), insertWrapDetails = __webpack_require__(309), setToString = __webpack_require__(100), updateWrapDetails = __webpack_require__(320); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } module.exports = setWrapToString; /***/ }), /* 190 */ /***/ (function(module, exports) { /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; /***/ }), /* 191 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear; /***/ }), /* 192 */ /***/ (function(module, exports) { /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete; /***/ }), /* 193 */ /***/ (function(module, exports) { /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; /***/ }), /* 194 */ /***/ (function(module, exports) { /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; /***/ }), /* 195 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), Map = __webpack_require__(39), MapCache = __webpack_require__(40); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet; /***/ }), /* 196 */ /***/ (function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(180); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }), /* 197 */ /***/ (function(module, exports) { /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; /***/ }), /* 198 */ /***/ (function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(130), baseIteratee = __webpack_require__(13), toInteger = __webpack_require__(53); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, baseIteratee(predicate, 3), index); } module.exports = findIndex; /***/ }), /* 199 */ /***/ (function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(131); /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } module.exports = flatten; /***/ }), /* 200 */ /***/ (function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(259), hasPath = __webpack_require__(97); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }), /* 201 */ /***/ (function(module, exports, __webpack_require__) { var constant = __webpack_require__(197), createInverter = __webpack_require__(299), identity = __webpack_require__(24); /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); module.exports = invert; /***/ }), /* 202 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var numberTag = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } module.exports = isNumber; /***/ }), /* 203 */ /***/ (function(module, exports) { /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } module.exports = isUndefined; /***/ }), /* 204 */ /***/ (function(module, exports) { /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } module.exports = last; /***/ }), /* 205 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(40); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }), /* 206 */ /***/ (function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }), /* 207 */ /***/ (function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(66), castSlice = __webpack_require__(281), charsEndIndex = __webpack_require__(282), charsStartIndex = __webpack_require__(283), stringToArray = __webpack_require__(318), toString = __webpack_require__(75); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } module.exports = trim; /***/ }), /* 208 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var emptyFunction = __webpack_require__(120); var invariant = __webpack_require__(121); module.exports = function() { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { invariant( false, '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' ); }; shim.isRequired = shim; function getShim() { return shim; }; var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 209 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var replace = String.prototype.replace; var percentTwenties = /%20/g; module.exports = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; /***/ }), /* 210 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items); } } return res; }, []); return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); /***/ }), /* 211 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _highlight = __webpack_require__(237); var _highlight2 = _interopRequireDefault(_highlight); var _highlightTags = __webpack_require__(213); var _highlightTags2 = _interopRequireDefault(_highlightTags); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var highlight = function highlight(_ref) { var attributeName = _ref.attributeName; var hit = _ref.hit; var highlightProperty = _ref.highlightProperty; return (0, _highlight2.default)({ attributeName: attributeName, hit: hit, preTag: _highlightTags2.default.highlightPreTag, postTag: _highlightTags2.default.highlightPostTag, highlightProperty: highlightProperty }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`. * @example * const CustomHighlight = connectHighlight(({highlight, attributeName, hit, highlightProperty) => { * const parsedHit = highlight({attributeName, hit, highlightProperty}); * return parsedHit.map(part => { * if(part.isHighlighted) return <em>{part.value}</em>; * return part.value: * }); * }); */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /***/ }), /* 212 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _SearchBox = __webpack_require__(346); var _SearchBox2 = _interopRequireDefault(_SearchBox); 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 itemsPropType = _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.any, label: _propTypes2.default.string.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var List = function (_Component) { _inherits(List, _Component); function List() { _classCallCheck(this, List); var _this = _possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this)); _this.defaultProps = { isFromSearch: false }; _this.onShowMoreClick = function () { _this.setState(function (state) { return { extended: !state.extended }; }); }; _this.getLimit = function () { var _this$props = _this.props; var limitMin = _this$props.limitMin; var limitMax = _this$props.limitMax; var extended = _this.state.extended; return extended ? limitMax : limitMin; }; _this.resetQuery = function () { _this.setState({ query: '' }); }; _this.renderItem = function (item, resetQuery) { var items = item.items && _react2.default.createElement( 'div', _this.props.cx('itemItems'), item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }) ); return _react2.default.createElement( 'div', _extends({ key: item.key || item.label }, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')), _this.props.renderItem(item, resetQuery), items ); }; _this.state = { extended: false, query: '' }; return _this; } _createClass(List, [{ key: 'renderShowMore', value: function renderShowMore() { var _props = this.props; var showMore = _props.showMore; var translate = _props.translate; var cx = _props.cx; var extended = this.state.extended; var disabled = this.props.limitMin >= this.props.items.length; if (!showMore) { return null; } return _react2.default.createElement( 'button', _extends({ disabled: disabled }, cx('showMore', disabled && 'showMoreDisabled'), { onClick: this.onShowMoreClick }), translate('showMore', extended) ); } }, { key: 'renderSearchBox', value: function renderSearchBox() { var _this2 = this; var _props2 = this.props; var cx = _props2.cx; var searchForItems = _props2.searchForItems; var isFromSearch = _props2.isFromSearch; var translate = _props2.translate; var items = _props2.items; var selectItem = _props2.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? _react2.default.createElement( 'div', cx('noResults'), translate('noResults') ) : null; return _react2.default.createElement( 'div', cx('SearchBox'), _react2.default.createElement(_SearchBox2.default, { currentRefinement: this.state.query, refine: function refine(value) { _this2.setState({ query: value }); searchForItems(value); }, focusShortcuts: [], translate: translate, onSubmit: function onSubmit(e) { e.preventDefault(); e.stopPropagation(); if (isFromSearch) { selectItem(items[0], _this2.resetQuery); } } }), noResults ); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props; var cx = _props3.cx; var items = _props3.items; var withSearchBox = _props3.withSearchBox; var canRefine = _props3.canRefine; var searchBox = withSearchBox ? this.renderSearchBox() : null; if (items.length === 0) { return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), searchBox ); } // Always limit the number of items we show on screen, since the actual // number of retrieved items might vary with the `maxValuesPerFacet` config // option. var limit = this.getLimit(); return _react2.default.createElement( 'div', cx('root', !this.props.canRefine && 'noRefinement'), searchBox, _react2.default.createElement( 'div', cx('items'), items.slice(0, limit).map(function (item) { return _this3.renderItem(item, _this3.resetQuery); }) ), this.renderShowMore() ); } }]); return List; }(_react.Component); List.propTypes = { cx: _propTypes2.default.func.isRequired, // Only required with showMore. translate: _propTypes2.default.func, items: itemsPropType, renderItem: _propTypes2.default.func.isRequired, selectItem: _propTypes2.default.func, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, limit: _propTypes2.default.number, show: _propTypes2.default.func, searchForItems: _propTypes2.default.func, withSearchBox: _propTypes2.default.bool, isFromSearch: _propTypes2.default.bool, canRefine: _propTypes2.default.bool }; exports.default = List; /***/ }), /* 213 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var timestamp = Date.now().toString(); exports.default = { highlightPreTag: "<ais-highlight-" + timestamp + ">", highlightPostTag: "</ais-highlight-" + timestamp + ">" }; /***/ }), /* 214 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var AlgoliaSearchHelper = __webpack_require__(245); var SearchParameters = __webpack_require__(81); var SearchResults = __webpack_require__(115); /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new AlgoliaSearchHelper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = __webpack_require__(118); /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = __webpack_require__(117); module.exports = algoliasearchHelper; /***/ }), /* 215 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // This file hosts our error definitions // We use custom error "types" so that we can act on them when we need it // e.g.: if error instanceof errors.UnparsableJSON then.. var inherits = __webpack_require__(349); function AlgoliaSearchError(message, extraProperties) { var forEach = __webpack_require__(110); var error = this; // try to get a stacktrace if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old'; } this.name = 'AlgoliaSearchError'; this.message = message || 'Unknown error'; if (extraProperties) { forEach(extraProperties, function addToErrorObject(value, key) { error[key] = value; }); } } inherits(AlgoliaSearchError, Error); function createCustomError(name, message) { function AlgoliaSearchCustomError() { var args = Array.prototype.slice.call(arguments, 0); // custom message not set, use default if (typeof args[0] !== 'string') { args.unshift(message); } AlgoliaSearchError.apply(this, args); this.name = 'AlgoliaSearch' + name + 'Error'; } inherits(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place module.exports = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timedout before getting a response' ), Network: createCustomError( 'Network', 'Network issue, see err.more for details' ), JSONPScriptFail: createCustomError( 'JSONPScriptFail', '<script> was loaded but did not call our provided callback' ), JSONPScriptError: createCustomError( 'JSONPScriptError', '<script> unable to load due to an `error` event on it' ), Unknown: createCustomError( 'Unknown', 'Unknown error occured' ) }; /***/ }), /* 216 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __webpack_require__(419); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109))) /***/ }), /* 217 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18), isArrayLike = __webpack_require__(11), isIndex = __webpack_require__(31), isObject = __webpack_require__(6); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }), /* 218 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(202); /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } module.exports = isNaN; /***/ }), /* 219 */ /***/ (function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(338); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } module.exports = toFinite; /***/ }), /* 220 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys2 = __webpack_require__(9); var _keys3 = _interopRequireDefault(_keys2); var _difference2 = __webpack_require__(325); var _difference3 = _interopRequireDefault(_difference2); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); 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 _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); 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 getId() { return 'configure'; } exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = (0, _omit3.default)(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = (0, _omit3.default)(props, 'children'); var nonPresentKeys = this._props ? (0, _difference3.default)((0, _keys3.default)(this._props), (0, _keys3.default)(props)) : []; this._props = props; var nextValue = _defineProperty({}, id, _extends({}, (0, _omit3.default)(nextSearchState[id], nonPresentKeys), items)); return (0, _indexUtils.refineValue)(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = (0, _indexUtils.getIndex)(this.context); var subState = (0, _indexUtils.hasMultipleIndex)(this.context) && searchState.indices ? searchState.indices[index] : searchState; var configureKeys = subState[id] ? Object.keys(subState[id]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = subState[id][item]; } return acc; }, {}); var nextValue = _defineProperty({}, id, configureState); return (0, _indexUtils.refineValue)(searchState, nextValue, this.context); } }); /***/ }), /* 221 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getId = undefined; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _algoliasearchHelper = __webpack_require__(214); var _indexUtils = __webpack_require__(5); 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; } var getId = exports.getId = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue(path, props, searchState, context) { var id = props.id; var attributes = props.attributes; var separator = props.separator; var rootPath = props.rootPath; var showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement(props, searchState, context); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new _algoliasearchHelper.SearchParameters({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue(value, limit, props, searchState, context) { return value.slice(0, limit).map(function (v) { return { label: v.name, value: getValue(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, limit, props, searchState, context) }; }); } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement || ''); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: _propTypes2.default.string, rootPath: _propTypes2.default.string, showParentLevel: _propTypes2.default.bool, defaultRefinement: _propTypes2.default.string, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var id = getId(props); var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: false }; } var limit = showMore ? limitMax : limitMin; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue(value.data, limit, props, searchState, this.context) : []; return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes; var separator = props.separator; var rootPath = props.rootPath; var showParentLevel = props.showParentLevel; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var id = getId(props); var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); var currentRefinement = getCurrentRefinement(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attributeName: rootAttribute, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /***/ }), /* 222 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var hits = results ? results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); /***/ }), /* 223 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); 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 getId() { return 'hitsPerPage'; } function getCurrentRefinement(props, searchState, context) { var id = getId(); return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: _propTypes2.default.number.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string, value: _propTypes2.default.number.isRequired })).isRequired, transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }), /* 224 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); 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 getId() { return 'page'; } function getCurrentRefinement(props, searchState, context) { var id = getId(); var page = 1; return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var hits = results.hits; var page = results.page; var nbPages = results.nbPages; var hitsPerPage = results.hitsPerPage; if (page === 0) { this._allResults = hits; } else { var previousPage = this._allResults.length / hitsPerPage - 1; if (page > previousPage) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits)); } else if (page < previousPage) { this._allResults = hits; } // If it is the same page we do not touch the page result list } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId(); var nextPage = getCurrentRefinement(props, searchState, this.context) + 1; var nextValue = _defineProperty({}, id, nextPage); var resetPage = false; return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage); } }); /***/ }), /* 225 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _orderBy2 = __webpack_require__(106); var _orderBy3 = _interopRequireDefault(_orderBy2); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); 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; } var namespace = 'menu'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue(name, props, searchState, context) { var currentRefinement = getCurrentRefinement(props, searchState, context); return name === currentRefinement ? '' : name; } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } var sortBy = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user tha ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [withSearchBox=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaMenu', propTypes: { attributeName: _propTypes2.default.string.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, defaultRefinement: _propTypes2.default.string, transformItems: _propTypes2.default.func, withSearchBox: _propTypes2.default.bool, searchForFacetValues: _propTypes2.default.bool }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.'); } // Search For Facet Values is not available with derived helper (used for multi index search) if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) { return { label: v.name, value: getValue(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = withSearchBox && !isFromSearch ? (0, _orderBy3.default)(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters.addDisjunctiveFacet(attributeName); var currentRefinement = getCurrentRefinement(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: currentRefinement === null ? [] : [{ label: props.attributeName + ': ' + currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _refine(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); /***/ }), /* 226 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _find3 = __webpack_require__(47); var _find4 = _interopRequireDefault(_find3); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); 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 stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'); var _value$split2 = _slicedToArray(_value$split, 2); var startStr = _value$split2[0]; var endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace = 'multiRange'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attributeName, results, value) { var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine(props, searchState, nextRefinement, context) { var nextValue = _defineProperty({}, getId(props, searchState), nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } /** * connectMultiRange connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectMultiRange * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @kind connector * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaMultiRange', propTypes: { id: _propTypes2.default.string, attributeName: _propTypes2.default.string.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.node, start: _propTypes2.default.number, end: _propTypes2.default.number })).isRequired, transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState, this.context); var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId(props), results, value) : false }; }); var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var refinedItem = (0, _find4.default)(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: (0, _isEmpty3.default)(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var _parseItem = parseItem(getCurrentRefinement(props, searchState, this.context)); var start = _parseItem.start; var end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attributeName); if (start) { searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var value = getCurrentRefinement(props, searchState, this.context); var items = []; var index = (0, _indexUtils.getIndex)(this.context); if (value !== '') { var _find2 = (0, _find4.default)(props.items, function (item) { return stringifyItem(item) === value; }); var label = _find2.label; items.push({ label: props.attributeName + ': ' + label, attributeName: props.attributeName, currentRefinement: label, value: function value(nextState) { return _refine(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); /***/ }), /* 227 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); 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 getId() { return 'page'; } function getCurrentRefinement(props, searchState, context) { var id = getId(); var page = 1; return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine(props, searchState, nextPage, context) { var id = getId(); var nextValue = _defineProperty({}, id, nextPage); var resetPage = false; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage); } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }), /* 228 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps() { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /***/ }), /* 229 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); 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; } var namespace = 'refinementList'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue(name, props, searchState, context) { var currentRefinement = getCurrentRefinement(props, searchState, context); var isAnewValue = currentRefinement.indexOf(name) === -1; var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates : currentRefinement.filter(function (selectedValue) { return selectedValue !== name; }); // cannot use .splice(), it mutates return nextRefinement; } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); // Setting the value to an empty string ensures that it is persisted in // the URL as an empty value. // This is necessary in the case where `defaultRefinement` contains one // item and we try to deselect it. `nextSelected` would be an empty array, // which would not be persisted to the URL. // {foo: ['bar']} => "foo[0]=bar" // {foo: []} => "" var nextValue = _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } /** * connectRefinementList connector provides the logic to build a widget that will * give the user the ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy = ['isRefined', 'count:desc', 'name:asc']; exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaRefinementList', propTypes: { id: _propTypes2.default.string, attributeName: _propTypes2.default.string.isRequired, operator: _propTypes2.default.oneOf(['and', 'or']), showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, defaultRefinement: _propTypes2.default.arrayOf(_propTypes2.default.string), withSearchBox: _propTypes2.default.bool, searchForFacetValues: _propTypes2.default.bool, // @deprecated transformItems: _propTypes2.default.func }, defaultProps: { operator: 'or', showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.'); } // Search For Facet Values is not available with derived helper (used for multi index search) if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, withSearchBox: withSearchBox }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) { return { label: v.name, value: getValue(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var operator = props.operator; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters[addKey](attributeName); return getCurrentRefinement(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attributeName, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var context = this.context; return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: getCurrentRefinement(props, searchState, context).length > 0 ? [{ attributeName: props.attributeName, label: props.attributeName + ': ', currentRefinement: getCurrentRefinement(props, searchState, context), value: function value(nextState) { return _refine(props, nextState, [], context); }, items: getCurrentRefinement(props, searchState, context).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement(props, nextState, context).filter(function (other) { return other !== item; }); return _refine(props, searchState, nextSelectedItems, context); } }; }) }] : [] }; } }); /***/ }), /* 230 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectScrollTo connector provides the logic to build a widget that will * let the page scroll to a certain point. * @name connectScrollTo * @kind connector * @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget. * @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: _propTypes2.default.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = (0, _indexUtils.getCurrentRefinementValue)(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); return { value: value }; } }); /***/ }), /* 231 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); 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 getId() { return 'query'; } function getCurrentRefinement(props, searchState, context) { var id = getId(props); return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine(props, searchState, nextRefinement, context) { var id = getId(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, getId()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query. * @name connectSearchBox * @kind connector * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the query to search for. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: _propTypes2.default.string }, getProvidedProps: function getProvidedProps(props, searchState) { return { currentRefinement: getCurrentRefinement(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /***/ }), /* 232 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); 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 getId() { return 'sortBy'; } function getCurrentRefinement(props, searchState, context) { var id = getId(props); return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * connectSortBy connector provides the logic to build a widget that will * displays a list of indexes allowing a user to change the hits are sorting. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: _propTypes2.default.string, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string, value: _propTypes2.default.string.isRequired })).isRequired, transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }), /* 233 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); /***/ }), /* 234 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); 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 getId(props) { return props.attributeName; } var namespace = 'toggle'; function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } /** * connectToggle connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization. * @name connectToggle * @kind connector * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName`. * @propType {boolean} [defaultChecked=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {boolean} currentRefinement - the refinement currently applied */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaToggle', propTypes: { label: _propTypes2.default.string, filter: _propTypes2.default.func, attributeName: _propTypes2.default.string, value: _propTypes2.default.any, defaultRefinement: _propTypes2.default.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var value = props.value; var filter = props.filter; var checked = getCurrentRefinement(props, searchState, this.context); if (checked) { if (attributeName) { searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var checked = getCurrentRefinement(props, searchState, this.context); var items = []; var index = (0, _indexUtils.getIndex)(this.context); if (checked) { items.push({ label: props.label, currentRefinement: props.label, attributeName: props.attributeName, value: function value(nextState) { return _refine(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); /***/ }), /* 235 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(211); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Highlight = __webpack_require__(380); var _Highlight2 = _interopRequireDefault(_Highlight); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Highlight * @kind widget * @propType {string} attributeName - the location of the highlighted attribute in the hit * @propType {object} hit - the hit object containing the highlighted attribute * @propType {string} [tagName='em'] - the tag to be used for highlighted parts of the hit * @example * import React from 'react'; * * import {InstantSearch, connectHits, Highlight} from 'InstantSearch'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Highlight attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Highlight2.default); /***/ }), /* 236 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); 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 Link = function (_Component) { _inherits(Link, _Component); function Link() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) { if ((0, _utils.isSpecialClick)(e)) { return; } _this.props.onClick(); e.preventDefault(); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Link, [{ key: 'render', value: function render() { return _react2.default.createElement('a', _extends({}, (0, _omit3.default)(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(_react.Component); Link.propTypes = { onClick: _propTypes2.default.func.isRequired }; exports.default = Link; /***/ }), /* 237 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _get2 = __webpack_require__(73); var _get3 = _interopRequireDefault(_get2); exports.default = parseAlgoliaHit; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attributeName - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseAlgoliaHit(_ref) { var _ref$preTag = _ref.preTag; var preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag; var _ref$postTag = _ref.postTag; var postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag; var highlightProperty = _ref.highlightProperty; var attributeName = _ref.attributeName; var hit = _ref.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = (0, _get3.default)(hit[highlightProperty], attributeName); var highlightedValue = !highlightObject ? '' : highlightObject.value; return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue }); } /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref2) { var preTag = _ref2.preTag; var postTag = _ref2.postTag; var highlightedValue = _ref2.highlightedValue; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } /***/ }), /* 238 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 239 */ /***/ (function(module, exports) { module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } /***/ }), /* 240 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util = __webpack_require__(114); var events = __webpack_require__(113); /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; module.exports = DerivedHelper; /***/ }), /* 241 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var isUndefined = __webpack_require__(203); var isString = __webpack_require__(50); var isFunction = __webpack_require__(19); var isEmpty = __webpack_require__(16); var defaults = __webpack_require__(101); var reduce = __webpack_require__(52); var filter = __webpack_require__(102); var omit = __webpack_require__(38); var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated prefinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * behaviors can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optionnal parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined(attribute)) { return {}; } else if (isString(attribute)) { return omit(refinementList, attribute); } else if (isFunction(attribute)) { return reduce(refinementList, function(memo, values, key) { var facetList = filter(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty(facetList)) memo[key] = facetList; return memo; }, {}); } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = __webpack_require__(74); var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; module.exports = lib; /***/ }), /* 242 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var filter = __webpack_require__(102); var map = __webpack_require__(17); var isEmpty = __webpack_require__(16); var indexOf = __webpack_require__(74); function filterState(state, filters) { var partialState = {}; var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf(attributes, '*') === -1) { forEach(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } module.exports = filterState; /***/ }), /* 243 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var invert = __webpack_require__(201); var keys = __webpack_require__(9); var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert(keys2Short); module.exports = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; /***/ }), /* 244 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = generateTrees; var last = __webpack_require__(204); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var orderBy = __webpack_require__(106); var trim = __webpack_require__(207); var find = __webpack_require__(47); var pickBy = __webpack_require__(334); var prepareHierarchicalFacetSortBy = __webpack_require__(116); function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy( map( pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim(last(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /***/ }), /* 245 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var SearchParameters = __webpack_require__(81); var SearchResults = __webpack_require__(115); var DerivedHelper = __webpack_require__(240); var requestBuilder = __webpack_require__(247); var util = __webpack_require__(114); var events = __webpack_require__(113); var flatten = __webpack_require__(199); var forEach = __webpack_require__(35); var isEmpty = __webpack_require__(16); var map = __webpack_require__(17); var url = __webpack_require__(117); var version = __webpack_require__(118); /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when the search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version); this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occcurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occured it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder._getQueries(tempState.index, tempState); if (cb) { return this.client.search( queries, function(err, content) { if (err) cb(err, null, tempState); else cb(err, new SearchResults(tempState, content.results), tempState); } ); } return this.client.search(queries).then(function(content) { return { content: new SearchResults(tempState, content.results), state: tempState, _originalResponse: content }; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {objet} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query insde the engine */ /** * Search for facet values based on an query and the name of a facetted attribute. This * triggers a search and will retrun a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} query the string query for the search * @param {string} facet the name of the facetted attribute * @return {promise<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query) { var state = this.state; var index = this.client.initIndex(this.state.index); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, this.state); return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) { content.facetHits = forEach(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this.state = this.state.setPage(0).setQuery(q); this._change(); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this.state = this.state.setPage(0).clearRefinements(name); this._change(); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this.state = this.state.setPage(0).clearTags(); this._change(); return this; }; /** * Adds a disjunctive filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value); this._change(); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Adds a filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).addExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this.state = this.state.setPage(0).addTagRefinement(tag); this._change(); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optionnals, triggering different behaviors: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Removes a disjunctive filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet); this._change(); return this; }; /** * Removes a filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).removeExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this.state = this.state.setPage(0).removeTagRefinement(tag); this._change(); return this; }; /** * Adds or removes an exclusion filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).toggleFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this.state = this.state.setPage(0).toggleTagRefinement(tag); this._change(); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this.state = this.state.setPage(page); this._change(); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this.state = this.state.setPage(0).setIndex(name); this._change(); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { var newState = this.state.setPage(0).setQueryParameter(parameter, value); if (this.state === newState) return this; this.state = newState; this._change(); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this.state = new SearchParameters(newState); this._change(); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optionnal filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optionnal parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific facetted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for facetting * @param {string} [value] optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for facetting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten(derivedQueries)); var queryId = this._queryId++; this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId)); }; /** * Transform the responses as sent by the server and transform them into a user * usable objet that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {Error} err error if any, null otherwise * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._lastQueryIdReceived = queryId; if (err) { this.emit('error', err); return; } var results = content.results; forEach(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults(state, specificResults); helper.emit('result', formattedResponse, state); }); }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function() { this.emit('change', this.state, this.lastResults); }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the facetting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } module.exports = AlgoliaSearchHelper; /***/ }), /* 246 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var map = __webpack_require__(17); var isArray = __webpack_require__(0); var isNumber = __webpack_require__(202); var isString = __webpack_require__(50); function valToNumber(v) { if (isNumber(v)) { return v; } else if (isString(v)) { return parseFloat(v); } else if (isArray(v)) { return map(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } module.exports = valToNumber; /***/ }), /* 247 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var merge = __webpack_require__(105); var isArray = __webpack_require__(0); var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach(state.numericRefinements, function(operators, attribute) { forEach(operators, function(values, operator) { if (facetName !== attribute) { forEach(values, function(value) { if (isArray(value)) { var vs = map(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach(state.facetsRefinements, function(facetValues, facetName) { forEach(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach(state.facetsExcludes, function(facetValues, facetName) { forEach(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var queries = merge(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), { facetQuery: query, facetName: facetName }); return queries; } }; module.exports = requestBuilder; /***/ }), /* 248 */ /***/ (function(module, exports, __webpack_require__) { var foreach = __webpack_require__(110); module.exports = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; /***/ }), /* 249 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /* 250 */ /***/ (function(module, exports) { /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } module.exports = addMapEntry; /***/ }), /* 251 */ /***/ (function(module, exports) { /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } module.exports = addSetEntry; /***/ }), /* 252 */ /***/ (function(module, exports) { /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } module.exports = asciiToArray; /***/ }), /* 253 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keys = __webpack_require__(9); /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } module.exports = baseAssign; /***/ }), /* 254 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keysIn = __webpack_require__(51); /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } module.exports = baseAssignIn; /***/ }), /* 255 */ /***/ (function(module, exports) { /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } module.exports = baseClamp; /***/ }), /* 256 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), arrayEach = __webpack_require__(85), assignValue = __webpack_require__(90), baseAssign = __webpack_require__(253), baseAssignIn = __webpack_require__(254), cloneBuffer = __webpack_require__(144), copyArray = __webpack_require__(68), copySymbols = __webpack_require__(291), copySymbolsIn = __webpack_require__(292), getAllKeys = __webpack_require__(95), getAllKeysIn = __webpack_require__(96), getTag = __webpack_require__(56), initCloneArray = __webpack_require__(307), initCloneByTag = __webpack_require__(308), initCloneObject = __webpack_require__(165), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isObject = __webpack_require__(6), keys = __webpack_require__(9); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } module.exports = baseClone; /***/ }), /* 257 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arrayIncludes = __webpack_require__(87), arrayIncludesWith = __webpack_require__(127), arrayMap = __webpack_require__(12), baseUnary = __webpack_require__(45), cacheHas = __webpack_require__(67); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } module.exports = baseDifference; /***/ }), /* 258 */ /***/ (function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(63); /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } module.exports = baseFilter; /***/ }), /* 259 */ /***/ (function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }), /* 260 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arrayIncludes = __webpack_require__(87), arrayIncludesWith = __webpack_require__(127), arrayMap = __webpack_require__(12), baseUnary = __webpack_require__(45), cacheHas = __webpack_require__(67); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseIntersection; /***/ }), /* 261 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43); /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } module.exports = baseInverter; /***/ }), /* 262 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), baseIsEqual = __webpack_require__(65); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }), /* 263 */ /***/ (function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }), /* 264 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6), isPrototype = __webpack_require__(37), nativeKeysIn = __webpack_require__(313); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }), /* 265 */ /***/ (function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(262), getMatchData = __webpack_require__(304), matchesStrictComparable = __webpack_require__(179); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }), /* 266 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(65), get = __webpack_require__(73), hasIn = __webpack_require__(200), isKey = __webpack_require__(72), isStrictComparable = __webpack_require__(168), matchesStrictComparable = __webpack_require__(179), toKey = __webpack_require__(23); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; /***/ }), /* 267 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), assignMergeValue = __webpack_require__(129), baseFor = __webpack_require__(132), baseMergeDeep = __webpack_require__(268), isObject = __webpack_require__(6), keysIn = __webpack_require__(51); /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } module.exports = baseMerge; /***/ }), /* 268 */ /***/ (function(module, exports, __webpack_require__) { var assignMergeValue = __webpack_require__(129), cloneBuffer = __webpack_require__(144), cloneTypedArray = __webpack_require__(145), copyArray = __webpack_require__(68), initCloneObject = __webpack_require__(165), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isArrayLikeObject = __webpack_require__(103), isBuffer = __webpack_require__(26), isFunction = __webpack_require__(19), isObject = __webpack_require__(6), isPlainObject = __webpack_require__(49), isTypedArray = __webpack_require__(36), toPlainObject = __webpack_require__(339); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } module.exports = baseMergeDeep; /***/ }), /* 269 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), baseMap = __webpack_require__(138), baseSortBy = __webpack_require__(276), baseUnary = __webpack_require__(45), compareMultiple = __webpack_require__(290), identity = __webpack_require__(24); /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } module.exports = baseOrderBy; /***/ }), /* 270 */ /***/ (function(module, exports, __webpack_require__) { var basePickBy = __webpack_require__(139), hasIn = __webpack_require__(200); /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } module.exports = basePick; /***/ }), /* 271 */ /***/ (function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }), /* 272 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }), /* 273 */ /***/ (function(module, exports) { /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } module.exports = baseReduce; /***/ }), /* 274 */ /***/ (function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(90), castPath = __webpack_require__(21), isIndex = __webpack_require__(31), isObject = __webpack_require__(6), toKey = __webpack_require__(23); /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } module.exports = baseSet; /***/ }), /* 275 */ /***/ (function(module, exports, __webpack_require__) { var constant = __webpack_require__(197), defineProperty = __webpack_require__(152), identity = __webpack_require__(24); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; /***/ }), /* 276 */ /***/ (function(module, exports) { /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } module.exports = baseSortBy; /***/ }), /* 277 */ /***/ (function(module, exports) { /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } module.exports = baseSum; /***/ }), /* 278 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), last = __webpack_require__(204), parent = __webpack_require__(314), toKey = __webpack_require__(23); /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } module.exports = baseUnset; /***/ }), /* 279 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12); /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } module.exports = baseValues; /***/ }), /* 280 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(103); /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } module.exports = castArrayLikeObject; /***/ }), /* 281 */ /***/ (function(module, exports, __webpack_require__) { var baseSlice = __webpack_require__(141); /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } module.exports = castSlice; /***/ }), /* 282 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } module.exports = charsEndIndex; /***/ }), /* 283 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } module.exports = charsStartIndex; /***/ }), /* 284 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93); /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } module.exports = cloneDataView; /***/ }), /* 285 */ /***/ (function(module, exports, __webpack_require__) { var addMapEntry = __webpack_require__(250), arrayReduce = __webpack_require__(89), mapToArray = __webpack_require__(98); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } module.exports = cloneMap; /***/ }), /* 286 */ /***/ (function(module, exports) { /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } module.exports = cloneRegExp; /***/ }), /* 287 */ /***/ (function(module, exports, __webpack_require__) { var addSetEntry = __webpack_require__(251), arrayReduce = __webpack_require__(89), setToArray = __webpack_require__(99); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } module.exports = cloneSet; /***/ }), /* 288 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } module.exports = cloneSymbol; /***/ }), /* 289 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(27); /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } module.exports = compareAscending; /***/ }), /* 290 */ /***/ (function(module, exports, __webpack_require__) { var compareAscending = __webpack_require__(289); /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } module.exports = compareMultiple; /***/ }), /* 291 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), getSymbols = __webpack_require__(71); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols; /***/ }), /* 292 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), getSymbolsIn = __webpack_require__(158); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn; /***/ }), /* 293 */ /***/ (function(module, exports) { /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } module.exports = countHolders; /***/ }), /* 294 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(11); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }), /* 295 */ /***/ (function(module, exports) { /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }), /* 296 */ /***/ (function(module, exports, __webpack_require__) { var createCtor = __webpack_require__(69), root = __webpack_require__(3); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } module.exports = createBind; /***/ }), /* 297 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), createCtor = __webpack_require__(69), createHybrid = __webpack_require__(150), createRecurry = __webpack_require__(151), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34), root = __webpack_require__(3); /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } module.exports = createCurry; /***/ }), /* 298 */ /***/ (function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(13), isArrayLike = __webpack_require__(11), keys = __webpack_require__(9); /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = baseIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } module.exports = createFind; /***/ }), /* 299 */ /***/ (function(module, exports, __webpack_require__) { var baseInverter = __webpack_require__(261); /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } module.exports = createInverter; /***/ }), /* 300 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), createCtor = __webpack_require__(69), root = __webpack_require__(3); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } module.exports = createPartial; /***/ }), /* 301 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } module.exports = customDefaultsAssignIn; /***/ }), /* 302 */ /***/ (function(module, exports, __webpack_require__) { var isPlainObject = __webpack_require__(49); /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } module.exports = customOmitClone; /***/ }), /* 303 */ /***/ (function(module, exports, __webpack_require__) { var realNames = __webpack_require__(315); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } module.exports = getFuncName; /***/ }), /* 304 */ /***/ (function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(168), keys = __webpack_require__(9); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }), /* 305 */ /***/ (function(module, exports) { /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } module.exports = getWrapDetails; /***/ }), /* 306 */ /***/ (function(module, exports) { /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } module.exports = hasUnicode; /***/ }), /* 307 */ /***/ (function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; /***/ }), /* 308 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93), cloneDataView = __webpack_require__(284), cloneMap = __webpack_require__(285), cloneRegExp = __webpack_require__(286), cloneSet = __webpack_require__(287), cloneSymbol = __webpack_require__(288), cloneTypedArray = __webpack_require__(145); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } module.exports = initCloneByTag; /***/ }), /* 309 */ /***/ (function(module, exports) { /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } module.exports = insertWrapDetails; /***/ }), /* 310 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), isArguments = __webpack_require__(25), isArray = __webpack_require__(0); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } module.exports = isFlattenable; /***/ }), /* 311 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), getData = __webpack_require__(156), getFuncName = __webpack_require__(303), lodash = __webpack_require__(341); /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } module.exports = isLaziable; /***/ }), /* 312 */ /***/ (function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(146), composeArgsRight = __webpack_require__(147), replaceHolders = __webpack_require__(34); /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } module.exports = mergeData; /***/ }), /* 313 */ /***/ (function(module, exports) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }), /* 314 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64), baseSlice = __webpack_require__(141); /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } module.exports = parent; /***/ }), /* 315 */ /***/ (function(module, exports) { /** Used to lookup unminified function names. */ var realNames = {}; module.exports = realNames; /***/ }), /* 316 */ /***/ (function(module, exports, __webpack_require__) { var copyArray = __webpack_require__(68), isIndex = __webpack_require__(31); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } module.exports = reorder; /***/ }), /* 317 */ /***/ (function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }), /* 318 */ /***/ (function(module, exports, __webpack_require__) { var asciiToArray = __webpack_require__(252), hasUnicode = __webpack_require__(306), unicodeToArray = __webpack_require__(319); /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } module.exports = stringToArray; /***/ }), /* 319 */ /***/ (function(module, exports) { /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange + ']', rsCombo = '[' + rsComboRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } module.exports = unicodeToArray; /***/ }), /* 320 */ /***/ (function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(85), arrayIncludes = __webpack_require__(87); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } module.exports = updateWrapDetails; /***/ }), /* 321 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), LodashWrapper = __webpack_require__(124), copyArray = __webpack_require__(68); /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } module.exports = wrapperClone; /***/ }), /* 322 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), createAssigner = __webpack_require__(149), keysIn = __webpack_require__(51); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); module.exports = assignInWith; /***/ }), /* 323 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; module.exports = bind; /***/ }), /* 324 */ /***/ (function(module, exports) { /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } module.exports = compact; /***/ }), /* 325 */ /***/ (function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(257), baseFlatten = __webpack_require__(131), baseRest = __webpack_require__(20), isArrayLikeObject = __webpack_require__(103); /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); module.exports = difference; /***/ }), /* 326 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43), castFunction = __webpack_require__(143); /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, castFunction(iteratee)); } module.exports = forOwn; /***/ }), /* 327 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44), isArrayLike = __webpack_require__(11), isString = __webpack_require__(50), toInteger = __webpack_require__(53), values = __webpack_require__(340); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } module.exports = includes; /***/ }), /* 328 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIntersection = __webpack_require__(260), baseRest = __webpack_require__(20), castArrayLikeObject = __webpack_require__(280); /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); module.exports = intersection; /***/ }), /* 329 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), baseForOwn = __webpack_require__(43), baseIteratee = __webpack_require__(13); /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = baseIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } module.exports = mapKeys; /***/ }), /* 330 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), baseForOwn = __webpack_require__(43), baseIteratee = __webpack_require__(13); /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = baseIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } module.exports = mapValues; /***/ }), /* 331 */ /***/ (function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }), /* 332 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; module.exports = partial; /***/ }), /* 333 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; module.exports = partialRight; /***/ }), /* 334 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), basePickBy = __webpack_require__(139), getAllKeysIn = __webpack_require__(96); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = baseIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } module.exports = pickBy; /***/ }), /* 335 */ /***/ (function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(271), basePropertyDeep = __webpack_require__(272), isKey = __webpack_require__(72), toKey = __webpack_require__(23); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }), /* 336 */ /***/ (function(module, exports, __webpack_require__) { var baseClamp = __webpack_require__(255), baseToString = __webpack_require__(66), toInteger = __webpack_require__(53), toString = __webpack_require__(75); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } module.exports = startsWith; /***/ }), /* 337 */ /***/ (function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(13), baseSum = __webpack_require__(277); /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, baseIteratee(iteratee, 2)) : 0; } module.exports = sumBy; /***/ }), /* 338 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6), isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }), /* 339 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keysIn = __webpack_require__(51); /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } module.exports = toPlainObject; /***/ }), /* 340 */ /***/ (function(module, exports, __webpack_require__) { var baseValues = __webpack_require__(279), keys = __webpack_require__(9); /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } module.exports = values; /***/ }), /* 341 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), LodashWrapper = __webpack_require__(124), baseLodash = __webpack_require__(92), isArray = __webpack_require__(0), isObjectLike = __webpack_require__(7), wrapperClone = __webpack_require__(321); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; module.exports = lodash; /***/ }), /* 342 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var stringify = __webpack_require__(344); var parse = __webpack_require__(343); var formats = __webpack_require__(209); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }), /* 343 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(108); var has = Object.prototype.hasOwnProperty; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseValues(str, options) { var obj = {}; var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; var key, val; if (pos === -1) { key = options.decoder(part); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos)); val = options.decoder(part.slice(pos + 1)); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function parseObject(chain, val, options) { if (!chain.length) { return val; } var root = chain.shift(); var obj; if (root === '[]') { obj = []; obj = obj.concat(parseObject(chain, val, options)); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = parseObject(chain, val, options); } else { obj[cleanRoot] = parseObject(chain, val, options); } } return obj; }; var parseKeys = function parseKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey; // The regex chunks var parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Stash the parent if it exists var keys = []; if (segment[1]) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, segment[1])) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) { if (!options.allowPrototypes) { continue; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; module.exports = function (str, opts) { var options = opts || {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; /***/ }), /* 344 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(108); var formats = __webpack_require__(209); var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var toISO = Date.prototype.toISOString; var defaults = { delimiter: '&', encode: true, encoder: utils.encode, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder ? encoder(prefix) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } } return values; }; module.exports = function (object, opts) { var obj = object; var options = opts || {}; var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; if (typeof options.format === 'undefined') { options.format = formats.default; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } return keys.join(delimiter); }; /***/ }), /* 345 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Highlighter; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlighter(_ref) { var hit = _ref.hit; var attributeName = _ref.attributeName; var highlight = _ref.highlight; var highlightProperty = _ref.highlightProperty; var tagName = _ref.tagName; var parsedHighlightedValue = highlight({ hit: hit, attributeName: attributeName, highlightProperty: highlightProperty }); var reactHighlighted = parsedHighlightedValue.map(function (v, i) { var key = 'split-' + i + '-' + v.value; if (!v.isHighlighted) { return _react2.default.createElement( 'span', { key: key, className: 'ais-Highlight__nonHighlighted' }, v.value ); } var HighlightedTag = tagName ? tagName : 'em'; return _react2.default.createElement( HighlightedTag, { key: key, className: 'ais-Highlight__highlighted' }, v.value ); }); return _react2.default.createElement( 'span', { className: 'ais-Highlight' }, reactHighlighted ); } Highlighter.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, highlightProperty: _propTypes2.default.string.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 346 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('SearchBox'); var SearchBox = function (_Component) { _inherits(SearchBox, _Component); function SearchBox(props) { _classCallCheck(this, SearchBox); var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this)); _this.getQuery = function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }; _this.setQuery = function (val) { var _this$props = _this.props; var refine = _this$props.refine; var searchAsYouType = _this$props.searchAsYouType; if (searchAsYouType) { refine(val); } else { _this.setState({ query: val }); } }; _this.onInputMount = function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }; _this.onKeyDown = function (e) { if (!_this.props.focusShortcuts) { return; } var shortcuts = _this.props.focusShortcuts.map(function (key) { return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key; }); var elt = e.target || e.srcElement; var tagName = elt.tagName; if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') { // already in an input return; } var which = e.which || e.keyCode; if (shortcuts.indexOf(which) === -1) { // not the right shortcut return; } _this.input.focus(); e.stopPropagation(); e.preventDefault(); }; _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); _this.input.blur(); var _this$props2 = _this.props; var refine = _this$props2.refine; var searchAsYouType = _this$props2.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }; _this.onChange = function (e) { _this.setQuery(e.target.value); if (_this.props.onChange) { _this.props.onChange(e); } }; _this.onReset = function () { _this.setQuery(''); _this.input.focus(); if (_this.props.onReset) { _this.props.onReset(); } }; _this.state = { query: props.searchAsYouType ? null : props.currentRefinement }; return _this; } _createClass(SearchBox, [{ key: 'componentDidMount', value: function componentDidMount() { document.addEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { document.removeEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Reset query when the searchParameters query has changed. // This is kind of an anti-pattern (props in state), but it works here // since we know for sure that searchParameters having changed means a // new search has been triggered. if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: nextProps.currentRefinement }); } } // From https://github.com/algolia/autocomplete.js/pull/86 }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var autoFocus = _props.autoFocus; var query = this.getQuery(); var submitComponent = this.props.submitComponent ? this.props.submitComponent : _react2.default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-search-13' }) ); var resetComponent = this.props.resetComponent ? this.props.resetComponent : _react2.default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' }) ); var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) { if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) { return _extends({}, props, _defineProperty({}, prop, _this2.props[prop])); } return props; }, {}); /* eslint-disable max-len */ return _react2.default.createElement( 'form', _extends({ noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset }, cx('root'), { action: '', role: 'search' }), _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } }, _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-search-13', viewBox: '0 0 40 40' }, _react2.default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z', fillRule: 'evenodd' }) ), _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-clear-3', viewBox: '0 0 20 20' }, _react2.default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z', fillRule: 'evenodd' }) ) ), _react2.default.createElement( 'div', _extends({ role: 'search' }, cx('wrapper')), _react2.default.createElement('input', _extends({ ref: this.onInputMount, type: 'search', placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: 'off', autoCorrect: 'off', autoCapitalize: 'off', spellCheck: 'false', required: true, value: query, onChange: this.onChange }, searchInputEvents, cx('input'))), _react2.default.createElement( 'button', _extends({ type: 'submit', title: translate('submitTitle') }, cx('submit')), submitComponent ), _react2.default.createElement( 'button', _extends({ type: 'reset', title: translate('resetTitle') }, cx('reset'), { onClick: this.onReset }), resetComponent ) ) ); /* eslint-enable */ } }]); return SearchBox; }(_react.Component); SearchBox.propTypes = { currentRefinement: _propTypes2.default.string, refine: _propTypes2.default.func.isRequired, translate: _propTypes2.default.func.isRequired, resetComponent: _propTypes2.default.element, submitComponent: _propTypes2.default.element, focusShortcuts: _propTypes2.default.arrayOf(_propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number])), autoFocus: _propTypes2.default.bool, searchAsYouType: _propTypes2.default.bool, onSubmit: _propTypes2.default.func, onReset: _propTypes2.default.func, onChange: _propTypes2.default.func, // For testing purposes __inputRef: _propTypes2.default.func }; SearchBox.defaultProps = { currentRefinement: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true }; exports.default = (0, _translatable2.default)({ resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); /***/ }), /* 347 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); 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 Select = function (_Component) { _inherits(Select, _Component); function Select() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Select); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.onSelect(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Select, [{ key: 'render', value: function render() { var _props = this.props; var cx = _props.cx; var items = _props.items; var selectedItem = _props.selectedItem; return _react2.default.createElement( 'select', _extends({}, cx('root'), { value: selectedItem, onChange: this.onChange }), items.map(function (item) { return _react2.default.createElement( 'option', { key: (0, _has3.default)(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, (0, _has3.default)(item, 'label') ? item.label : item.value ); }) ); } }]); return Select; }(_react.Component); Select.propTypes = { cx: _propTypes2.default.func.isRequired, onSelect: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]).isRequired, key: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), label: _propTypes2.default.string, disabled: _propTypes2.default.bool })).isRequired, selectedItem: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]).isRequired }; exports.default = Select; /***/ }), /* 348 */ /***/ (function(module, exports, __webpack_require__) { module.exports = buildSearchMethod; var errors = __webpack_require__(215); /** * Creates a search method to be used in clients * @param {string} queryParam the name of the attribute used for the query * @param {string} url the url * @return {function} the search method */ function buildSearchMethod(queryParam, url) { /** * The search method. Prepares the data and send the query to Algolia. * @param {string} query the string used for query search * @param {object} args additional parameters to send with the search * @param {function} [callback] the callback to be called with the client gets the answer * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise */ return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } // Normalizing the function signature if (arguments.length === 0 || typeof query === 'function') { // Usage : .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // Usage : .search(query/args), .search(query, cb) callback = args; args = undefined; } // At this point we have 3 arguments with values // Usage : .search(args) // careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } var additionalUA; if (args !== undefined) { if (args.additionalUA) { additionalUA = args.additionalUA; delete args.additionalUA; } // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback, additionalUA); }; } /***/ }), /* 349 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 350 */, /* 351 */ /***/ (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; }; }(); exports.default = createIndex; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Index = __webpack_require__(398); var _Index2 = _interopRequireDefault(_Index); 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; } /** * Creates a specialized root Index component. It accepts * a specification of the root Element. * @param {object} root - the defininition of the root of an Index sub tree. * @returns {object} a Index root */ function createIndex(root) { var _class, _temp; return _temp = _class = function (_Component) { _inherits(CreateIndex, _Component); function CreateIndex() { _classCallCheck(this, CreateIndex); return _possibleConstructorReturn(this, (CreateIndex.__proto__ || Object.getPrototypeOf(CreateIndex)).apply(this, arguments)); } _createClass(CreateIndex, [{ key: 'render', value: function render() { return _react2.default.createElement(_Index2.default, { indexName: this.props.indexName, root: root, children: this.props.children }); } }]); return CreateIndex; }(_react.Component), _class.propTypes = { children: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]), indexName: _propTypes2.default.string.isRequired }, _temp; } /***/ }), /* 352 */ /***/ (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; }; }(); exports.default = createInstantSearch; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _InstantSearch = __webpack_require__(399); var _InstantSearch2 = _interopRequireDefault(_InstantSearch); 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 _name$author$descript = { name: 'react-instantsearch', author: { name: 'Algolia, Inc.', url: 'https://www.algolia.com' }, description: '\u26A1 Lightning-fast search for React and React Native apps', version: '4.0.0-beta.3', scripts: { build: './scripts/build.sh', 'build-and-publish': './scripts/build-and-publish.sh' }, homepage: 'https://community.algolia.com/react-instantsearch/', repository: { type: 'git', url: 'https://github.com/algolia/react-instantsearch/' }, dependencies: { algoliasearch: '^3.21.1', 'algoliasearch-helper': '2.19.0', classnames: '^2.2.5', lodash: '^4.17.4', 'prop-types': '^15.5.8' }, license: 'MIT', devDependencies: { enzyme: '^2.8.1', react: '^15.5.4', 'react-dom': '^15.5.4', 'react-native': '^0.41.2', 'react-test-renderer': '^15.5.4' } }; var version = _name$author$descript.version; /** * Creates a specialized root InstantSearch component. It accepts * an algolia client and a specification of the root Element. * @param {function} defaultAlgoliaClient - a function that builds an Algolia client * @param {object} root - the defininition of the root of an InstantSearch sub tree. * @returns {object} an InstantSearch root */ function createInstantSearch(defaultAlgoliaClient, root) { var _class, _temp; return _temp = _class = function (_Component) { _inherits(CreateInstantSearch, _Component); function CreateInstantSearch(props) { _classCallCheck(this, CreateInstantSearch); var _this = _possibleConstructorReturn(this, (CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call(this)); _this.client = props.algoliaClient || defaultAlgoliaClient(props.appId, props.apiKey); _this.client.addAlgoliaAgent('react-instantsearch ' + version); return _this; } _createClass(CreateInstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } this.client.addAlgoliaAgent('react-instantsearch ' + version); } }, { key: 'render', value: function render() { return _react2.default.createElement(_InstantSearch2.default, { createURL: this.props.createURL, indexName: this.props.indexName, searchParameters: this.props.searchParameters, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, root: root, algoliaClient: this.client, children: this.props.children }); } }]); return CreateInstantSearch; }(_react.Component), _class.propTypes = { algoliaClient: _propTypes2.default.object, appId: _propTypes2.default.string, apiKey: _propTypes2.default.string, children: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]), indexName: _propTypes2.default.string.isRequired, searchParameters: _propTypes2.default.object, createURL: _propTypes2.default.func, searchState: _propTypes2.default.object, onSearchStateChange: _propTypes2.default.func }, _temp; } /***/ }), /* 353 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(210); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _ClearAll = __webpack_require__(376); var _ClearAll2 = _interopRequireDefault(_ClearAll); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ClearAll widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearAll * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query * @themeKey ais-ClearAll__root - the widget button * @translationKey reset - the clear all button value * @example * import React from 'react'; * * import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ClearAll /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_ClearAll2.default); /***/ }), /* 354 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectConfigure = __webpack_require__(220); var _connectConfigure2 = _interopRequireDefault(_connectConfigure); var _Configure = __webpack_require__(377); var _Configure2 = _interopRequireDefault(_Configure); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * * import {Configure} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure distinct={1} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectConfigure2.default)(_Configure2.default); /***/ }), /* 355 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(210); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _CurrentRefinements = __webpack_require__(378); var _CurrentRefinements2 = _interopRequireDefault(_CurrentRefinements); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The CurrentRefinements widget displays the list of currently applied filters. * * It allows the user to selectively remove them. * @name CurrentRefinements * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-CurrentRefinements__root - the root div of the widget * @themeKey ais-CurrentRefinements__items - the container of the filters * @themeKey ais-CurrentRefinements__item - a single filter * @themeKey ais-CurrentRefinements__itemLabel - the label of a filter * @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter * @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * * import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CurrentRefinements /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_CurrentRefinements2.default); /***/ }), /* 356 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHierarchicalMenu = __webpack_require__(221); var _connectHierarchicalMenu2 = _interopRequireDefault(_connectHierarchicalMenu); var _HierarchicalMenu = __webpack_require__(379); var _HierarchicalMenu2 = _interopRequireDefault(_HierarchicalMenu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The hierarchical menu lets the user browse attributes using a tree-like structure. * * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * * @name HierarchicalMenu * @kind widget * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HierarchicalMenu__root - Container of the widget * @themeKey ais-HierarchicalMenu__items - Container of the items * @themeKey ais-HierarchicalMenu__item - Id for a single list item * @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list * @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed * @themeKey HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected * @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count * @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry * @themeKey ais-HierarchicalMenu__itemCount - the count of the entry * @themeKey ais-HierarchicalMenu__itemItems - id representing a children * @themeKey ais-HierarchicalMenu__showMore - container for the show more button * @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement * @translationKey showMore - Label value of the button which toggles the number of items * @example * import React from 'react'; * import { * InstantSearch, * HierarchicalMenu, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HierarchicalMenu * id="categories" * key="categories" * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHierarchicalMenu2.default)(_HierarchicalMenu2.default); /***/ }), /* 357 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHits = __webpack_require__(222); var _connectHits2 = _interopRequireDefault(_connectHits); var _Hits = __webpack_require__(381); var _Hits2 = _interopRequireDefault(_Hits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays a list of hits. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name Hits * @kind widget * @propType {Component} [hitComponent] - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-Hits__root - the root of the component * @example * import React from 'react'; * import { * InstantSearch, * Hits, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHits2.default)(_Hits2.default); /***/ }), /* 358 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHitsPerPage = __webpack_require__(223); var _connectHitsPerPage2 = _interopRequireDefault(_connectHitsPerPage); var _HitsPerPage = __webpack_require__(382); var _HitsPerPage2 = _interopRequireDefault(_HitsPerPage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The HitsPerPage widget displays a dropdown menu to let the user change the number * of displayed hits. * * If you only want to configure the number of hits per page without * displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure /> documentation`](widgets/Configure.html) * * @name HitsPerPage * @kind widget * @propType {{value: number, label: string}[]} items - List of available options. * @propType {number} defaultRefinement - The number of items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HitsPerPage__root - the root of the component. * @example * import React from 'react'; * import { * InstantSearch, * HitsPerPage, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HitsPerPage * defaultRefinement={20} * items={[{value: '30', label: 'Show 20 hits'}, {value: '50', label: 'Show 50 hits'}]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHitsPerPage2.default)(_HitsPerPage2.default); /***/ }), /* 359 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectInfiniteHits = __webpack_require__(224); var _connectInfiniteHits2 = _interopRequireDefault(_connectInfiniteHits); var _InfiniteHits = __webpack_require__(383); var _InfiniteHits2 = _interopRequireDefault(_InfiniteHits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays an infinite list of hits along with a **load more** button. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name InfiniteHits * @kind widget * @propType {Component} hitComponent - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey root - the root of the component * @translationKey loadMore - the label of load more button * @example * import React from 'react'; * import { * InstantSearch, * Hits, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <InfiniteHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectInfiniteHits2.default)(_InfiniteHits2.default); /***/ }), /* 360 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMenu = __webpack_require__(225); var _connectMenu2 = _interopRequireDefault(_connectMenu); var _Menu = __webpack_require__(385); var _Menu2 = _interopRequireDefault(_Menu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Menu component displays a menu that lets the user choose a single value for a specific attribute. * @name Menu * @kind widget * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values * @themeKey ais-Menu__root - the root of the component * @themeKey ais-Menu__items - the container of all items in the menu * @themeKey ais-Menu__item - a single item * @themeKey ais-Menu__itemLinkSelected - the selected menu item * @themeKey ais-Menu__itemLink - the item link * @themeKey ais-Menu__itemLabelSelected - the selected item label * @themeKey ais-Menu__itemLabel - the item label * @themeKey ais-Menu__itemCount - the item count * @themeKey ais-Menu__itemCountSelected - the selected item count * @themeKey ais-Menu__noRefinement - present when there is no refinement * @themeKey ais-Menu__showMore - the button that let the user toggle more results * @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @example * import React from 'react'; * * import {Menu, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Menu * attributeName="category" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMenu2.default)(_Menu2.default); /***/ }), /* 361 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMultiRange = __webpack_require__(226); var _connectMultiRange2 = _interopRequireDefault(_connectMultiRange); var _MultiRange = __webpack_require__(386); var _MultiRange2 = _interopRequireDefault(_MultiRange); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * MultiRange is a widget used for selecting the range value of a numeric attribute. * @name MultiRange * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max". * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-MultiRange__root - The root component of the widget * @themeKey ais-MultiRange__items - The container of the items * @themeKey ais-MultiRange__item - A single item * @themeKey ais-MultiRange__itemSelected - The selected item * @themeKey ais-MultiRange__itemLabel - The label of an item * @themeKey ais-MultiRange__itemLabelSelected - The selected label item * @themeKey ais-MultiRange__itemRadio - The radio of an item * @themeKey ais-MultiRange__itemRadioSelected - The selected radio item * @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges * @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range * @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * * import {InstantSearch, MultiRange} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <MultiRange attributeName="price" * items={[ * {end: 10, label: '<$10'}, * {start: 10, end: 100, label: '$10-$100'}, * {start: 100, end: 500, label: '$100-$500'}, * {start: 500, label: '>$500'}, * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMultiRange2.default)(_MultiRange2.default); /***/ }), /* 362 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPagination = __webpack_require__(227); var _connectPagination2 = _interopRequireDefault(_connectPagination); var _Pagination = __webpack_require__(387); var _Pagination2 = _interopRequireDefault(_Pagination); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Pagination widget displays a simple pagination system allowing the user to * change the current page. * @name Pagination * @kind widget * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @themeKey ais-Pagination__root - The root component of the widget * @themeKey ais-Pagination__itemFirst - The first page link item * @themeKey ais-Pagination__itemPrevious - The previous page link item * @themeKey ais-Pagination__itemPage - The page link item * @themeKey ais-Pagination__itemNext - The next page link item * @themeKey ais-Pagination__itemLast - The last page link item * @themeKey ais-Pagination__itemDisabled - a disabled item * @themeKey ais-Pagination__itemSelected - a selected item * @themeKey ais-Pagination__itemLink - The link of an item * @themeKey ais-Pagination__noRefinement - present when there is no refinement * @translationKey previous - Label value for the previous page link * @translationKey next - Label value for the next page link * @translationKey first - Label value for the first page link * @translationKey last - Label value for the last page link * @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string * @translationKey ariaPrevious - Accessibility label value for the previous page link * @translationKey ariaNext - Accessibility label value for the next page link * @translationKey ariaFirst - Accessibility label value for the first page link * @translationKey ariaLast - Accessibility label value for the last page link * @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string * @example * import React from 'react'; * * import {Pagination, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Pagination/> * </InstantSearch> * ); * } */ exports.default = (0, _connectPagination2.default)(_Pagination2.default); /***/ }), /* 363 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _Panel = __webpack_require__(388); var _Panel2 = _interopRequireDefault(_Panel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Panel widget wraps other widgets in a consistent panel design. * * It also reacts, indicates and set CSS classes when widgets are no more * relevant for refining. E.g. when a RefinementList becomes empty because of * the current search results. * @name Panel * @kind widget * @propType {string} title - The panel title * @themeKey ais-Panel__root - Container of the widget * @themeKey ais-Panel__title - The panel title * @themeKey ais-Panel__noRefinement - Present if the panel content is empty * @example * import React from 'react'; * * import {Panel, RefinementList, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Panel title="category"> * <RefinementList attributeName="category" /> * </Panel> * </InstantSearch> * ); * } */ exports.default = _Panel2.default; /***/ }), /* 364 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPoweredBy = __webpack_require__(228); var _connectPoweredBy2 = _interopRequireDefault(_connectPoweredBy); var _PoweredBy = __webpack_require__(389); var _PoweredBy2 = _interopRequireDefault(_PoweredBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * PoweredBy displays an Algolia logo. * * Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing). * @name PoweredBy * @kind widget * @themeKey ais-PoweredBy__root - The root component of the widget * @themeKey ais-PoweredBy__searchBy - The powered by label * @themeKey ais-PoweredBy__algoliaLink - The algolia logo link * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * * import {PoweredBy, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <PoweredBy /> * </InstantSearch> * ); * } */ exports.default = (0, _connectPoweredBy2.default)(_PoweredBy2.default); /***/ }), /* 365 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _RangeInput = __webpack_require__(390); var _RangeInput2 = _interopRequireDefault(_RangeInput); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * RangeInput allows a user to select a numeric range using a minimum and maximum input. * @name RangeInput * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the record * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @themeKey ais-RangeInput__root - The root component of the widget * @themeKey ais-RangeInput__labelMin - The label for the min input * @themeKey ais-RangeInput__inputMin - The min input * @themeKey ais-RangeInput__separator - The separator between input * @themeKey ais-RangeInput__labelMax - The label for the max input * @themeKey ais-RangeInput__inputMax - The max input * @themeKey ais-RangeInput__submit - The submit button * @themeKey ais-RangeInput__noRefinement - present when there is no refinement * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * * import {RangeInput, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RangeInput attributeName="price"/> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_RangeInput2.default); /***/ }), /* 366 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Since a lot of sliders already exist, we did not include one by default. * However you can easily connect React InstantSearch to an existing one * using the [connectRange connector](connectors/connectRange.html). * * @name RangeSlider * @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values. * @kind widget * @example * * // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the * // range connector import PropTypes from 'prop-types'; import React, {Component} from 'react'; import {connectRange} from 'react-instantsearch/connectors'; import Rheostat from 'rheostat'; class Range extends React.Component { static propTypes = { min: PropTypes.number, max: PropTypes.number, currentRefinement: PropTypes.object, refine: PropTypes.func.isRequired, canRefine: PropTypes.bool.isRequired, }; state = {currentValues: {min: this.props.min, max: this.props.max}}; componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}}); } } onValuesUpdated = (sliderState) => { this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}}); }; onChange = (sliderState) => { if (this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1]) { this.props.refine({min: sliderState.values[0], max: sliderState.values[1]}); } }; render() { const {min, max, currentRefinement} = this.props; const {currentValues} = this.state; return min !== max ? <div> <Rheostat min={min} max={max} values={[currentRefinement.min, currentRefinement.max]} onChange={this.onChange} onValuesUpdated={this.onValuesUpdated} /> <div style={{display: 'flex', justifyContent: 'space-between'}}> <div>{currentValues.min}</div> <div>{currentValues.max}</div> </div> </div> : null; } } const ConnectedRange = connectRange(Range); */ exports.default = (0, _connectRange2.default)(function () { return _react2.default.createElement( 'div', null, 'We do not provide any Slider, see the documentation to learn how to connect one easily:', _react2.default.createElement( 'a', { target: '_blank', href: 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' }, 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' ) ); }); /***/ }), /* 367 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRefinementList = __webpack_require__(229); var _connectRefinementList2 = _interopRequireDefault(_connectRefinementList); var _RefinementList = __webpack_require__(391); var _RefinementList2 = _interopRequireDefault(_RefinementList); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximum number of displayed items. Only used when showMore is set to `true` * @propType {string[]} [defaultRefinement] - the values of the items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-RefinementList__root - the root of the component * @themeKey ais-RefinementList__items - the container of all items in the list * @themeKey ais-RefinementList__itemSelected - the selected list item * @themeKey ais-RefinementList__itemCheckbox - the item checkbox * @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox * @themeKey ais-RefinementList__itemLabel - the item label * @themeKey ais-RefinementList__itemLabelSelected - the selected item label * @themeKey RefinementList__itemCount - the item count * @themeKey RefinementList__itemCountSelected - the selected item count * @themeKey ais-RefinementList__showMore - the button that let the user toggle more results * @themeKey ais-RefinementList__noRefinement - present when there is no refinement * @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @example * import React from 'react'; * * import {RefinementList, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RefinementList attributeName="colors" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRefinementList2.default)(_RefinementList2.default); /***/ }), /* 368 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectScrollTo = __webpack_require__(230); var _connectScrollTo2 = _interopRequireDefault(_connectScrollTo); var _ScrollTo = __webpack_require__(392); var _ScrollTo2 = _interopRequireDefault(_ScrollTo); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ScrollTo component will made the page scroll to the component wrapped by it when one of the * [search state](guide/Search_state.html) prop is updated. By default when the page number changes, * the scroll goes to the wrapped component. * * @name ScrollTo * @kind widget * @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes. * @example * import React from 'react'; * * import {ScrollTo, Hits, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); * } */ exports.default = (0, _connectScrollTo2.default)(_ScrollTo2.default); /***/ }), /* 369 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSearchBox = __webpack_require__(231); var _connectSearchBox2 = _interopRequireDefault(_connectSearchBox); var _SearchBox = __webpack_require__(346); var _SearchBox2 = _interopRequireDefault(_SearchBox); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SearchBox component displays a search box that lets the user search for a specific query. * @name SearchBox * @kind widget * @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes. * @propType {boolean} [autoFocus=false] - Should the search box be focused on render? * @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused. * @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container. * @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container. * @propType {function} [on*] - Listen to any events sent form the search input itself. * @propType {React.Element} [submitComponent] - Change the apparence of the default submit button (magnifying glass). * @propType {React.Element} [resetComponent] - Change the apparence of the default reset button (cross). * @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted. * @themeKey ais-SearchBox__root - the root of the component * @themeKey ais-SearchBox__wrapper - the search box wrapper * @themeKey ais-SearchBox__input - the search box input * @themeKey ais-SearchBox__submit - the submit button * @themeKey ais-SearchBox__reset - the reset button * @translationkey submitTitle - The submit button title * @translationkey resetTitle - The reset button title * @translationkey placeholder - The label of the input placeholder * @example * import React from 'react'; * * import {SearchBox, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSearchBox2.default)(_SearchBox2.default); /***/ }), /* 370 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(211); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Snippet = __webpack_require__(393); var _Snippet2 = _interopRequireDefault(_Snippet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted snippet form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Snippet * @kind widget * @propType {string} attributeName - the location of the highlighted snippet attribute in the hit * @propType {object} hit - the hit object containing the highlighted snippet attribute * @propType {string} [tagName='em'] - the tag to be used for highlighted parts of the attribute * @example * import React from 'react'; * * import {InstantSearch, connectHits, Snippet} from 'InstantSearch'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Snippet attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Snippet2.default); /***/ }), /* 371 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSortBy = __webpack_require__(232); var _connectSortBy2 = _interopRequireDefault(_connectSortBy); var _SortBy = __webpack_require__(394); var _SortBy2 = _interopRequireDefault(_SortBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SortBy component displays a list of indexes allowing a user to change the hits are sorting. * @name SortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind widget * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {string} defaultRefinement - The default selected index. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-SortBy__root - the root of the component * @example * import React from 'react'; * * import {SortBy, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SortBy * items={[ * {value: 'ikea', label: 'Featured'}, * {value: 'ikea_price_asc', label: 'Price asc.'}, * {value: 'ikea_price_desc', label: 'Price desc.'}, * ]} * defaultRefinement="ikea" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSortBy2.default)(_SortBy2.default); /***/ }), /* 372 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _StarRating = __webpack_require__(395); var _StarRating2 = _interopRequireDefault(_StarRating); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * StarRating lets the user refine search results by clicking on stars. * * The stars are based on the selected `attributeName`. * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @name StarRating * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating. * @themeKey ais-StarRating__root - The root component of the widget * @themeKey ais-StarRating__ratingLink - The item link * @themeKey ais-StarRating__ratingLinkSelected - The selected link item * @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item * @themeKey ais-StarRating__ratingIcon - The rating icon * @themeKey ais-StarRating__ratingIconSelected - The selected rating icon * @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon * @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon * @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon * @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon * @themeKey ais-StarRating__ratingLabel - The link label * @themeKey ais-StarRating__ratingLabelSelected - The selected link label * @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label * @themeKey ais-StarRating__ratingCount - The link count * @themeKey ais-StarRating__ratingCountSelected - The selected link count * @themeKey ais-StarRating__ratingCountDisabled - The disabled link count * @themeKey ais-StarRating__noRefinement - present when there is no refinement * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * * import {StarRating, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <StarRating attributeName="rating" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_StarRating2.default); /***/ }), /* 373 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectStats = __webpack_require__(233); var _connectStats2 = _interopRequireDefault(_connectStats); var _Stats = __webpack_require__(396); var _Stats2 = _interopRequireDefault(_Stats); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). * @name Stats * @kind widget * @themeKey ais-Stats__root - the root of the component * @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time. * @example * import React from 'react'; * * import {Stats, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Stats /> * </InstantSearch> * ); * } */ exports.default = (0, _connectStats2.default)(_Stats2.default); /***/ }), /* 374 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectToggle = __webpack_require__(234); var _connectToggle2 = _interopRequireDefault(_connectToggle); var _Toggle = __webpack_require__(397); var _Toggle2 = _interopRequireDefault(_Toggle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Toggle provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization. * @name Toggle * @kind widget * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName` when checked. * @propType {boolean} [defaultChecked=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-Toggle__root - the root of the component * @themeKey ais-Toggle__checkbox - the toggle checkbox * @themeKey ais-Toggle__label - the toggle label * @example * import React from 'react'; * * import {Toggle, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Toggle attributeName="materials" * label="Made with solid pine" * value={'Solid pine'} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectToggle2.default)(_Toggle2.default); /***/ }), /* 375 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var AlgoliaSearchCore = __webpack_require__(404); var createAlgoliasearch = __webpack_require__(406); module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) '); /***/ }), /* 376 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('ClearAll'); var ClearAll = function (_Component) { _inherits(ClearAll, _Component); function ClearAll() { _classCallCheck(this, ClearAll); return _possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments)); } _createClass(ClearAll, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var items = _props.items; var refine = _props.refine; var isDisabled = items.length === 0; if (isDisabled) { return _react2.default.createElement( 'button', _extends({}, cx('root'), { disabled: true }), translate('reset') ); } return _react2.default.createElement( 'button', _extends({}, cx('root'), { onClick: refine.bind(null, items) }), translate('reset') ); } }]); return ClearAll; }(_react.Component); ClearAll.propTypes = { translate: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.object).isRequired, refine: _propTypes2.default.func.isRequired }; exports.default = (0, _translatable2.default)({ reset: 'Clear all filters' })(ClearAll); /***/ }), /* 377 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { return null; }; /***/ }), /* 378 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('CurrentRefinements'); var CurrentRefinements = function (_Component) { _inherits(CurrentRefinements, _Component); function CurrentRefinements() { _classCallCheck(this, CurrentRefinements); return _possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments)); } _createClass(CurrentRefinements, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var items = _props.items; var refine = _props.refine; var canRefine = _props.canRefine; return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), _react2.default.createElement( 'div', cx('items'), items.map(function (item) { return _react2.default.createElement( 'div', _extends({ key: item.label }, cx('item', item.items && 'itemParent')), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), item.items ? item.items.map(function (nestedItem) { return _react2.default.createElement( 'div', _extends({ key: nestedItem.label }, cx('item')), _react2.default.createElement( 'span', cx('itemLabel'), nestedItem.label ), _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, nestedItem.value) }), translate('clearFilter', nestedItem) ) ); }) : _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, item.value) }), translate('clearFilter', item) ) ); }) ) ); } }]); return CurrentRefinements; }(_react.Component); CurrentRefinements.propTypes = { translate: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string })).isRequired, refine: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, transformItems: _propTypes2.default.func }; CurrentRefinements.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ clearFilter: '✕' })(CurrentRefinements); /***/ }), /* 379 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('HierarchicalMenu'); var itemsPropType = _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.string, count: _propTypes2.default.number.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var HierarchicalMenu = function (_Component) { _inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props; var createURL = _this$props.createURL; var refine = _this$props.refine; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink'), { onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), ' ', _react2.default.createElement( 'span', cx('itemCount'), item.count ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(HierarchicalMenu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine']))); } }]); return HierarchicalMenu; }(_react.Component); HierarchicalMenu.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, items: itemsPropType, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; HierarchicalMenu.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /***/ }), /* 380 */ /***/ (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; }; exports.default = Highlight; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(345); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlight(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_highlightResult' }, props)); } Highlight.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 381 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('Hits'); var Hits = function (_Component) { _inherits(Hits, _Component); function Hits() { _classCallCheck(this, Hits); return _possibleConstructorReturn(this, (Hits.__proto__ || Object.getPrototypeOf(Hits)).apply(this, arguments)); } _createClass(Hits, [{ key: 'render', value: function render() { var _props = this.props; var ItemComponent = _props.hitComponent; var hits = _props.hits; return _react2.default.createElement( 'div', cx('root'), hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }) ); } }]); return Hits; }(_react.Component); Hits.propTypes = { hits: _propTypes2.default.array, hitComponent: _propTypes2.default.func.isRequired }; /* eslint-disable react/display-name */ Hits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; /* eslint-enable react/display-name */ exports.default = Hits; /***/ }), /* 382 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(347); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('HitsPerPage'); var HitsPerPage = function (_Component) { _inherits(HitsPerPage, _Component); function HitsPerPage() { _classCallCheck(this, HitsPerPage); return _possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments)); } _createClass(HitsPerPage, [{ key: 'render', value: function render() { var _props = this.props; var currentRefinement = _props.currentRefinement; var refine = _props.refine; var items = _props.items; return _react2.default.createElement(_Select2.default, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx }); } }]); return HitsPerPage; }(_react.Component); HitsPerPage.propTypes = { refine: _propTypes2.default.func.isRequired, currentRefinement: _propTypes2.default.number.isRequired, transformItems: _propTypes2.default.func, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ /** * Number of hits to display. */ value: _propTypes2.default.number.isRequired, /** * Label to display on the option. */ label: _propTypes2.default.string })) }; exports.default = HitsPerPage; /***/ }), /* 383 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); 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 cx = (0, _classNames2.default)('InfiniteHits'); var InfiniteHits = function (_Component) { _inherits(InfiniteHits, _Component); function InfiniteHits() { _classCallCheck(this, InfiniteHits); return _possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments)); } _createClass(InfiniteHits, [{ key: 'render', value: function render() { var _props = this.props; var ItemComponent = _props.hitComponent; var hits = _props.hits; var hasMore = _props.hasMore; var refine = _props.refine; var translate = _props.translate; var renderedHits = hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }); var loadMoreButton = hasMore ? _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { onClick: function onClick() { return refine(); } }), translate('loadMore') ) : _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { disabled: true }), translate('loadMore') ); return _react2.default.createElement( 'div', cx('root'), renderedHits, loadMoreButton ); } }]); return InfiniteHits; }(_react.Component); InfiniteHits.propTypes = { hits: _propTypes2.default.array, hitComponent: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]).isRequired, hasMore: _propTypes2.default.bool.isRequired, refine: _propTypes2.default.func.isRequired, translate: _propTypes2.default.func.isRequired }; /* eslint-disable react/display-name */ InfiniteHits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; /* eslint-enable react/display-name */ exports.default = (0, _translatable2.default)({ loadMore: 'Load more' })(InfiniteHits); /***/ }), /* 384 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); 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 LinkList = function (_Component) { _inherits(LinkList, _Component); function LinkList() { _classCallCheck(this, LinkList); return _possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments)); } _createClass(LinkList, [{ key: 'render', value: function render() { var _props = this.props; var cx = _props.cx; var createURL = _props.createURL; var items = _props.items; var onSelect = _props.onSelect; var canRefine = _props.canRefine; return _react2.default.createElement( 'ul', cx('root', !canRefine && 'noRefinement'), items.map(function (item) { return _react2.default.createElement( 'li', _extends({ key: (0, _has3.default)(item, 'key') ? item.key : item.value }, cx('item', item.selected && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), { disabled: item.disabled }), item.disabled ? _react2.default.createElement( 'span', cx('itemLink', 'itemLinkDisabled'), (0, _has3.default)(item, 'label') ? item.label : item.value ) : _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.selected && 'itemLinkSelected'), { 'aria-label': item.ariaLabel, href: createURL(item.value), onClick: onSelect.bind(null, item.value) }), (0, _has3.default)(item, 'label') ? item.label : item.value ) ); }) ); } }]); return LinkList; }(_react.Component); LinkList.propTypes = { cx: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number, _propTypes2.default.object]).isRequired, key: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), label: _propTypes2.default.node, modifier: _propTypes2.default.string, ariaLabel: _propTypes2.default.string, disabled: _propTypes2.default.bool })), onSelect: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired }; exports.default = LinkList; /***/ }), /* 385 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); var _Highlight = __webpack_require__(235); var _Highlight2 = _interopRequireDefault(_Highlight); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('Menu'); var Menu = function (_Component) { _inherits(Menu, _Component); function Menu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Menu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item, resetQuery) { var createURL = _this.props.createURL; var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.isRefined && 'itemLinkSelected'), { onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }, _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Menu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']))); } }]); return Menu; }(_react.Component); Menu.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, searchForItems: _propTypes2.default.func.isRequired, withSearchBox: _propTypes2.default.bool, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.string.isRequired, count: _propTypes2.default.number.isRequired, isRefined: _propTypes2.default.bool.isRequired })), isFromSearch: _propTypes2.default.bool.isRequired, canRefine: _propTypes2.default.bool.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; Menu.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(Menu); /***/ }), /* 386 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); 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 cx = (0, _classNames2.default)('MultiRange'); var MultiRange = function (_Component) { _inherits(MultiRange, _Component); function MultiRange() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MultiRange); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props; var refine = _this$props.refine; var translate = _this$props.translate; var label = item.value === '' ? translate('all') : item.label; return _react2.default.createElement( 'label', cx(item.value === '' && 'itemAll'), _react2.default.createElement('input', _extends({}, cx('itemRadio', item.isRefined && 'itemRadioSelected'), { type: 'radio', checked: item.isRefined, disabled: item.noRefinement, onChange: refine.bind(null, item.value) })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MultiRange, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props; var items = _props.items; var canRefine = _props.canRefine; return _react2.default.createElement(_List2.default, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx, items: items.map(function (item) { return _extends({}, item, { key: item.value }); }) }); } }]); return MultiRange; }(_react.Component); MultiRange.propTypes = { items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.node.isRequired, value: _propTypes2.default.string.isRequired, isRefined: _propTypes2.default.bool.isRequired, noRefinement: _propTypes2.default.bool.isRequired })).isRequired, refine: _propTypes2.default.func.isRequired, transformItems: _propTypes2.default.func, canRefine: _propTypes2.default.bool.isRequired, translate: _propTypes2.default.func.isRequired }; MultiRange.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ all: 'All' })(MultiRange); /***/ }), /* 387 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _range2 = __webpack_require__(424); var _range3 = _interopRequireDefault(_range2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _LinkList = __webpack_require__(384); var _LinkList2 = _interopRequireDefault(_LinkList); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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 _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 cx = (0, _classNames2.default)('Pagination'); function getPagesDisplayedCount(padding, total) { return Math.min(2 * padding + 1, total); } function calculatePaddingLeft(current, padding, total, totalDisplayedPages) { if (current <= padding) { return current; } if (current >= total - padding) { return totalDisplayedPages - (total - current); } return padding; } function getPages(page, total, padding) { var totalDisplayedPages = getPagesDisplayedCount(padding, total); if (totalDisplayedPages === total) return (0, _range3.default)(1, total + 1); var paddingLeft = calculatePaddingLeft(page, padding, total, totalDisplayedPages); var paddingRight = totalDisplayedPages - paddingLeft; var first = page - paddingLeft; var last = page + paddingRight; return (0, _range3.default)(first + 1, last + 1); } var Pagination = function (_Component) { _inherits(Pagination, _Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments)); } _createClass(Pagination, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'getItem', value: function getItem(modifier, translationKey, value) { var _props = this.props; var nbPages = _props.nbPages; var maxPages = _props.maxPages; var translate = _props.translate; return { key: modifier + '.' + value, modifier: modifier, disabled: value < 1 || value >= Math.min(maxPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate('aria' + (0, _utils.capitalize)(translationKey), value) }; } }, { key: 'render', value: function render() { var _props2 = this.props; var nbPages = _props2.nbPages; var maxPages = _props2.maxPages; var currentRefinement = _props2.currentRefinement; var pagesPadding = _props2.pagesPadding; var showFirst = _props2.showFirst; var showPrevious = _props2.showPrevious; var showNext = _props2.showNext; var showLast = _props2.showLast; var refine = _props2.refine; var createURL = _props2.createURL; var translate = _props2.translate; var ListComponent = _props2.listComponent; var otherProps = _objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']); var totalPages = Math.min(nbPages, maxPages); var lastPage = totalPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'itemFirst', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'itemPrevious', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) { return { key: value, modifier: 'itemPage', label: translate('page', value), value: value, selected: value === currentRefinement, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'itemNext', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'itemLast', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return _react2.default.createElement(ListComponent, _extends({}, otherProps, { cx: cx, items: items, onSelect: refine, createURL: createURL })); } }]); return Pagination; }(_react.Component); Pagination.propTypes = { nbPages: _propTypes2.default.number.isRequired, currentRefinement: _propTypes2.default.number.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, translate: _propTypes2.default.func.isRequired, listComponent: _propTypes2.default.func, showFirst: _propTypes2.default.bool, showPrevious: _propTypes2.default.bool, showNext: _propTypes2.default.bool, showLast: _propTypes2.default.bool, pagesPadding: _propTypes2.default.number, maxPages: _propTypes2.default.number }; Pagination.defaultProps = { listComponent: _LinkList2.default, showFirst: true, showPrevious: true, showNext: true, showLast: false, pagesPadding: 3, maxPages: Infinity }; Pagination.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ previous: '‹', next: '›', first: '«', last: '»', page: function page(currentRefinement) { return currentRefinement.toString(); }, ariaPrevious: 'Previous page', ariaNext: 'Next page', ariaFirst: 'First page', ariaLast: 'Last page', ariaPage: function ariaPage(currentRefinement) { return 'Page ' + currentRefinement.toString(); } })(Pagination); /***/ }), /* 388 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('Panel'); var Panel = function (_Component) { _inherits(Panel, _Component); _createClass(Panel, [{ key: 'getChildContext', value: function getChildContext() { return { canRefine: this.canRefine }; } }]); function Panel(props) { _classCallCheck(this, Panel); var _this = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props)); _this.state = { canRefine: true }; _this.canRefine = function (canRefine) { _this.setState({ canRefine: canRefine }); }; return _this; } _createClass(Panel, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', cx('root', !this.state.canRefine && 'noRefinement'), _react2.default.createElement( 'h5', cx('title'), this.props.title ), this.props.children ); } }]); return Panel; }(_react.Component); Panel.propTypes = { title: _propTypes2.default.string.isRequired, children: _propTypes2.default.node }; Panel.childContextTypes = { canRefine: _propTypes2.default.func }; exports.default = Panel; /***/ }), /* 389 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362' }, _react2.default.createElement( 'linearGradient', { id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' }, _react2.default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }), _react2.default.createElement('stop', { offset: '1', stopColor: '#3369E7' }) ), _react2.default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }), _react2.default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }), _react2.default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' }) ); }; /* eslint-enable max-len */ var PoweredBy = function (_Component) { _inherits(PoweredBy, _Component); function PoweredBy() { _classCallCheck(this, PoweredBy); return _possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments)); } _createClass(PoweredBy, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var url = _props.url; return _react2.default.createElement( 'div', cx('root'), _react2.default.createElement( 'span', cx('searchBy'), translate('searchBy'), ' ' ), _react2.default.createElement( 'a', _extends({ href: url, target: '_blank' }, cx('algoliaLink')), _react2.default.createElement(AlgoliaLogo, null) ) ); } }]); return PoweredBy; }(_react.Component); PoweredBy.propTypes = { url: _propTypes2.default.string.isRequired, translate: _propTypes2.default.func.isRequired }; exports.default = (0, _translatable2.default)({ searchBy: 'Search by' })(PoweredBy); /***/ }), /* 390 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isNaN2 = __webpack_require__(218); var _isNaN3 = _interopRequireDefault(_isNaN2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('RangeInput'); var RangeInput = function (_Component) { _inherits(RangeInput, _Component); function RangeInput(props) { _classCallCheck(this, RangeInput); var _this = _possibleConstructorReturn(this, (RangeInput.__proto__ || Object.getPrototypeOf(RangeInput)).call(this, props)); _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); if (!(0, _isNaN3.default)(parseFloat(_this.state.from, 10)) && !(0, _isNaN3.default)(parseFloat(_this.state.to, 10))) { _this.props.refine({ min: _this.state.from, max: _this.state.to }); } }; _this.state = _this.props.canRefine ? { from: props.currentRefinement.min, to: props.currentRefinement.max } : { from: '', to: '' }; return _this; } _createClass(RangeInput, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.canRefine) { this.setState({ from: nextProps.currentRefinement.min, to: nextProps.currentRefinement.max }); } if (this.context.canRefine) this.context.canRefine(nextProps.canRefine); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var canRefine = _props.canRefine; return _react2.default.createElement( 'form', _extends({}, cx('root', !canRefine && 'noRefinement'), { onSubmit: this.onSubmit }), _react2.default.createElement( 'fieldset', _extends({ disabled: !canRefine }, cx('fieldset')), _react2.default.createElement( 'label', cx('labelMin'), _react2.default.createElement('input', _extends({}, cx('inputMin'), { type: 'number', value: this.state.from, onChange: function onChange(e) { return _this2.setState({ from: e.target.value }); } })) ), _react2.default.createElement( 'span', cx('separator'), translate('separator') ), _react2.default.createElement( 'label', cx('labelMax'), _react2.default.createElement('input', _extends({}, cx('inputMax'), { type: 'number', value: this.state.to, onChange: function onChange(e) { return _this2.setState({ to: e.target.value }); } })) ), _react2.default.createElement( 'button', _extends({}, cx('submit'), { type: 'submit' }), translate('submit') ) ) ); } }]); return RangeInput; }(_react.Component); RangeInput.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, min: _propTypes2.default.number, max: _propTypes2.default.number, currentRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number, max: _propTypes2.default.number }), canRefine: _propTypes2.default.bool.isRequired }; RangeInput.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ submit: 'ok', separator: 'to' })(RangeInput); /***/ }), /* 391 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _Highlight = __webpack_require__(235); var _Highlight2 = _interopRequireDefault(_Highlight); 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 cx = (0, _classNames2.default)('RefinementList'); var RefinementList = function (_Component) { _inherits(RefinementList, _Component); function RefinementList(props) { _classCallCheck(this, RefinementList); var _this = _possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props)); _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }; _this.renderItem = function (item, resetQuery) { var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( 'label', null, _react2.default.createElement('input', _extends({}, cx('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), { type: 'checkbox', checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item, resetQuery); } })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }; _this.state = { query: '' }; return _this; } _createClass(RefinementList, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement( 'div', null, _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']), { query: this.state.query })) ); } }]); return RefinementList; }(_react.Component); RefinementList.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, searchForItems: _propTypes2.default.func.isRequired, withSearchBox: _propTypes2.default.bool, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.arrayOf(_propTypes2.default.string).isRequired, count: _propTypes2.default.number.isRequired, isRefined: _propTypes2.default.bool.isRequired })), isFromSearch: _propTypes2.default.bool.isRequired, canRefine: _propTypes2.default.bool.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; RefinementList.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(RefinementList); /***/ }), /* 392 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _reactDom = __webpack_require__(429); 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 ScrollTo = function (_Component) { _inherits(ScrollTo, _Component); function ScrollTo() { _classCallCheck(this, ScrollTo); return _possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments)); } _createClass(ScrollTo, [{ key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var value = this.props.value; if (value !== prevProps.value) { var el = (0, _reactDom.findDOMNode)(this); el.scrollIntoView(); } } }, { key: 'render', value: function render() { return _react.Children.only(this.props.children); } }]); return ScrollTo; }(_react.Component); ScrollTo.propTypes = { value: _propTypes2.default.any, children: _propTypes2.default.node }; exports.default = ScrollTo; /***/ }), /* 393 */ /***/ (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; }; exports.default = Snippet; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(345); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Snippet(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_snippetResult' }, props)); } Snippet.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 394 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(347); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('SortBy'); var SortBy = function (_Component) { _inherits(SortBy, _Component); function SortBy() { var _ref; var _temp, _this, _ret; _classCallCheck(this, SortBy); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = SortBy.__proto__ || Object.getPrototypeOf(SortBy)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(SortBy, [{ key: 'render', value: function render() { var _props = this.props; var refine = _props.refine; var items = _props.items; var currentRefinement = _props.currentRefinement; return _react2.default.createElement(_Select2.default, { cx: cx, selectedItem: currentRefinement, onSelect: refine, items: items }); } }]); return SortBy; }(_react.Component); SortBy.propTypes = { refine: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string, value: _propTypes2.default.string.isRequired })).isRequired, currentRefinement: _propTypes2.default.string.isRequired, transformItems: _propTypes2.default.func }; exports.default = SortBy; /***/ }), /* 395 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('StarRating'); var StarRating = function (_Component) { _inherits(StarRating, _Component); function StarRating() { _classCallCheck(this, StarRating); return _possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments)); } _createClass(StarRating, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'onClick', value: function onClick(min, max, e) { e.preventDefault(); e.stopPropagation(); if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) { this.props.refine({ min: this.props.min, max: this.props.max }); } else { this.props.refine({ min: min, max: max }); } } }, { key: 'buildItem', value: function buildItem(_ref) { var max = _ref.max; var lowerBound = _ref.lowerBound; var count = _ref.count; var translate = _ref.translate; var createURL = _ref.createURL; var isLastSelectableItem = _ref.isLastSelectableItem; var disabled = !count; var isCurrentMinLower = this.props.currentRefinement.min < lowerBound; var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max; var icons = []; for (var icon = 0; icon < max; icon++) { var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon'; icons.push(_react2.default.createElement('span', _extends({ key: icon }, cx(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled')))); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var StarsWrapper = isLastAndSelect ? 'div' : 'a'; var onClickHandler = isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return _react2.default.createElement( StarsWrapper, _extends({}, cx('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), { disabled: disabled, key: lowerBound }, onClickHandler), icons, _react2.default.createElement( 'span', cx('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'), translate('ratingLabel') ), _react2.default.createElement( 'span', null, ' ' ), _react2.default.createElement( 'span', cx('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'), count ) ); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var refine = _props.refine; var min = _props.min; var max = _props.max; var count = _props.count; var createURL = _props.createURL; var canRefine = _props.canRefine; var items = []; var _loop = function _loop(i) { var hasCount = !(0, _isEmpty3.default)(count.filter(function (item) { return Number(item.value) === i; })); var lastSelectableItem = count.reduce(function (acc, item) { return item.value < acc.value || !acc.value && hasCount ? item : acc; }, {}); var itemCount = count.reduce(function (acc, item) { return item.value >= i && hasCount ? acc + item.count : acc; }, 0); items.push(_this2.buildItem({ lowerBound: i, max: max, refine: refine, count: itemCount, translate: translate, createURL: createURL, isLastSelectableItem: i === Number(lastSelectableItem.value) })); }; for (var i = max; i >= min; i--) { _loop(i); } return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), items ); } }]); return StarRating; }(_react.Component); StarRating.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, min: _propTypes2.default.number, max: _propTypes2.default.number, currentRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number, max: _propTypes2.default.number }), count: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.string, count: _propTypes2.default.number })), canRefine: _propTypes2.default.bool.isRequired }; StarRating.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ ratingLabel: ' & Up' })(StarRating); /***/ }), /* 396 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('Stats'); var Stats = function (_Component) { _inherits(Stats, _Component); function Stats() { _classCallCheck(this, Stats); return _possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments)); } _createClass(Stats, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var nbHits = _props.nbHits; var processingTimeMS = _props.processingTimeMS; return _react2.default.createElement( 'span', cx('root'), translate('stats', nbHits, processingTimeMS) ); } }]); return Stats; }(_react.Component); Stats.propTypes = { translate: _propTypes2.default.func.isRequired, nbHits: _propTypes2.default.number.isRequired, processingTimeMS: _propTypes2.default.number.isRequired }; exports.default = (0, _translatable2.default)({ stats: function stats(n, ms) { return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms'; } })(Stats); /***/ }), /* 397 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); 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 cx = (0, _classNames2.default)('Toggle'); var Toggle = function (_Component) { _inherits(Toggle, _Component); function Toggle() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Toggle); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.checked); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Toggle, [{ key: 'render', value: function render() { var _props = this.props; var currentRefinement = _props.currentRefinement; var label = _props.label; return _react2.default.createElement( 'label', cx('root'), _react2.default.createElement('input', _extends({}, cx('checkbox'), { type: 'checkbox', checked: currentRefinement, onChange: this.onChange })), _react2.default.createElement( 'span', cx('label'), label ) ); } }]); return Toggle; }(_react.Component); Toggle.propTypes = { currentRefinement: _propTypes2.default.bool.isRequired, refine: _propTypes2.default.func.isRequired, label: _propTypes2.default.string.isRequired }; exports.default = Toggle; /***/ }), /* 398 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); 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; } /* eslint valid-jsdoc: 0 */ /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @example * import {InstantSearch, Index, SearchBox, Hits, Configure} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch appId="" apiKey="" indexName="index1"> <SearchBox/> <Configure hitsPerPage={1} /> <Index indexName="index1"> <Hits /> </Index> <Index indexName="index2"> <Hits /> </Index> </InstantSearch> * ); * } */ var Index = function (_Component) { _inherits(Index, _Component); function Index() { _classCallCheck(this, Index); return _possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).apply(this, arguments)); } _createClass(Index, [{ key: 'getChildContext', value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexName } }; } }, { key: 'render', value: function render() { var childrenCount = _react.Children.count(this.props.children); var _props$root = this.props.root; var Root = _props$root.Root; var props = _props$root.props; if (childrenCount === 0) return null;else return _react2.default.createElement( Root, props, this.props.children ); } }]); return Index; }(_react.Component); Index.propTypes = { // @TODO: These props are currently constant. indexName: _propTypes2.default.string.isRequired, children: _propTypes2.default.node, root: _propTypes2.default.shape({ Root: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]), props: _propTypes2.default.object }).isRequired }; Index.childContextTypes = { // @TODO: more precise widgets manager propType multiIndexContext: _propTypes2.default.object.isRequired }; exports.default = Index; /***/ }), /* 399 */ /***/ (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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _createInstantSearchManager = __webpack_require__(400); var _createInstantSearchManager2 = _interopRequireDefault(_createInstantSearchManager); 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; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } else if (props.searchState && !nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @example * import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch * appId="appId" * apiKey="apiKey" * indexName="indexName" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); * } */ var InstantSearch = function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { _classCallCheck(this, InstantSearch); var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = (0, _createInstantSearchManager2.default)({ indexName: props.indexName, searchParameters: props.searchParameters, algoliaClient: props.algoliaClient, initialState: initialState }); return _this; } _createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this) } }; } return { ais: _extends({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = _react.Children.count(this.props.children); var _props$root = this.props.root; var Root = _props$root.Root; var props = _props$root.props; if (childrenCount === 0) return null;else return _react2.default.createElement( Root, props, this.props.children ); } }]); return InstantSearch; }(_react.Component); InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: _propTypes2.default.string.isRequired, algoliaClient: _propTypes2.default.object.isRequired, searchParameters: _propTypes2.default.object, createURL: _propTypes2.default.func, searchState: _propTypes2.default.object, onSearchStateChange: _propTypes2.default.func, children: _propTypes2.default.node, root: _propTypes2.default.shape({ Root: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]), props: _propTypes2.default.object }).isRequired }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: _propTypes2.default.object.isRequired }; exports.default = InstantSearch; /***/ }), /* 400 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); 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; }; exports.default = createInstantSearchManager; var _algoliasearchHelper = __webpack_require__(214); var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper); var _createWidgetsManager = __webpack_require__(402); var _createWidgetsManager2 = _interopRequireDefault(_createWidgetsManager); var _createStore = __webpack_require__(401); var _createStore2 = _interopRequireDefault(_createStore); var _highlightTags = __webpack_require__(213); var _highlightTags2 = _interopRequireDefault(_highlightTags); 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; } /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName; var _ref$initialState = _ref.initialState; var initialState = _ref$initialState === undefined ? {} : _ref$initialState; var algoliaClient = _ref.algoliaClient; var _ref$searchParameters = _ref.searchParameters; var searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters; var baseSP = new _algoliasearchHelper.SearchParameters(_extends({}, searchParameters, { index: indexName }, _highlightTags2.default)); var helper = (0, _algoliasearchHelper2.default)(algoliaClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); var derivedHelpers = {}; var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used. var initialSearchParameters = helper.state; var widgetsManager = (0, _createWidgetsManager2.default)(onWidgetsUpdate); var store = (0, _createStore2.default)({ widgets: initialState, metadata: [], results: null, error: null, searching: false }); var skip = false; function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { indexMapping = {}; var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !widget.multiIndexContext; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); indexMapping[sharedParameters.index] = indexName; var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.multiIndexContext && widget.multiIndexContext.targetedIndex !== indexName; }).reduce(function (indices, widget) { var targetedIndex = widget.multiIndexContext.targetedIndex; var index = indices.find(function (i) { return i.targetedIndex === targetedIndex; }); if (index) { index.widgets.push(widget); } else { indices.push({ targetedIndex: targetedIndex, widgets: [widget] }); } return indices; }, []); var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.multiIndexContext && widget.multiIndexContext.targetedIndex === indexName; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state); var sharedParameters = _getSearchParameters.sharedParameters; var mainIndexParameters = _getSearchParameters.mainIndexParameters; var derivatedWidgets = _getSearchParameters.derivatedWidgets; Object.keys(derivedHelpers).forEach(function (key) { return derivedHelpers[key].detach(); }); derivedHelpers = {}; helper.setState(sharedParameters); derivatedWidgets.forEach(function (derivatedSearchParameters) { var index = derivatedSearchParameters.targetedIndex; var derivedHelper = helper.derive(function () { var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters.setIndex(index)); indexMapping[parameters.index] = index; return parameters; }); derivedHelper.on('result', handleSearchSuccess); derivedHelper.on('error', handleSearchError); derivedHelpers[index] = derivedHelper; }); helper.setState(mainIndexParameters); helper.search(); } } function handleSearchSuccess(content) { var state = store.getState(); var results = state.results ? state.results : []; if (!(0, _isEmpty3.default)(derivedHelpers)) { results[indexMapping[content.index]] = content; } else { results = content; } var nextState = (0, _omit3.default)(_extends({}, store.getState(), { results: results, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var nextState = (0, _omit3.default)(_extends({}, store.getState(), { error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(nextSearchState) { store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(nextSearchState.facetName, nextSearchState.query).then(function (content) { var _extends2; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty(_extends2, nextSearchState.facetName, content.facetHits), _defineProperty(_extends2, 'query', nextSearchState.query), _extends2)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex, skipSearch: skipSearch }; } /***/ }), /* 401 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createStore; function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } /***/ }), /* 402 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createWidgetsManager; var _utils = __webpack_require__(58); function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; (0, _utils.defer)(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } /***/ }), /* 403 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withKeysPropType = exports.stateManagerPropType = exports.configManagerPropType = undefined; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var configManagerPropType = exports.configManagerPropType = _propTypes2.default.shape({ register: _propTypes2.default.func.isRequired, swap: _propTypes2.default.func.isRequired, unregister: _propTypes2.default.func.isRequired }); var stateManagerPropType = exports.stateManagerPropType = _propTypes2.default.shape({ createURL: _propTypes2.default.func.isRequired, setState: _propTypes2.default.func.isRequired, getState: _propTypes2.default.func.isRequired, unlisten: _propTypes2.default.func.isRequired }); var withKeysPropType = exports.withKeysPropType = function withKeysPropType(keys) { return function (props, propName, componentName) { var prop = props[propName]; if (prop) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var key = _step.value; if (keys.indexOf(key) === -1) { return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.')); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } return undefined; }; }; /***/ }), /* 404 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {module.exports = AlgoliaSearchCore; var errors = __webpack_require__(215); var exitPromise = __webpack_require__(412); var IndexCore = __webpack_require__(405); var store = __webpack_require__(416); // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API. * Set to 'https:' to force using https. * Default to document.location.protocol in browsers * @param {Object|Array} [opts.hosts={ * read: [this.applicationID + '-dsn.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]), * write: [this.applicationID + '.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]) - The hosts to use for Algolia Search API. * If you provide them, you will less benefit from our HA implementation */ function AlgoliaSearchCore(applicationID, apiKey, opts) { var debug = __webpack_require__(216)('algoliasearch'); var clone = __webpack_require__(119); var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)'; if (opts._allowEmptyCredentials !== true && !applicationID) { throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage); } if (opts._allowEmptyCredentials !== true && !apiKey) { throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage); } this.applicationID = applicationID; this.apiKey = apiKey; this.hosts = { read: [], write: [] }; opts = opts || {}; var protocol = opts.protocol || 'https:'; this._timeouts = opts.timeouts || { connect: 1 * 1000, // 500ms connect is GPRS latency read: 2 * 1000, write: 30 * 1000 }; // backward compat, if opts.timeout is passed, we use it to configure all timeouts like before if (opts.timeout) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout; } // while we advocate for colon-at-the-end values: 'http:' for `opts.protocol` // we also accept `http` and `https`. It's a common error. if (!/:$/.test(protocol)) { protocol = protocol + ':'; } if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)'); } this._checkAppIdData(); if (!opts.hosts) { var defaultHosts = map(this._shuffleResult, function(hostNumber) { return applicationID + '-' + hostNumber + '.algolianet.com'; }); // no hosts given, compute defaults this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts); this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts); } else if (isArray(opts.hosts)) { // when passing custom hosts, we need to have a different host index if the number // of write/read hosts are different. this.hosts.read = clone(opts.hosts); this.hosts.write = clone(opts.hosts); } else { this.hosts.read = clone(opts.hosts.read); this.hosts.write = clone(opts.hosts.write); } // add protocol and lowercase hosts this.hosts.read = map(this.hosts.read, prepareHost(protocol)); this.hosts.write = map(this.hosts.write, prepareHost(protocol)); this.extraHeaders = []; // In some situations you might want to warm the cache this.cache = opts._cache || {}; this._ua = opts._ua; this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache; this._useFallback = opts.useFallback === undefined ? true : opts.useFallback; this._setTimeout = opts._setTimeout; debug('init done, %j', this); } /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearchCore.prototype.initIndex = function(indexName) { return new IndexCore(this, indexName); }; /** * Add an extra field to the HTTP request * * @param name the header field name * @param value the header field value */ AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) { this.extraHeaders.push({ name: name.toLowerCase(), value: value }); }; /** * Augment sent x-algolia-agent with more data, each agent part * is automatically separated from the others by a semicolon; * * @param algoliaAgent the agent to add */ AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) { if (this._ua.indexOf(';' + algoliaAgent) === -1) { this._ua += ';' + algoliaAgent; } }; /* * Wrapper that try all hosts to maximize the quality of service */ AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) { this._checkAppIdData(); var requestDebug = __webpack_require__(216)('algoliasearch:' + initialOpts.url); var body; var additionalUA = initialOpts.additionalUA || ''; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders(additionalUA, false); } else { headers = this._computeRequestHeaders(additionalUA); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); var cacheID; if (client._useCache) { cacheID = initialOpts.url; } // as we sometime use POST requests to pass parameters (like query='aa'), // the cacheID must also include the body to be different between calls if (client._useCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (client._useCache && cache && cache[cacheID] !== undefined) { requestDebug('serving response from cache'); return client._promise.resolve(JSON.parse(cache[cacheID])); } // if we reached max tries if (tries >= client.hosts[initialOpts.hostType].length) { if (!hasFallback || usingFallback) { requestDebug('could not get any response'); // then stop return client._promise.reject(new errors.AlgoliaSearchError( 'Cannot connect to the AlgoliaSearch API.' + ' Send an email to [email protected] to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders(additionalUA); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); client._setHostIndexByType(0, initialOpts.hostType); usingFallback = true; // the current request is now using fallback return doRequest(client._request.fallback, reqOpts); } var currentHost = client._getHostByType(initialOpts.hostType); var url = currentHost + reqOpts.url; var options = { body: reqOpts.body, jsonBody: reqOpts.jsonBody, method: reqOpts.method, headers: headers, timeouts: reqOpts.timeouts, debug: requestDebug }; requestDebug('method: %s, url: %s, headers: %j, timeouts: %d', options.method, url, options.headers, options.timeouts); if (requester === client._request.fallback) { requestDebug('using fallback'); } // `requester` is any of this._request or this._request.fallback // thus it needs to be called using the client as context return requester.call(client, url, options).then(success, tryFallback); function success(httpResponse) { // compute the status of the response, // // When in browser mode, using XDR or JSONP, we have no statusCode available // So we rely on our API response `status` property. // But `waitTask` can set a `status` property which is not the statusCode (it's the task status) // So we check if there's a `message` along `status` and it means it's an error // // That's the only case where we have a response.status that's not the http statusCode var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status || // this is important to check the request statusCode AFTER the body eventual // statusCode because some implementations (jQuery XDomainRequest transport) may // send statusCode 200 while we had an error httpResponse.statusCode || // When in browser mode, using XDR or JSONP // we default to success when no error (no response.status && response.message) // If there was a JSON.parse() error then body is null and it fails httpResponse && httpResponse.body && 200; requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j', httpResponse.statusCode, status, httpResponse.headers); var httpResponseOk = Math.floor(status / 100) === 2; var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime, statusCode: status }); if (httpResponseOk) { if (client._useCache && cache) { cache[cacheID] = httpResponse.responseText; } return httpResponse.body; } var shouldRetry = Math.floor(status / 100) !== 4; if (shouldRetry) { tries += 1; return retryRequest(); } requestDebug('unrecoverable error'); // no success and no retry => fail var unrecoverableError = new errors.AlgoliaSearchError( httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status} ); return client._promise.reject(unrecoverableError); } function tryFallback(err) { // error cases: // While not in fallback mode: // - CORS not supported // - network error // While in fallback mode: // - timeout // - network error // - badly formatted JSONP (script loaded, did not call our callback) // In both cases: // - uncaught exception occurs (TypeError) requestDebug('error: %s, stack: %s', err.message, err.stack); var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime }); if (!(err instanceof errors.AlgoliaSearchError)) { err = new errors.Unknown(err && err.message, err); } tries += 1; // stop the request implementation when: if ( // we did not generate this error, // it comes from a throw in some other piece of code err instanceof errors.Unknown || // server sent unparsable JSON err instanceof errors.UnparsableJSON || // max tries and already using fallback or no fallback tries >= client.hosts[initialOpts.hostType].length && (usingFallback || !hasFallback)) { // stop request implementation for this command err.debugData = debugData; return client._promise.reject(err); } // When a timeout occured, retry by raising timeout if (err instanceof errors.RequestTimeout) { return retryRequestWithHigherTimeout(); } return retryRequest(); } function retryRequest() { requestDebug('retrying request'); client._incrementHostIndex(initialOpts.hostType); return doRequest(requester, reqOpts); } function retryRequestWithHigherTimeout() { requestDebug('retrying request with higher timeout'); client._incrementHostIndex(initialOpts.hostType); client._incrementTimeoutMultipler(); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); return doRequest(requester, reqOpts); } } var promise = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType) } ); // either we have a callback // either we are using promises if (initialOpts.callback) { promise.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, content); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { return promise; } }; /* * Transform search param object in query string * @param {object} args arguments to add to the current query string * @param {string} params current query string * @return {string} the final query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) { var forEach = __webpack_require__(110); var ua = additionalUA ? this._ua + ';' + additionalUA : this._ua; var requestHeaders = { 'x-algolia-agent': ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (withAPIKey !== false) { requestHeaders['x-algolia-api-key'] = this.apiKey; } if (this.userToken) { requestHeaders['x-algolia-usertoken'] = this.userToken; } if (this.securityTags) { requestHeaders['x-algolia-tagfilters'] = this.securityTags; } if (this.extraHeaders) { forEach(this.extraHeaders, function addToRequestHeaders(header) { requestHeaders[header.name] = header.value; }); } return requestHeaders; }; /** * Search through multiple indices at the same time * @param {Object[]} queries An array of queries you want to run. * @param {string} queries[].indexName The index name you want to target * @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params` * @param {Object} queries[].params Any search param like hitsPerPage, .. * @param {Function} callback Callback to be called * @return {Promise|undefined} Returns a promise if no callback given */ AlgoliaSearchCore.prototype.search = function(queries, opts, callback) { var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: client.search(arrayOfQueries[, callback])'; if (!isArray(queries)) { throw new Error(usage); } if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } var client = this; var postObj = { requests: map(queries, function prepareRequest(query) { var params = ''; // allow query.query // so we are mimicing the index.search(query, params) method // {indexName:, query:, params:} if (query.query !== undefined) { params += 'query=' + encodeURIComponent(query.query); } return { indexName: query.indexName, params: client._getSearchParams(query.params, params) }; }) }; var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) { return requestId + '=' + encodeURIComponent( '/1/indexes/' + encodeURIComponent(request.indexName) + '?' + request.params ); }).join('&'); var url = '/1/indexes/*/queries'; if (opts.strategy !== undefined) { url += '?strategy=' + opts.strategy; } return this._jsonRequest({ cache: this.cache, method: 'POST', url: url, body: postObj, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/*', body: { params: JSONPParams } }, callback: callback }); }; /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ AlgoliaSearchCore.prototype.setSecurityTags = function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.securityTags = tags; }; /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ AlgoliaSearchCore.prototype.setUserToken = function(userToken) { this.userToken = userToken; }; /** * Clear all queries in client's cache * @return undefined */ AlgoliaSearchCore.prototype.clearCache = function() { this.cache = {}; }; /** * Set the number of milliseconds a request can take before automatically being terminated. * @deprecated * @param {Number} milliseconds */ AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) { if (milliseconds) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds; } }; /** * Set the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) { this._timeouts = timeouts; }; /** * Get the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.getTimeouts = function() { return this._timeouts; }; AlgoliaSearchCore.prototype._getAppIdData = function() { var data = store.get(this.applicationID); if (data !== null) this._cacheAppIdData(data); return data; }; AlgoliaSearchCore.prototype._setAppIdData = function(data) { data.lastChange = (new Date()).getTime(); this._cacheAppIdData(data); return store.set(this.applicationID, data); }; AlgoliaSearchCore.prototype._checkAppIdData = function() { var data = this._getAppIdData(); var now = (new Date()).getTime(); if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) { return this._resetInitialAppIdData(data); } return data; }; AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) { var newData = data || {}; newData.hostIndexes = {read: 0, write: 0}; newData.timeoutMultiplier = 1; newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]); return this._setAppIdData(newData); }; AlgoliaSearchCore.prototype._cacheAppIdData = function(data) { this._hostIndexes = data.hostIndexes; this._timeoutMultiplier = data.timeoutMultiplier; this._shuffleResult = data.shuffleResult; }; AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) { var foreach = __webpack_require__(110); var currentData = this._getAppIdData(); foreach(newData, function(value, key) { currentData[key] = value; }); return this._setAppIdData(currentData); }; AlgoliaSearchCore.prototype._getHostByType = function(hostType) { return this.hosts[hostType][this._getHostIndexByType(hostType)]; }; AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() { return this._timeoutMultiplier; }; AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) { return this._hostIndexes[hostType]; }; AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) { var clone = __webpack_require__(119); var newHostIndexes = clone(this._hostIndexes); newHostIndexes[hostType] = hostIndex; this._partialAppIdDataUpdate({hostIndexes: newHostIndexes}); return hostIndex; }; AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) { return this._setHostIndexByType( (this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType ); }; AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() { var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4); return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier}); }; AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) { return { connect: this._timeouts.connect * this._timeoutMultiplier, complete: this._timeouts[hostType] * this._timeoutMultiplier }; }; function prepareHost(protocol) { return function prepare(host) { return protocol + '//' + host.toLowerCase(); }; } // Prototype.js < 1.7, a widely used library, defines a weird // Array.prototype.toJSON function that will fail to stringify our content // appropriately // refs: // - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q // - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c // - http://stackoverflow.com/a/3148441/147079 function safeJSONStringify(obj) { /* eslint no-extend-native:0 */ if (Array.prototype.toJSON === undefined) { return JSON.stringify(obj); } var toJSON = Array.prototype.toJSON; delete Array.prototype.toJSON; var out = JSON.stringify(obj); Array.prototype.toJSON = toJSON; return out; } function shuffle(array) { var currentIndex = array.length; var temporaryValue; var randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function removeCredentials(headers) { var newHeaders = {}; for (var headerName in headers) { if (Object.prototype.hasOwnProperty.call(headers, headerName)) { var value; if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') { value = '**hidden for security purposes**'; } else { value = headers[headerName]; } newHeaders[headerName] = value; } } return newHeaders; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109))) /***/ }), /* 405 */ /***/ (function(module, exports, __webpack_require__) { var buildSearchMethod = __webpack_require__(348); var deprecate = __webpack_require__(410); var deprecatedMessage = __webpack_require__(411); module.exports = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the full text query * @param {object} [args] (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param {function} [callback] the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the similar query * @param {object} [args] (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery'); /* * Browse index content. The response content will have a `cursor` property that you can use * to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browse('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }, callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browse = function(query, queryParameters, callback) { var merge = __webpack_require__(413); var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse', body: {params: params}, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse', body: {cursor: cursor}, hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone = __webpack_require__(119); var omit = __webpack_require__(414); var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])'; if (params.facetName === undefined || params.facetQuery === undefined) { throw new Error(usage); } var facetName = params.facetName; var filteredParams = omit(clone(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback, additionalUA) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback, additionalUA: additionalUA }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occured */ IndexCore.prototype.getObject = function(objectID, attrs, callback) { var indexObj = this; if (arguments.length === 1 || typeof attrs === 'function') { callback = attrs; attrs = undefined; } var params = ''; if (attrs !== undefined) { params = '?attributes='; for (var i = 0; i < attrs.length; ++i) { if (i !== 0) { params += ','; } params += attrs[i]; } } return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, hostType: 'read', callback: callback }); }; /* * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve */ IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) { var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; if (arguments.length === 1 || typeof attributesToRetrieve === 'function') { callback = attributesToRetrieve; attributesToRetrieve = undefined; } var body = { requests: map(objectIDs, function prepareRequest(objectID) { var request = { indexName: indexObj.indexName, objectID: objectID }; if (attributesToRetrieve) { request.attributesToRetrieve = attributesToRetrieve.join(','); } return request; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/*/objects', hostType: 'read', body: body, callback: callback }); }; IndexCore.prototype.as = null; IndexCore.prototype.indexName = null; IndexCore.prototype.typeAheadArgs = null; IndexCore.prototype.typeAheadValueOption = null; /***/ }), /* 406 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(421); var Promise = global.Promise || __webpack_require__(420).Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = __webpack_require__(349); var errors = __webpack_require__(215); var inlineHeaders = __webpack_require__(408); var jsonpRequest = __webpack_require__(409); var places = __webpack_require__(415); uaSuffix = uaSuffix || ''; if (false) { require('debug').enable('algoliasearch*'); } function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = __webpack_require__(119); var getDocumentProtocol = __webpack_require__(407); opts = cloneDeep(opts || {}); if (opts.protocol === undefined) { opts.protocol = getDocumentProtocol(); } opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = __webpack_require__(417); algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version; algoliasearch.initPlaces = places(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia global.__algolia = { debug: __webpack_require__(216), algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in global, hasXDomainRequest: 'XDomainRequest' in global }; if (support.hasXMLHttpRequest) { support.cors = 'withCredentials' in new XMLHttpRequest(); } function AlgoliaSearchBrowser() { // call AlgoliaSearch constructor AlgoliaSearch.apply(this, arguments); } inherits(AlgoliaSearchBrowser, AlgoliaSearch); AlgoliaSearchBrowser.prototype._request = function request(url, opts) { return new Promise(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors.Network('CORS not supported')); return; } url = inlineHeaders(url, opts.headers); var body = opts.body; var req = support.cors ? new XMLHttpRequest() : new XDomainRequest(); var reqTimeout; var timedOut; var connected = false; reqTimeout = setTimeout(onTimeout, opts.timeouts.connect); // we set an empty onprogress listener // so that XDomainRequest on IE9 is not aborted // refs: // - https://github.com/algolia/algoliasearch-client-js/issues/76 // - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment req.onprogress = onProgress; if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange; req.onload = onLoad; req.onerror = onError; // do not rely on default XHR async flag, as some analytics code like hotjar // breaks it and set it to false by default if (req instanceof XMLHttpRequest) { req.open(opts.method, url, true); } else { req.open(opts.method, url); } // headers are meant to be sent after open if (support.cors) { if (body) { if (opts.method === 'POST') { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests req.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); } else { req.setRequestHeader('content-type', 'application/json'); } } req.setRequestHeader('accept', 'application/json'); } req.send(body); // event object not received in IE8, at least // but we do not use it, still important to note function onLoad(/* event */) { // When browser does not supports req.timeout, we can // have both a load and timeout event, since handled by a dumb setTimeout if (timedOut) { return; } clearTimeout(reqTimeout); var out; try { out = { body: JSON.parse(req.responseText), responseText: req.responseText, statusCode: req.status, // XDomainRequest does not have any response headers headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {} }; } catch (e) { out = new errors.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors.UnparsableJSON) { reject(out); } else { resolve(out); } } function onError(event) { if (timedOut) { return; } clearTimeout(reqTimeout); // error event is trigerred both with XDR/XHR on: // - DNS error // - unallowed cross domain request reject( new errors.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors.RequestTimeout()); } function onConnect() { connected = true; clearTimeout(reqTimeout); reqTimeout = setTimeout(onTimeout, opts.timeouts.complete); } function onProgress() { if (!connected) onConnect(); } function onReadyStateChange() { if (!connected && req.readyState > 1) onConnect(); } }); }; AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) { url = inlineHeaders(url, opts.headers); return new Promise(function wrapJsonpRequest(resolve, reject) { jsonpRequest(url, opts, function jsonpRequestDone(err, content) { if (err) { reject(err); return; } resolve(content); }); }); }; AlgoliaSearchBrowser.prototype._promise = { reject: function rejectPromise(val) { return Promise.reject(val); }, resolve: function resolvePromise(val) { return Promise.resolve(val); }, delay: function delayPromise(ms) { return new Promise(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); } }; return algoliasearch; }; /***/ }), /* 407 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = getDocumentProtocol; function getDocumentProtocol() { var protocol = window.document.location.protocol; // when in `file:` mode (local html file), default to `http:` if (protocol !== 'http:' && protocol !== 'https:') { protocol = 'http:'; } return protocol; } /***/ }), /* 408 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = inlineHeaders; var encode = __webpack_require__(428); function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode(headers); } /***/ }), /* 409 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = jsonpRequest; var errors = __webpack_require__(215); var JSONPCounter = 0; function jsonpRequest(url, opts, cb) { if (opts.method !== 'GET') { cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.')); return; } opts.debug('JSONP: start'); var cbCalled = false; var timedOut = false; JSONPCounter += 1; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); var cbName = 'algoliaJSONP_' + JSONPCounter; var done = false; window[cbName] = function(data) { removeGlobals(); if (timedOut) { opts.debug('JSONP: Late answer, ignoring'); return; } cbCalled = true; clean(); cb(null, { body: data/* , // We do not send the statusCode, there's no statusCode in JSONP, it will be // computed using data.status && data.message like with XDR statusCode*/ }); }; // add callback by hand url += '&callback=' + cbName; // add body params manually if (opts.jsonBody && opts.jsonBody.params) { url += '&' + opts.jsonBody.params; } var ontimeout = setTimeout(timeout, opts.timeouts.complete); // script onreadystatechange needed only for // <= IE8 // https://github.com/angular/angular.js/issues/4523 script.onreadystatechange = readystatechange; script.onload = success; script.onerror = error; script.async = true; script.defer = true; script.src = url; head.appendChild(script); function success() { opts.debug('JSONP: success'); if (done || timedOut) { return; } done = true; // script loaded but did not call the fn => script loading error if (!cbCalled) { opts.debug('JSONP: Fail. Script loaded but did not call the callback'); clean(); cb(new errors.JSONPScriptFail()); } } function readystatechange() { if (this.readyState === 'loaded' || this.readyState === 'complete') { success(); } } function clean() { clearTimeout(ontimeout); script.onload = null; script.onreadystatechange = null; script.onerror = null; head.removeChild(script); } function removeGlobals() { try { delete window[cbName]; delete window[cbName + '_loaded']; } catch (e) { window[cbName] = window[cbName + '_loaded'] = undefined; } } function timeout() { opts.debug('JSONP: Script timeout'); timedOut = true; clean(); cb(new errors.RequestTimeout()); } function error() { opts.debug('JSONP: Script error'); if (done || timedOut) { return; } clean(); cb(new errors.JSONPScriptError()); } } /***/ }), /* 410 */ /***/ (function(module, exports) { module.exports = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.log(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; /***/ }), /* 411 */ /***/ (function(module, exports) { module.exports = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace('.', '') .replace('()', ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink; }; /***/ }), /* 412 */ /***/ (function(module, exports) { // Parse cloud does not supports setTimeout // We do not store a setTimeout reference in the client everytime // We only fallback to a fake setTimeout when not available // setTimeout cannot be override globally sadly module.exports = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; /***/ }), /* 413 */ /***/ (function(module, exports, __webpack_require__) { var foreach = __webpack_require__(110); module.exports = function merge(destination/* , sources */) { var sources = Array.prototype.slice.call(arguments); foreach(sources, function(source) { for (var keyName in source) { if (source.hasOwnProperty(keyName)) { if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') { destination[keyName] = merge({}, destination[keyName], source[keyName]); } else if (source[keyName] !== undefined) { destination[keyName] = source[keyName]; } } } }); return destination; }; /***/ }), /* 414 */ /***/ (function(module, exports, __webpack_require__) { module.exports = function omit(obj, test) { var keys = __webpack_require__(426); var foreach = __webpack_require__(110); var filtered = {}; foreach(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; /***/ }), /* 415 */ /***/ (function(module, exports, __webpack_require__) { module.exports = createPlacesClient; var buildSearchMethod = __webpack_require__(348); function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = __webpack_require__(119); opts = opts && cloneDeep(opts) || {}; opts.hosts = opts.hosts || [ 'places-dsn.algolia.net', 'places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com' ]; // allow initPlaces() no arguments => community rate limited if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) { appID = ''; apiKey = ''; opts._allowEmptyCredentials = true; } var client = algoliasearch(appID, apiKey, opts); var index = client.initIndex('places'); index.search = buildSearchMethod('query', '/1/places/query'); return index; }; } /***/ }), /* 416 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var debug = __webpack_require__(216)('algoliasearch:src/hostIndexState.js'); var localStorageNamespace = 'algoliasearch-client-js'; var store; var moduleStore = { state: {}, set: function(key, data) { this.state[key] = data; return this.state[key]; }, get: function(key) { return this.state[key] || null; } }; var localStorageStore = { set: function(key, data) { moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure try { var namespace = JSON.parse(global.localStorage[localStorageNamespace]); namespace[key] = data; global.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(global.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; module.exports = { get: getOrSet, set: getOrSet, supportsLocalStorage: supportsLocalStorage }; function getOrSet(key, data) { if (arguments.length === 1) { return store.get(key); } return store.set(key, data); } function supportsLocalStorage() { try { if ('localStorage' in global && global.localStorage !== null) { if (!global.localStorage[localStorageNamespace]) { // actual creation of the namespace global.localStorage.setItem(localStorageNamespace, JSON.stringify({})); } return true; } return false; } catch (_) { return false; } } // In case of any error on localStorage, we clean our own namespace, this should handle // quota errors when a lot of keys + data are used function cleanup() { try { global.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 417 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = '3.21.1'; /***/ }), /* 418 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }), /* 419 */ /***/ (function(module, exports, __webpack_require__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug.debug = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(425); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }), /* 420 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 4.0.5 */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ES6Promise = factory()); }(this, (function () { 'use strict'; function objectOrFunction(x) { return typeof x === 'function' || typeof x === 'object' && x !== null; } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = require; var vertx = __webpack_require__(430); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); _resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then) { asap(function (promise) { var sealed = false; var error = tryThen(then, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { _resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; _reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; _reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { _reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return _resolve(promise, value); }, function (reason) { return _reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$) { if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { handleOwnThenable(promise, maybeThenable); } else { if (then$$ === GET_THEN_ERROR) { _reject(promise, GET_THEN_ERROR.error); } else if (then$$ === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$)) { handleForeignThenable(promise, maybeThenable, then$$); } else { fulfill(promise, maybeThenable); } } } function _resolve(promise, value) { if (promise === value) { _reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function _reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { _reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { _resolve(promise, value); } else if (failed) { _reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { _reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { _resolve(promise, value); }, function rejectPromise(reason) { _reject(promise, reason); }); } catch (e) { _reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { _reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); }; Enumerator.prototype._enumerate = function () { var length = this.length; var _input = this._input; for (var i = 0; this._state === PENDING && i < length; i++) { this._eachEntry(_input[i], i); } }; Enumerator.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$ = c.resolve; if (resolve$$ === resolve) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$) { return resolve$$(entry); }), i); } } else { this._willSettleAt(resolve$$(entry), i); } }; Enumerator.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { _reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); _reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } Promise.all = all; Promise.race = race; Promise.resolve = resolve; Promise.reject = reject; Promise._setScheduler = setScheduler; Promise._setAsap = setAsap; Promise._asap = asap; Promise.prototype = { constructor: Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: then, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function _catch(onRejection) { return this.then(null, onRejection); } }; function polyfill() { var local = undefined; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise; } // Strange compat.. Promise.polyfill = polyfill; Promise.Promise = Promise; return Promise; }))); //# sourceMappingURL=es6-promise.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109), __webpack_require__(54))) /***/ }), /* 421 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 422 */ /***/ (function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeMax = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } module.exports = baseRange; /***/ }), /* 423 */ /***/ (function(module, exports, __webpack_require__) { var baseRange = __webpack_require__(422), isIterateeCall = __webpack_require__(217), toFinite = __webpack_require__(219); /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } module.exports = createRange; /***/ }), /* 424 */ /***/ (function(module, exports, __webpack_require__) { var createRange = __webpack_require__(423); /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); module.exports = range; /***/ }), /* 425 */ /***/ (function(module, exports) { /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } /***/ }), /* 426 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = __webpack_require__(427); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /* 427 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /* 428 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; /***/ }), /* 429 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_429__; /***/ }), /* 430 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 431 */, /* 432 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Panel = exports.Toggle = exports.Stats = exports.SortBy = exports.SearchBox = exports.ScrollTo = exports.ClearAll = exports.RefinementList = exports.StarRating = exports.RangeSlider = exports.RangeInput = exports.PoweredBy = exports.Pagination = exports.MultiRange = exports.Menu = exports.InfiniteHits = exports.HitsPerPage = exports.Hits = exports.Snippet = exports.Highlight = exports.HierarchicalMenu = exports.CurrentRefinements = exports.Configure = exports.Index = exports.InstantSearch = undefined; var _Configure = __webpack_require__(354); Object.defineProperty(exports, 'Configure', { enumerable: true, get: function get() { return _interopRequireDefault(_Configure).default; } }); var _CurrentRefinements = __webpack_require__(355); Object.defineProperty(exports, 'CurrentRefinements', { enumerable: true, get: function get() { return _interopRequireDefault(_CurrentRefinements).default; } }); var _HierarchicalMenu = __webpack_require__(356); Object.defineProperty(exports, 'HierarchicalMenu', { enumerable: true, get: function get() { return _interopRequireDefault(_HierarchicalMenu).default; } }); var _Highlight = __webpack_require__(235); Object.defineProperty(exports, 'Highlight', { enumerable: true, get: function get() { return _interopRequireDefault(_Highlight).default; } }); var _Snippet = __webpack_require__(370); Object.defineProperty(exports, 'Snippet', { enumerable: true, get: function get() { return _interopRequireDefault(_Snippet).default; } }); var _Hits = __webpack_require__(357); Object.defineProperty(exports, 'Hits', { enumerable: true, get: function get() { return _interopRequireDefault(_Hits).default; } }); var _HitsPerPage = __webpack_require__(358); Object.defineProperty(exports, 'HitsPerPage', { enumerable: true, get: function get() { return _interopRequireDefault(_HitsPerPage).default; } }); var _InfiniteHits = __webpack_require__(359); Object.defineProperty(exports, 'InfiniteHits', { enumerable: true, get: function get() { return _interopRequireDefault(_InfiniteHits).default; } }); var _Menu = __webpack_require__(360); Object.defineProperty(exports, 'Menu', { enumerable: true, get: function get() { return _interopRequireDefault(_Menu).default; } }); var _MultiRange = __webpack_require__(361); Object.defineProperty(exports, 'MultiRange', { enumerable: true, get: function get() { return _interopRequireDefault(_MultiRange).default; } }); var _Pagination = __webpack_require__(362); Object.defineProperty(exports, 'Pagination', { enumerable: true, get: function get() { return _interopRequireDefault(_Pagination).default; } }); var _PoweredBy = __webpack_require__(364); Object.defineProperty(exports, 'PoweredBy', { enumerable: true, get: function get() { return _interopRequireDefault(_PoweredBy).default; } }); var _RangeInput = __webpack_require__(365); Object.defineProperty(exports, 'RangeInput', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeInput).default; } }); var _RangeSlider = __webpack_require__(366); Object.defineProperty(exports, 'RangeSlider', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeSlider).default; } }); var _StarRating = __webpack_require__(372); Object.defineProperty(exports, 'StarRating', { enumerable: true, get: function get() { return _interopRequireDefault(_StarRating).default; } }); var _RefinementList = __webpack_require__(367); Object.defineProperty(exports, 'RefinementList', { enumerable: true, get: function get() { return _interopRequireDefault(_RefinementList).default; } }); var _ClearAll = __webpack_require__(353); Object.defineProperty(exports, 'ClearAll', { enumerable: true, get: function get() { return _interopRequireDefault(_ClearAll).default; } }); var _ScrollTo = __webpack_require__(368); Object.defineProperty(exports, 'ScrollTo', { enumerable: true, get: function get() { return _interopRequireDefault(_ScrollTo).default; } }); var _SearchBox = __webpack_require__(369); Object.defineProperty(exports, 'SearchBox', { enumerable: true, get: function get() { return _interopRequireDefault(_SearchBox).default; } }); var _SortBy = __webpack_require__(371); Object.defineProperty(exports, 'SortBy', { enumerable: true, get: function get() { return _interopRequireDefault(_SortBy).default; } }); var _Stats = __webpack_require__(373); Object.defineProperty(exports, 'Stats', { enumerable: true, get: function get() { return _interopRequireDefault(_Stats).default; } }); var _Toggle = __webpack_require__(374); Object.defineProperty(exports, 'Toggle', { enumerable: true, get: function get() { return _interopRequireDefault(_Toggle).default; } }); var _Panel = __webpack_require__(363); Object.defineProperty(exports, 'Panel', { enumerable: true, get: function get() { return _interopRequireDefault(_Panel).default; } }); var _createInstantSearch = __webpack_require__(352); var _createInstantSearch2 = _interopRequireDefault(_createInstantSearch); var _createIndex = __webpack_require__(351); var _createIndex2 = _interopRequireDefault(_createIndex); var _lite = __webpack_require__(375); var _lite2 = _interopRequireDefault(_lite); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InstantSearch = (0, _createInstantSearch2.default)(_lite2.default, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); exports.InstantSearch = InstantSearch; var Index = (0, _createIndex2.default)({ Root: 'div', props: { className: 'ais-MultiIndex__root' } }); exports.Index = Index; /***/ }) /******/ ]); }); //# sourceMappingURL=Dom.js.map
ajax/libs/primereact/7.0.0-rc.1/chip/chip.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames, ObjectUtils } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Chip = /*#__PURE__*/function (_Component) { _inherits(Chip, _Component); var _super = _createSuper(Chip); function Chip(props) { var _this; _classCallCheck(this, Chip); _this = _super.call(this, props); _this.state = { visible: true }; _this.close = _this.close.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(Chip, [{ key: "onKeyDown", value: function onKeyDown(event) { if (event.keyCode === 13) { // enter this.close(event); } } }, { key: "close", value: function close(event) { var _this2 = this; event.persist(); this.setState({ visible: false }, function () { if (_this2.props.onRemove) { _this2.props.onRemove(event); } }); } }, { key: "renderContent", value: function renderContent() { var _this3 = this; var content = []; if (this.props.image) { var onError = function onError(e) { if (_this3.props.onImageError) { _this3.props.onImageError(e); } }; content.push( /*#__PURE__*/React.createElement("img", { key: "image", src: this.props.image, alt: this.props.imageAlt, onError: onError })); } else if (this.props.icon) { var iconClassName = classNames('p-chip-icon', this.props.icon); content.push( /*#__PURE__*/React.createElement("span", { key: "icon", className: iconClassName })); } if (this.props.label) { content.push( /*#__PURE__*/React.createElement("span", { key: "label", className: "p-chip-text" }, this.props.label)); } if (this.props.removable) { var removableIconClassName = classNames('p-chip-remove-icon', this.props.removeIcon); content.push( /*#__PURE__*/React.createElement("span", { key: "removeIcon", tabIndex: 0, className: removableIconClassName, onClick: this.close, onKeyDown: this.onKeyDown })); } return content; } }, { key: "renderElement", value: function renderElement() { var containerClassName = classNames('p-chip p-component', { 'p-chip-image': this.props.image != null }, this.props.className); var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : this.renderContent(); return /*#__PURE__*/React.createElement("div", { className: containerClassName, style: this.props.style }, content); } }, { key: "render", value: function render() { return this.state.visible && this.renderElement(); } }]); return Chip; }(Component); _defineProperty(Chip, "defaultProps", { label: null, icon: null, image: null, removable: false, removeIcon: 'pi pi-times-circle', className: null, style: null, template: null, imageAlt: 'chip', onImageError: null, onRemove: null }); export { Chip };
ajax/libs/material-ui/4.9.4/es/AppBar/AppBar.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import capitalize from '../utils/capitalize'; import Paper from '../Paper'; export const styles = theme => { const backgroundColorDefault = theme.palette.type === 'light' ? theme.palette.grey[100] : theme.palette.grey[900]; return { /* Styles applied to the root element. */ root: { display: 'flex', flexDirection: 'column', width: '100%', boxSizing: 'border-box', // Prevent padding issue with the Modal and fixed positioned AppBar. zIndex: theme.zIndex.appBar, flexShrink: 0 }, /* Styles applied to the root element if `position="fixed"`. */ positionFixed: { position: 'fixed', top: 0, left: 'auto', right: 0, '@media print': { // Prevent the app bar to be visible on each printed page. position: 'absolute' } }, /* Styles applied to the root element if `position="absolute"`. */ positionAbsolute: { position: 'absolute', top: 0, left: 'auto', right: 0 }, /* Styles applied to the root element if `position="sticky"`. */ positionSticky: { // ⚠️ sticky is not supported by IE 11. position: 'sticky', top: 0, left: 'auto', right: 0 }, /* Styles applied to the root element if `position="static"`. */ positionStatic: { position: 'static', transform: 'translateZ(0)' // Make sure we can see the elevation. }, /* Styles applied to the root element if `position="relative"`. */ positionRelative: { position: 'relative' }, /* Styles applied to the root element if `color="default"`. */ colorDefault: { backgroundColor: backgroundColorDefault, color: theme.palette.getContrastText(backgroundColorDefault) }, /* Styles applied to the root element if `color="primary"`. */ colorPrimary: { backgroundColor: theme.palette.primary.main, color: theme.palette.primary.contrastText }, /* Styles applied to the root element if `color="secondary"`. */ colorSecondary: { backgroundColor: theme.palette.secondary.main, color: theme.palette.secondary.contrastText }, /* Styles applied to the root element if `color="inherit"`. */ colorInherit: { color: 'inherit' }, /* Styles applied to the root element if `color="transparent"`. */ colorTransparent: { backgroundColor: 'transparent', color: 'inherit' } }; }; const AppBar = React.forwardRef(function AppBar(props, ref) { const { classes, className, color = 'primary', position = 'fixed' } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "color", "position"]); return React.createElement(Paper, _extends({ square: true, component: "header", elevation: 4, className: clsx(classes.root, classes[`position${capitalize(position)}`], classes[`color${capitalize(color)}`], className, position === 'fixed' && 'mui-fixed'), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? AppBar.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary', 'transparent']), /** * The positioning type. The behavior of the different options is described * [in the MDN web docs](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning). * Note: `sticky` is not universally supported and will fall back to `static` when unavailable. */ position: PropTypes.oneOf(['absolute', 'fixed', 'relative', 'static', 'sticky']) } : void 0; export default withStyles(styles, { name: 'MuiAppBar' })(AppBar);
ajax/libs/boardgame-io/0.49.11/esm/react.js
cdnjs/cdnjs
import 'nanoid/non-secure'; import './Debug-fd09b8bc.js'; import 'redux'; import './turn-order-0b7dce3d.js'; import 'immer'; import './plugin-random-087f861e.js'; import 'lodash.isplainobject'; import './reducer-07c7b307.js'; import 'rfc6902'; import './initialize-9ac1bbf5.js'; import './transport-ce07b771.js'; import { C as Client$1 } from './client-fa36c03a.js'; import 'flatted'; import 'setimmediate'; import { M as MCTSBot } from './ai-3099ce9a.js'; import { L as LobbyClient } from './client-5f57c3f2.js'; import React from 'react'; import PropTypes from 'prop-types'; import Cookies from 'react-cookies'; import './util-b1699aa1.js'; import { S as SocketIO, L as Local } from './socketio-e4fb268a.js'; import './master-be1abdd0.js'; import './filter-player-view-c30cdfbf.js'; import 'socket.io-client'; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Client * * boardgame.io React client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} debug - Enables the Debug UI. * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET, * UNDO and REDO. */ function Client(opts) { var _a; const { game, numPlayers, board, multiplayer, enhancer } = opts; let { loading, debug } = opts; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting..."); loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _a = class WrappedBoard extends React.Component { constructor(props) { super(props); if (debug === undefined) { debug = props.debug; } this.client = Client$1({ game, debug, numPlayers, multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, enhancer, }); } componentDidMount() { this.unsubscribe = this.client.subscribe(() => this.forceUpdate()); this.client.start(); } componentWillUnmount() { this.client.stop(); this.unsubscribe(); } componentDidUpdate(prevProps) { if (this.props.matchID != prevProps.matchID) { this.client.updateMatchID(this.props.matchID); } if (this.props.playerID != prevProps.playerID) { this.client.updatePlayerID(this.props.playerID); } if (this.props.credentials != prevProps.credentials) { this.client.updateCredentials(this.props.credentials); } } render() { const state = this.client.getState(); if (state === null) { return React.createElement(loading); } let _board = null; if (board) { _board = React.createElement(board, { ...state, ...this.props, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, matchID: this.client.matchID, playerID: this.client.playerID, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, log: this.client.log, matchData: this.client.matchData, sendChatMessage: this.client.sendChatMessage, chatMessages: this.client.chatMessages, }); } return React.createElement("div", { className: "bgio-client" }, _board); } }, _a.propTypes = { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string, // Enable / disable the Debug UI. debug: PropTypes.any, }, _a.defaultProps = { matchID: 'default', playerID: null, credentials: null, debug: true, }, _a; } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class _LobbyConnectionImpl { constructor({ server, gameComponents, playerName, playerCredentials, }) { this.client = new LobbyClient({ server }); this.gameComponents = gameComponents; this.playerName = playerName || 'Visitor'; this.playerCredentials = playerCredentials; this.matches = []; } async refresh() { try { this.matches = []; const games = await this.client.listGames(); for (const game of games) { if (!this._getGameComponents(game)) continue; const { matches } = await this.client.listMatches(game); this.matches.push(...matches); } } catch (error) { throw new Error('failed to retrieve list of matches (' + error + ')'); } } _getMatchInstance(matchID) { for (const inst of this.matches) { if (inst['matchID'] === matchID) return inst; } } _getGameComponents(gameName) { for (const comp of this.gameComponents) { if (comp.game.name === gameName) return comp; } } _findPlayer(playerName) { for (const inst of this.matches) { if (inst.players.some((player) => player.name === playerName)) return inst; } } async join(gameName, matchID, playerID) { try { let inst = this._findPlayer(this.playerName); if (inst) { throw new Error('player has already joined ' + inst.matchID); } inst = this._getMatchInstance(matchID); if (!inst) { throw new Error('game instance ' + matchID + ' not found'); } const json = await this.client.joinMatch(gameName, matchID, { playerID, playerName: this.playerName, }); inst.players[Number.parseInt(playerID)].name = this.playerName; this.playerCredentials = json.playerCredentials; } catch (error) { throw new Error('failed to join match ' + matchID + ' (' + error + ')'); } } async leave(gameName, matchID) { try { const inst = this._getMatchInstance(matchID); if (!inst) throw new Error('match instance not found'); for (const player of inst.players) { if (player.name === this.playerName) { await this.client.leaveMatch(gameName, matchID, { playerID: player.id.toString(), credentials: this.playerCredentials, }); delete player.name; delete this.playerCredentials; return; } } throw new Error('player not found in match'); } catch (error) { throw new Error('failed to leave match ' + matchID + ' (' + error + ')'); } } async disconnect() { const inst = this._findPlayer(this.playerName); if (inst) { await this.leave(inst.gameName, inst.matchID); } this.matches = []; this.playerName = 'Visitor'; } async create(gameName, numPlayers) { try { const comp = this._getGameComponents(gameName); if (!comp) throw new Error('game not found'); if (numPlayers < comp.game.minPlayers || numPlayers > comp.game.maxPlayers) throw new Error('invalid number of players ' + numPlayers); await this.client.createMatch(gameName, { numPlayers }); } catch (error) { throw new Error('failed to create match for ' + gameName + ' (' + error + ')'); } } } /** * LobbyConnection * * Lobby model. * * @param {string} server - '<host>:<port>' of the server. * @param {Array} gameComponents - A map of Board and Game objects for the supported games. * @param {string} playerName - The name of the player. * @param {string} playerCredentials - The credentials currently used by the player, if any. * * Returns: * A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances. */ function LobbyConnection(opts) { return new _LobbyConnectionImpl(opts); } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyLoginForm extends React.Component { constructor() { super(...arguments); this.state = { playerName: this.props.playerName, nameErrorMsg: '', }; this.onClickEnter = () => { if (this.state.playerName === '') return; this.props.onEnter(this.state.playerName); }; this.onKeyPress = (event) => { if (event.key === 'Enter') { this.onClickEnter(); } }; this.onChangePlayerName = (event) => { const name = event.target.value.trim(); this.setState({ playerName: name, nameErrorMsg: name.length > 0 ? '' : 'empty player name', }); }; } render() { return (React.createElement("div", null, React.createElement("p", { className: "phase-title" }, "Choose a player name:"), React.createElement("input", { type: "text", value: this.state.playerName, onChange: this.onChangePlayerName, onKeyPress: this.onKeyPress }), React.createElement("span", { className: "buttons" }, React.createElement("button", { className: "buttons", onClick: this.onClickEnter }, "Enter")), React.createElement("br", null), React.createElement("span", { className: "error-msg" }, this.state.nameErrorMsg, React.createElement("br", null)))); } } LobbyLoginForm.defaultProps = { playerName: '', }; /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyMatchInstance extends React.Component { constructor() { super(...arguments); this._createSeat = (player) => { return player.name || '[free]'; }; this._createButtonJoin = (inst, seatId) => (React.createElement("button", { key: 'button-join-' + inst.matchID, onClick: () => this.props.onClickJoin(inst.gameName, inst.matchID, '' + seatId) }, "Join")); this._createButtonLeave = (inst) => (React.createElement("button", { key: 'button-leave-' + inst.matchID, onClick: () => this.props.onClickLeave(inst.gameName, inst.matchID) }, "Leave")); this._createButtonPlay = (inst, seatId) => (React.createElement("button", { key: 'button-play-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, playerID: '' + seatId, numPlayers: inst.players.length, }) }, "Play")); this._createButtonSpectate = (inst) => (React.createElement("button", { key: 'button-spectate-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, numPlayers: inst.players.length, }) }, "Spectate")); this._createInstanceButtons = (inst) => { const playerSeat = inst.players.find((player) => player.name === this.props.playerName); const freeSeat = inst.players.find((player) => !player.name); if (playerSeat && freeSeat) { // already seated: waiting for match to start return this._createButtonLeave(inst); } if (freeSeat) { // at least 1 seat is available return this._createButtonJoin(inst, freeSeat.id); } // match is full if (playerSeat) { return (React.createElement("div", null, [ this._createButtonPlay(inst, playerSeat.id), this._createButtonLeave(inst), ])); } // allow spectating return this._createButtonSpectate(inst); }; } render() { const match = this.props.match; let status = 'OPEN'; if (!match.players.some((player) => !player.name)) { status = 'RUNNING'; } return (React.createElement("tr", { key: 'line-' + match.matchID }, React.createElement("td", { key: 'cell-name-' + match.matchID }, match.gameName), React.createElement("td", { key: 'cell-status-' + match.matchID }, status), React.createElement("td", { key: 'cell-seats-' + match.matchID }, match.players.map((player) => this._createSeat(player)).join(', ')), React.createElement("td", { key: 'cell-buttons-' + match.matchID }, this._createInstanceButtons(match)))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyCreateMatchForm extends React.Component { constructor(props) { super(props); this.state = { selectedGame: 0, numPlayers: 2, }; this._createGameNameOption = (game, idx) => { return (React.createElement("option", { key: 'name-option-' + idx, value: idx }, game.game.name)); }; this._createNumPlayersOption = (idx) => { return (React.createElement("option", { key: 'num-option-' + idx, value: idx }, idx)); }; this._createNumPlayersRange = (game) => { return Array.from({ length: game.maxPlayers + 1 }) .map((_, i) => i) .slice(game.minPlayers); }; this.onChangeNumPlayers = (event) => { this.setState({ numPlayers: Number.parseInt(event.target.value), }); }; this.onChangeSelectedGame = (event) => { const idx = Number.parseInt(event.target.value); this.setState({ selectedGame: idx, numPlayers: this.props.games[idx].game.minPlayers, }); }; this.onClickCreate = () => { this.props.createMatch(this.props.games[this.state.selectedGame].game.name, this.state.numPlayers); }; /* fix min and max number of players */ for (const game of props.games) { const matchDetails = game.game; if (!matchDetails.minPlayers) { matchDetails.minPlayers = 1; } if (!matchDetails.maxPlayers) { matchDetails.maxPlayers = 4; } console.assert(matchDetails.maxPlayers >= matchDetails.minPlayers); } this.state = { selectedGame: 0, numPlayers: props.games[0].game.minPlayers, }; } render() { return (React.createElement("div", null, React.createElement("select", { value: this.state.selectedGame, onChange: (evt) => this.onChangeSelectedGame(evt) }, this.props.games.map((game, index) => this._createGameNameOption(game, index))), React.createElement("span", null, "Players:"), React.createElement("select", { value: this.state.numPlayers, onChange: this.onChangeNumPlayers }, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map((number) => this._createNumPlayersOption(number))), React.createElement("span", { className: "buttons" }, React.createElement("button", { onClick: this.onClickCreate }, "Create")))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ var LobbyPhases; (function (LobbyPhases) { LobbyPhases["ENTER"] = "enter"; LobbyPhases["PLAY"] = "play"; LobbyPhases["LIST"] = "list"; })(LobbyPhases || (LobbyPhases = {})); /** * Lobby * * React lobby component. * * @param {Array} gameComponents - An array of Board and Game objects for the supported games. * @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000'). * If not set, defaults to the server that served the page. * @param {string} gameServer - Address of the game server (for example 'localhost:8001'). * If not set, defaults to the server that served the page. * @param {function} clientFactory - Function that is used to create the game clients. * @param {number} refreshInterval - Interval between server updates (default: 2000ms). * @param {bool} debug - Enable debug information (default: false). * * Returns: * A React component that provides a UI to create, list, join, leave, play or * spectate matches (game instances). */ class Lobby extends React.Component { constructor(props) { super(props); this.state = { phase: LobbyPhases.ENTER, playerName: 'Visitor', runningMatch: null, errorMsg: '', credentialStore: {}, }; this._createConnection = (props) => { const name = this.state.playerName; this.connection = LobbyConnection({ server: props.lobbyServer, gameComponents: props.gameComponents, playerName: name, playerCredentials: this.state.credentialStore[name], }); }; this._updateCredentials = (playerName, credentials) => { this.setState((prevState) => { // clone store or componentDidUpdate will not be triggered const store = Object.assign({}, prevState.credentialStore); store[playerName] = credentials; return { credentialStore: store }; }); }; this._updateConnection = async () => { await this.connection.refresh(); this.forceUpdate(); }; this._enterLobby = (playerName) => { this._startRefreshInterval(); this.setState({ playerName, phase: LobbyPhases.LIST }); }; this._exitLobby = async () => { this._clearRefreshInterval(); await this.connection.disconnect(); this.setState({ phase: LobbyPhases.ENTER, errorMsg: '' }); }; this._createMatch = async (gameName, numPlayers) => { try { await this.connection.create(gameName, numPlayers); await this.connection.refresh(); // rerender this.setState({}); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._joinMatch = async (gameName, matchID, playerID) => { try { await this.connection.join(gameName, matchID, playerID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._leaveMatch = async (gameName, matchID) => { try { await this.connection.leave(gameName, matchID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._startMatch = (gameName, matchOpts) => { const gameCode = this.connection._getGameComponents(gameName); if (!gameCode) { this.setState({ errorMsg: 'game ' + gameName + ' not supported', }); return; } let multiplayer = undefined; if (matchOpts.numPlayers > 1) { multiplayer = this.props.gameServer ? SocketIO({ server: this.props.gameServer }) : SocketIO(); } if (matchOpts.numPlayers == 1) { const maxPlayers = gameCode.game.maxPlayers; const bots = {}; for (let i = 1; i < maxPlayers; i++) { bots[i + ''] = MCTSBot; } multiplayer = Local({ bots }); } const app = this.props.clientFactory({ game: gameCode.game, board: gameCode.board, debug: this.props.debug, multiplayer, }); const match = { app: app, matchID: matchOpts.matchID, playerID: matchOpts.numPlayers > 1 ? matchOpts.playerID : '0', credentials: this.connection.playerCredentials, }; this._clearRefreshInterval(); this.setState({ phase: LobbyPhases.PLAY, runningMatch: match }); }; this._exitMatch = () => { this._startRefreshInterval(); this.setState({ phase: LobbyPhases.LIST, runningMatch: null }); }; this._getPhaseVisibility = (phase) => { return this.state.phase !== phase ? 'hidden' : 'phase'; }; this.renderMatches = (matches, playerName) => { return matches.map((match) => { const { matchID, gameName, players } = match; return (React.createElement(LobbyMatchInstance, { key: 'instance-' + matchID, match: { matchID, gameName, players: Object.values(players) }, playerName: playerName, onClickJoin: this._joinMatch, onClickLeave: this._leaveMatch, onClickPlay: this._startMatch })); }); }; this._createConnection(this.props); } componentDidMount() { const cookie = Cookies.load('lobbyState') || {}; if (cookie.phase && cookie.phase === LobbyPhases.PLAY) { cookie.phase = LobbyPhases.LIST; } if (cookie.phase && cookie.phase !== LobbyPhases.ENTER) { this._startRefreshInterval(); } this.setState({ phase: cookie.phase || LobbyPhases.ENTER, playerName: cookie.playerName || 'Visitor', credentialStore: cookie.credentialStore || {}, }); } componentDidUpdate(prevProps, prevState) { const name = this.state.playerName; const creds = this.state.credentialStore[name]; if (prevState.phase !== this.state.phase || prevState.credentialStore[name] !== creds || prevState.playerName !== name) { this._createConnection(this.props); this._updateConnection(); const cookie = { phase: this.state.phase, playerName: name, credentialStore: this.state.credentialStore, }; Cookies.save('lobbyState', cookie, { path: '/' }); } if (prevProps.refreshInterval !== this.props.refreshInterval) { this._startRefreshInterval(); } } componentWillUnmount() { this._clearRefreshInterval(); } _startRefreshInterval() { this._clearRefreshInterval(); this._currentInterval = setInterval(this._updateConnection, this.props.refreshInterval); } _clearRefreshInterval() { clearInterval(this._currentInterval); } render() { const { gameComponents, renderer } = this.props; const { errorMsg, playerName, phase, runningMatch } = this.state; if (renderer) { return renderer({ errorMsg, gameComponents, matches: this.connection.matches, phase, playerName, runningMatch, handleEnterLobby: this._enterLobby, handleExitLobby: this._exitLobby, handleCreateMatch: this._createMatch, handleJoinMatch: this._joinMatch, handleLeaveMatch: this._leaveMatch, handleExitMatch: this._exitMatch, handleRefreshMatches: this._updateConnection, handleStartMatch: this._startMatch, }); } return (React.createElement("div", { id: "lobby-view", style: { padding: 50 } }, React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.ENTER) }, React.createElement(LobbyLoginForm, { key: playerName, playerName: playerName, onEnter: this._enterLobby })), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.LIST) }, React.createElement("p", null, "Welcome, ", playerName), React.createElement("div", { className: "phase-title", id: "match-creation" }, React.createElement("span", null, "Create a match:"), React.createElement(LobbyCreateMatchForm, { games: gameComponents, createMatch: this._createMatch })), React.createElement("p", { className: "phase-title" }, "Join a match:"), React.createElement("div", { id: "instances" }, React.createElement("table", null, React.createElement("tbody", null, this.renderMatches(this.connection.matches, playerName))), React.createElement("span", { className: "error-msg" }, errorMsg, React.createElement("br", null))), React.createElement("p", { className: "phase-title" }, "Matches that become empty are automatically deleted.")), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.PLAY) }, runningMatch && (React.createElement(runningMatch.app, { matchID: runningMatch.matchID, playerID: runningMatch.playerID, credentials: runningMatch.credentials })), React.createElement("div", { className: "buttons", id: "match-exit" }, React.createElement("button", { onClick: this._exitMatch }, "Exit match"))), React.createElement("div", { className: "buttons", id: "lobby-exit" }, React.createElement("button", { onClick: this._exitLobby }, "Exit lobby")))); } } Lobby.propTypes = { gameComponents: PropTypes.array.isRequired, lobbyServer: PropTypes.string, gameServer: PropTypes.string, debug: PropTypes.bool, clientFactory: PropTypes.func, refreshInterval: PropTypes.number, }; Lobby.defaultProps = { debug: false, clientFactory: Client, refreshInterval: 2000, }; export { Client, Lobby };
ajax/libs/primereact/7.0.0-rc.1/row/row.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Row = /*#__PURE__*/function (_Component) { _inherits(Row, _Component); var _super = _createSuper(Row); function Row() { _classCallCheck(this, Row); return _super.apply(this, arguments); } _createClass(Row, [{ key: "render", value: function render() { return /*#__PURE__*/React.createElement("tr", null, this.props.children); } }]); return Row; }(Component); _defineProperty(Row, "defaultProps", { style: null, className: null }); export { Row };
ajax/libs/material-ui/4.9.3/es/Breadcrumbs/BreadcrumbCollapsed.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import withStyles from '../styles/withStyles'; import { emphasize } from '../styles/colorManipulator'; import MoreHorizIcon from '../internal/svg-icons/MoreHoriz'; const styles = theme => ({ root: { display: 'flex' }, icon: { width: 24, height: 16, backgroundColor: theme.palette.grey[100], color: theme.palette.grey[700], borderRadius: 2, marginLeft: theme.spacing(0.5), marginRight: theme.spacing(0.5), cursor: 'pointer', '&:hover, &:focus': { backgroundColor: theme.palette.grey[200] }, '&:active': { boxShadow: theme.shadows[0], backgroundColor: emphasize(theme.palette.grey[200], 0.12) } } }); /** * @ignore - internal component. */ function BreadcrumbCollapsed(props) { const { classes } = props, other = _objectWithoutPropertiesLoose(props, ["classes"]); return React.createElement("li", _extends({ className: classes.root }, other), React.createElement(MoreHorizIcon, { className: classes.icon })); } process.env.NODE_ENV !== "production" ? BreadcrumbCollapsed.propTypes = { /** * @ignore */ classes: PropTypes.object.isRequired } : void 0; export default withStyles(styles, { name: 'PrivateBreadcrumbCollapsed' })(BreadcrumbCollapsed);
ajax/libs/primereact/6.6.0-rc.1/orderlist/orderlist.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Button } from 'primereact/button'; import { ObjectUtils, DomHandler, classNames, Ripple } from 'primereact/core'; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderListControls = /*#__PURE__*/function (_Component) { _inherits(OrderListControls, _Component); var _super = _createSuper$2(OrderListControls); function OrderListControls() { var _this; _classCallCheck(this, OrderListControls); _this = _super.call(this); _this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this)); _this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this)); _this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this)); _this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderListControls, [{ key: "moveUp", value: function moveUp(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex - 1]; value[selectedItemIndex - 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'up' }); } } } }, { key: "moveTop", value: function moveTop(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.unshift(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'top' }); } } } }, { key: "moveDown", value: function moveDown(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== value.length - 1) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex + 1]; value[selectedItemIndex + 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'down' }); } } } }, { key: "moveBottom", value: function moveBottom(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== value.length - 1) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.push(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'bottom' }); } } } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement("div", { className: "p-orderlist-controls" }, /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-up", onClick: this.moveUp }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-double-up", onClick: this.moveTop }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-down", onClick: this.moveDown }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-double-down", onClick: this.moveBottom })); } }]); return OrderListControls; }(Component); function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderListSubList = /*#__PURE__*/function (_Component) { _inherits(OrderListSubList, _Component); var _super = _createSuper$1(OrderListSubList); function OrderListSubList(props) { var _this; _classCallCheck(this, OrderListSubList); _this = _super.call(this, props); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onListMouseMove = _this.onListMouseMove.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderListSubList, [{ key: "isSelected", value: function isSelected(item) { return ObjectUtils.findIndexInList(item, this.props.selection, this.props.dataKey) !== -1; } }, { key: "onDragStart", value: function onDragStart(event, index) { this.dragging = true; this.draggedItemIndex = index; if (this.props.dragdropScope) { event.dataTransfer.setData('text', 'orderlist'); } } }, { key: "onDragOver", value: function onDragOver(event, index) { if (this.draggedItemIndex !== index && this.draggedItemIndex + 1 !== index) { this.dragOverItemIndex = index; DomHandler.addClass(event.target, 'p-orderlist-droppoint-highlight'); event.preventDefault(); } } }, { key: "onDragLeave", value: function onDragLeave(event) { this.dragOverItemIndex = null; DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight'); } }, { key: "onDrop", value: function onDrop(event) { var dropIndex = this.draggedItemIndex > this.dragOverItemIndex ? this.dragOverItemIndex : this.dragOverItemIndex === 0 ? 0 : this.dragOverItemIndex - 1; var value = _toConsumableArray(this.props.value); ObjectUtils.reorderArray(value, this.draggedItemIndex, dropIndex); this.dragOverItemIndex = null; DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight'); if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value }); } } }, { key: "onDragEnd", value: function onDragEnd(event) { this.dragging = false; } }, { key: "onListMouseMove", value: function onListMouseMove(event) { if (this.dragging) { var offsetY = this.listElement.getBoundingClientRect().top + DomHandler.getWindowScrollTop(); var bottomDiff = offsetY + this.listElement.clientHeight - event.pageY; var topDiff = event.pageY - offsetY; if (bottomDiff < 25 && bottomDiff > 0) this.listElement.scrollTop += 15;else if (topDiff < 25 && topDiff > 0) this.listElement.scrollTop -= 15; } } }, { key: "renderDropPoint", value: function renderDropPoint(index, key) { var _this2 = this; return /*#__PURE__*/React.createElement("li", { key: key, className: "p-orderlist-droppoint", onDragOver: function onDragOver(e) { return _this2.onDragOver(e, index + 1); }, onDragLeave: this.onDragLeave, onDrop: this.onDrop }); } }, { key: "render", value: function render() { var _this3 = this; var header = null; var items = null; if (this.props.header) { header = /*#__PURE__*/React.createElement("div", { className: "p-orderlist-header" }, this.props.header); } if (this.props.value) { items = this.props.value.map(function (item, i) { var content = _this3.props.itemTemplate ? _this3.props.itemTemplate(item) : item; var itemClassName = classNames('p-orderlist-item', { 'p-highlight': _this3.isSelected(item) }, _this3.props.className); var key = JSON.stringify(item); if (_this3.props.dragdrop) { var _items = [_this3.renderDropPoint(i, key + '_droppoint'), /*#__PURE__*/React.createElement("li", { key: key, className: itemClassName, onClick: function onClick(e) { return _this3.props.onItemClick({ originalEvent: e, value: item, index: i }); }, onKeyDown: function onKeyDown(e) { return _this3.props.onItemKeyDown({ originalEvent: e, value: item, index: i }); }, role: "option", "aria-selected": _this3.isSelected(item), draggable: "true", onDragStart: function onDragStart(e) { return _this3.onDragStart(e, i); }, onDragEnd: _this3.onDragEnd, tabIndex: _this3.props.tabIndex }, content, /*#__PURE__*/React.createElement(Ripple, null))]; if (i === _this3.props.value.length - 1) { _items.push(_this3.renderDropPoint(item, i, key + '_droppoint_end')); } return _items; } else { return /*#__PURE__*/React.createElement("li", { key: JSON.stringify(item), className: itemClassName, role: "option", "aria-selected": _this3.isSelected(item), onClick: function onClick(e) { return _this3.props.onItemClick({ originalEvent: e, value: item, index: i }); }, onKeyDown: function onKeyDown(e) { return _this3.props.onItemKeyDown({ originalEvent: e, value: item, index: i }); }, tabIndex: _this3.props.tabIndex }, content); } }); } return /*#__PURE__*/React.createElement("div", { className: "p-orderlist-list-container" }, header, /*#__PURE__*/React.createElement("ul", { ref: function ref(el) { return _this3.listElement = el; }, className: "p-orderlist-list", style: this.props.listStyle, onDragOver: this.onListMouseMove, role: "listbox", "aria-multiselectable": true }, items)); } }]); return OrderListSubList; }(Component); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderList = /*#__PURE__*/function (_Component) { _inherits(OrderList, _Component); var _super = _createSuper(OrderList); function OrderList(props) { var _this; _classCallCheck(this, OrderList); _this = _super.call(this, props); _this.state = { selection: [] }; _this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this)); _this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this)); _this.onReorder = _this.onReorder.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderList, [{ key: "onItemClick", value: function onItemClick(event) { var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey; var index = ObjectUtils.findIndexInList(event.value, this.state.selection, this.props.dataKey); var selected = index !== -1; var selection; if (selected) { if (metaKey) selection = this.state.selection.filter(function (val, i) { return i !== index; });else selection = [event.value]; } else { if (metaKey) selection = [].concat(_toConsumableArray(this.state.selection), [event.value]);else selection = [event.value]; } this.setState({ selection: selection }); } }, { key: "onItemKeyDown", value: function onItemKeyDown(event) { var listItem = event.originalEvent.currentTarget; switch (event.originalEvent.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.focus(); } event.originalEvent.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.focus(); } event.originalEvent.preventDefault(); break; //enter case 13: this.onItemClick(event); event.originalEvent.preventDefault(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return !DomHandler.hasClass(nextItem, 'p-orderlist-item') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return !DomHandler.hasClass(prevItem, 'p-orderlist-item') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "onReorder", value: function onReorder(event) { if (this.props.onChange) { this.props.onChange({ event: event.originalEvent, value: event.value }); } this.reorderDirection = event.direction; } }, { key: "componentDidUpdate", value: function componentDidUpdate() { if (this.reorderDirection) { this.updateListScroll(); this.reorderDirection = null; } } }, { key: "updateListScroll", value: function updateListScroll() { var listItems = DomHandler.find(this.subList.listElement, '.p-orderlist-item.p-highlight'); if (listItems && listItems.length) { switch (this.reorderDirection) { case 'up': DomHandler.scrollInView(this.subList.listElement, listItems[0]); break; case 'top': this.subList.listElement.scrollTop = 0; break; case 'down': DomHandler.scrollInView(this.subList.listElement, listItems[listItems.length - 1]); break; case 'bottom': this.subList.listElement.scrollTop = this.subList.listElement.scrollHeight; break; } } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-orderlist p-component', this.props.className); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.element = el; }, id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement(OrderListControls, { value: this.props.value, selection: this.state.selection, onReorder: this.onReorder, dataKey: this.props.dataKey }), /*#__PURE__*/React.createElement(OrderListSubList, { ref: function ref(el) { return _this2.subList = el; }, value: this.props.value, selection: this.state.selection, onItemClick: this.onItemClick, onItemKeyDown: this.onItemKeyDown, itemTemplate: this.props.itemTemplate, header: this.props.header, listStyle: this.props.listStyle, dataKey: this.props.dataKey, dragdrop: this.props.dragdrop, onDragStart: this.onDragStart, onDragEnter: this.onDragEnter, onDragEnd: this.onDragEnd, onDragLeave: this.onDragEnter, onDrop: this.onDrop, onChange: this.props.onChange, tabIndex: this.props.tabIndex })); } }]); return OrderList; }(Component); _defineProperty(OrderList, "defaultProps", { id: null, value: null, header: null, style: null, className: null, listStyle: null, dragdrop: false, tabIndex: 0, dataKey: null, onChange: null, itemTemplate: null }); export { OrderList };
ajax/libs/react-native-web/0.16.4/exports/createElement/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import createDOMProps from '../../modules/createDOMProps'; import React from 'react'; var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = createDOMProps(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return /*#__PURE__*/React.createElement.apply(React, [Component, domProps].concat(children)); }; export default createElement;
ajax/libs/react-native-web/0.14.12/exports/createElement/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import createDOMProps from '../../modules/createDOMProps'; import React from 'react'; var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = createDOMProps(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return React.createElement.apply(React, [Component, domProps].concat(children)); }; export default createElement;
ajax/libs/material-ui/4.9.3/esm/NativeSelect/NativeSelectInput.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import capitalize from '../utils/capitalize'; /** * @ignore - internal component. */ var NativeSelectInput = React.forwardRef(function NativeSelectInput(props, ref) { var classes = props.classes, className = props.className, disabled = props.disabled, IconComponent = props.IconComponent, inputRef = props.inputRef, _props$variant = props.variant, variant = _props$variant === void 0 ? 'standard' : _props$variant, other = _objectWithoutProperties(props, ["classes", "className", "disabled", "IconComponent", "inputRef", "variant"]); return React.createElement(React.Fragment, null, React.createElement("select", _extends({ className: clsx(classes.root, // TODO v5: merge root and select classes.select, classes[variant], className, disabled && classes.disabled), disabled: disabled, ref: inputRef || ref }, other)), props.multiple ? null : React.createElement(IconComponent, { className: clsx(classes.icon, classes["icon".concat(capitalize(variant))]) })); }); process.env.NODE_ENV !== "production" ? NativeSelectInput.propTypes = { /** * The option elements to populate the select with. * Can be some `<option>` elements. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * The CSS class name of the select element. */ className: PropTypes.string, /** * If `true`, the select will be disabled. */ disabled: PropTypes.bool, /** * The icon that displays the arrow. */ IconComponent: PropTypes.elementType.isRequired, /** * Use that prop to pass a ref to the native select element. * @deprecated */ inputRef: refType, /** * @ignore */ multiple: PropTypes.bool, /** * Name attribute of the `select` or hidden `input` element. */ name: PropTypes.string, /** * Callback function fired when a menu item is selected. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The input value. */ value: PropTypes.any, /** * The variant to use. */ variant: PropTypes.oneOf(['standard', 'outlined', 'filled']) } : void 0; export default NativeSelectInput;
ajax/libs/react-extras/3.0.0/element-class.js
cdnjs/cdnjs
import React from 'react'; import PropTypes from 'prop-types'; export default class ElementClass extends React.PureComponent { componentWillMount() { const { add, remove } = this.props; const { classList } = this.element; if (add) { classList.add(...add.trim().split(' ')); } if (remove) { classList.remove(...remove.trim().split(' ')); } } componentWillUnmount() { const { add, remove } = this.props; const { classList } = this.element; if (add) { classList.remove(...add.trim().split(' ')); } if (remove) { classList.add(...remove.trim().split(' ')); } } render() { return null; } } ElementClass.propTypes = { add: PropTypes.string, remove: PropTypes.string };
ajax/libs/material-ui/5.0.0-alpha.17/modern/styles/ThemeProvider.js
cdnjs/cdnjs
import React from 'react'; import PropTypes from 'prop-types'; import { ThemeProvider as MuiThemeProvider } from '@material-ui/styles'; import { exactProp } from '@material-ui/utils'; import { ThemeContext as StyledEngineThemeContext } from '@material-ui/styled-engine'; import useTheme from './useTheme'; function InnerThemeProvider(props) { const theme = useTheme(); return /*#__PURE__*/React.createElement(StyledEngineThemeContext.Provider, { value: typeof theme === 'object' ? theme : {} }, props.children); } process.env.NODE_ENV !== "production" ? InnerThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node } : void 0; /** * This component makes the `theme` available down the React tree. * It should preferably be used at **the root of your component tree**. */ function ThemeProvider(props) { const { children, theme: localTheme } = props; return /*#__PURE__*/React.createElement(MuiThemeProvider, { theme: localTheme }, /*#__PURE__*/React.createElement(InnerThemeProvider, null, children)); } process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node, /** * A theme object. You can provide a function to extend the outer theme. */ theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0; } export default ThemeProvider;
ajax/libs/primereact/7.0.1/captcha/captcha.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Captcha = /*#__PURE__*/function (_Component) { _inherits(Captcha, _Component); var _super = _createSuper(Captcha); function Captcha() { _classCallCheck(this, Captcha); return _super.apply(this, arguments); } _createClass(Captcha, [{ key: "init", value: function init() { var _this = this; this._instance = window.grecaptcha.render(this.targetEL, { 'sitekey': this.props.siteKey, 'theme': this.props.theme, 'type': this.props.type, 'size': this.props.size, 'tabindex': this.props.tabIndex, 'hl': this.props.language, 'callback': function callback(response) { _this.recaptchaCallback(response); }, 'expired-callback': function expiredCallback() { _this.recaptchaExpiredCallback(); } }); } }, { key: "reset", value: function reset() { if (this._instance === null) return; window.grecaptcha.reset(this._instance); } }, { key: "getResponse", value: function getResponse() { if (this._instance === null) return null; return window.grecaptcha.getResponse(this._instance); } }, { key: "recaptchaCallback", value: function recaptchaCallback(response) { if (this.props.onResponse) { this.props.onResponse({ response: response }); } } }, { key: "recaptchaExpiredCallback", value: function recaptchaExpiredCallback() { if (this.props.onExpire) { this.props.onExpire(); } } }, { key: "addRecaptchaScript", value: function addRecaptchaScript() { var _this2 = this; this.recaptchaScript = null; if (!window.grecaptcha) { var head = document.head || document.getElementsByTagName('head')[0]; this.recaptchaScript = document.createElement('script'); this.recaptchaScript.src = "https://www.google.com/recaptcha/api.js?render=explicit"; this.recaptchaScript.async = true; this.recaptchaScript.defer = true; this.recaptchaScript.onload = function () { if (!window.grecaptcha) { console.warn("Recaptcha is not loaded"); return; } window.grecaptcha.ready(function () { _this2.init(); }); }; head.appendChild(this.recaptchaScript); } } }, { key: "componentDidMount", value: function componentDidMount() { this.addRecaptchaScript(); if (window.grecaptcha) { this.init(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.recaptchaScript) { this.recaptchaScript.parentNode.removeChild(this.recaptchaScript); } } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/React.createElement("div", { id: this.props.id, ref: function ref(el) { return _this3.targetEL = el; } }); } }]); return Captcha; }(Component); _defineProperty(Captcha, "defaultProps", { id: null, siteKey: null, theme: "light", type: "image", size: "normal", tabIndex: 0, language: "en", onResponse: null, onExpire: null }); export { Captcha };
ajax/libs/material-ui/4.9.2/es/ExpansionPanelActions/ExpansionPanelActions.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export const styles = { /* Styles applied to the root element. */ root: { display: 'flex', alignItems: 'center', padding: 8, justifyContent: 'flex-end' }, /* Styles applied to the root element if `disableSpacing={false}`. */ spacing: { '& > :not(:first-child)': { marginLeft: 8 } } }; const ExpansionPanelActions = React.forwardRef(function ExpansionPanelActions(props, ref) { const { classes, className, disableSpacing = false } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "disableSpacing"]); return React.createElement("div", _extends({ className: clsx(classes.root, className, !disableSpacing && classes.spacing), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? ExpansionPanelActions.propTypes = { /** * The content of the component. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, the actions do not have additional margin. */ disableSpacing: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiExpansionPanelActions' })(ExpansionPanelActions);
ajax/libs/react-instantsearch/5.2.0-beta.2/Connectors.js
cdnjs/cdnjs
/*! React InstantSearch 5.2.0-beta.2 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Connectors = {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } 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); } function nextTick(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); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd () { return '/' } function chdir (dir) { throw new Error('process.chdir is not supported'); }function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function(){ return (new Date()).getTime() }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp){ var clocktime = performanceNow.call(performance)*1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor((clocktime%1)*1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds<0) { seconds--; nanoseconds += 1e9; } } return [seconds,nanoseconds] } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** * 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; }; var emptyFunction_1 = emptyFunction; /** * 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) {}; 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; } } var invariant_1 = invariant; /* 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; } } var objectAssign = 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; }; /** * 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'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // It is still safe when called from React. return; } invariant_1( false, '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' ); } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * 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. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$1.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; } catch (e) {} var result = nativeObjectToString.call(value); { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype, objectProto$2 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$3.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$3.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$4.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = _mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } var _equalByTag = equalByTag; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$6.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable$1.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', boolTag$1 = '[object Boolean]', dateTag$1 = '[object Date]', errorTag$1 = '[object Error]', funcTag$1 = '[object Function]', mapTag$1 = '[object Map]', numberTag$1 = '[object Number]', objectTag = '[object Object]', regexpTag$1 = '[object RegExp]', setTag$1 = '[object Set]', stringTag$1 = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag$1 = '[object ArrayBuffer]', dataViewTag$1 = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$7.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$9.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$7.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$a = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$a.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag$2 = '[object Map]', objectTag$1 = '[object Object]', promiseTag = '[object Promise]', setTag$2 = '[object Set]', weakMapTag$1 = '[object WeakMap]'; var dataViewTag$2 = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView), mapCtorString = _toSource(_Map), promiseCtorString = _toSource(_Promise), setCtorString = _toSource(_Set), weakMapCtorString = _toSource(_WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2) || (_Map && getTag(new _Map) != mapTag$2) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$2) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$2; case mapCtorString: return mapTag$2; case promiseCtorString: return promiseTag; case setCtorString: return setTag$2; case weakMapCtorString: return weakMapTag$1; } } return result; }; } var _getTag = getTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]', arrayTag$1 = '[object Array]', objectTag$2 = '[object Object]'; /** Used for built-in method references. */ var objectProto$b = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$b.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$1 : _getTag(object), othTag = othIsArr ? arrayTag$1 : _getTag(other); objTag = objTag == argsTag$2 ? objectTag$2 : objTag; othTag = othTag == argsTag$2 ? objectTag$2 : othTag; var objIsObj = objTag == objectTag$2, othIsObj = othTag == objectTag$2, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1, COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** `Object#toString` result references. */ var symbolTag$1 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1, COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } var _createFind = createFind; /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } var _baseFindIndex = baseFindIndex; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = _createFind(findIndex_1); var find_1 = find; /** `Object#toString` result references. */ var mapTag$3 = '[object Map]', setTag$3 = '[object Set]'; /** Used for built-in method references. */ var objectProto$c = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$a = objectProto$c.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$3 || tag == setTag$3) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$a.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty = defineProperty; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty) { _defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$d = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$b = objectProto$d.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty$b.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$e = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$c = objectProto$e.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$c.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /** Used for built-in method references. */ var objectProto$f = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$d = objectProto$f.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$d.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined, symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$2 = '[object Boolean]', dateTag$2 = '[object Date]', mapTag$4 = '[object Map]', numberTag$2 = '[object Number]', regexpTag$2 = '[object RegExp]', setTag$4 = '[object Set]', stringTag$2 = '[object String]', symbolTag$2 = '[object Symbol]'; var arrayBufferTag$2 = '[object ArrayBuffer]', dataViewTag$3 = '[object DataView]', float32Tag$1 = '[object Float32Array]', float64Tag$1 = '[object Float64Array]', int8Tag$1 = '[object Int8Array]', int16Tag$1 = '[object Int16Array]', int32Tag$1 = '[object Int32Array]', uint8Tag$1 = '[object Uint8Array]', uint8ClampedTag$1 = '[object Uint8ClampedArray]', uint16Tag$1 = '[object Uint16Array]', uint32Tag$1 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$2: return _cloneArrayBuffer(object); case boolTag$2: case dateTag$2: return new Ctor(+object); case dataViewTag$3: return _cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return _cloneTypedArray(object, isDeep); case mapTag$4: return new Ctor; case numberTag$2: case stringTag$2: return new Ctor(object); case regexpTag$2: return _cloneRegExp(object); case setTag$4: return new Ctor; case symbolTag$2: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** `Object#toString` result references. */ var mapTag$5 = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike_1(value) && _getTag(value) == mapTag$5; } var _baseIsMap = baseIsMap; /* Node.js helper references. */ var nodeIsMap = _nodeUtil && _nodeUtil.isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap; var isMap_1 = isMap; /** `Object#toString` result references. */ var setTag$5 = '[object Set]'; /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike_1(value) && _getTag(value) == setTag$5; } var _baseIsSet = baseIsSet; /* Node.js helper references. */ var nodeIsSet = _nodeUtil && _nodeUtil.isSet; /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet; var isSet_1 = isSet; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]', arrayTag$2 = '[object Array]', boolTag$3 = '[object Boolean]', dateTag$3 = '[object Date]', errorTag$2 = '[object Error]', funcTag$2 = '[object Function]', genTag$1 = '[object GeneratorFunction]', mapTag$6 = '[object Map]', numberTag$3 = '[object Number]', objectTag$3 = '[object Object]', regexpTag$3 = '[object RegExp]', setTag$6 = '[object Set]', stringTag$3 = '[object String]', symbolTag$3 = '[object Symbol]', weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$3 = '[object ArrayBuffer]', dataViewTag$4 = '[object DataView]', float32Tag$2 = '[object Float32Array]', float64Tag$2 = '[object Float64Array]', int8Tag$2 = '[object Int8Array]', int16Tag$2 = '[object Int16Array]', int32Tag$2 = '[object Int32Array]', uint8Tag$2 = '[object Uint8Array]', uint8ClampedTag$2 = '[object Uint8ClampedArray]', uint16Tag$2 = '[object Uint16Array]', uint32Tag$2 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$3] = cloneableTags[arrayTag$2] = cloneableTags[arrayBufferTag$3] = cloneableTags[dataViewTag$4] = cloneableTags[boolTag$3] = cloneableTags[dateTag$3] = cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = cloneableTags[int32Tag$2] = cloneableTags[mapTag$6] = cloneableTags[numberTag$3] = cloneableTags[objectTag$3] = cloneableTags[regexpTag$3] = cloneableTags[setTag$6] = cloneableTags[stringTag$3] = cloneableTags[symbolTag$3] = cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true; cloneableTags[errorTag$2] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$2] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$3 || tag == argsTag$3 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = _initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet_1(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); return result; } if (isMap_1(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } var last_1 = last; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1)); } var _parent = parent; /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = _castPath(path, object); object = _parent(object, path); return object == null || delete object[_toKey(last_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype, objectProto$g = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$e = objectProto$g.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$4) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$e.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? _baseFlatten(array, 1) : []; } var flatten_1 = flatten; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax$1(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax$1(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { return _defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return _setToString(_overRest(func, undefined, flatten_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1, CLONE_FLAT_FLAG$1 = 2, CLONE_SYMBOLS_FLAG$1 = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = _flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = _arrayMap(paths, function(path) { path = _castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); _copyObject(object, _getAllKeysIn(object), result); if (isDeep) { result = _baseClone(result, CLONE_DEEP_FLAG$1 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, _customOmitClone); } var length = paths.length; while (length--) { _baseUnset(result, paths[length]); } return result; }); var omit_1 = omit; /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } var _baseIsNaN = baseIsNaN; /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } var _strictIndexOf = strictIndexOf; /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); } var _baseIndexOf = baseIndexOf; /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && _baseIndexOf(array, value, 0) > -1; } var _arrayIncludes = arrayIncludes; /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } var _arrayIncludesWith = arrayIncludesWith; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? _arrayIncludesWith : _arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = _arrayMap(array, _baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new _SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } var _baseIntersection = baseIntersection; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = _baseRest(function(arrays) { var mapped = _arrayMap(arrays, _castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? _baseIntersection(mapped) : []; }); var intersection_1 = intersection; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity_1; } var _castFunction = castFunction; /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && _baseForOwn(object, _castFunction(iteratee)); } var forOwn_1 = forOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var _baseFilter = baseFilter; /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } var _arrayReduce = arrayReduce; /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } var _baseReduce = baseReduce; /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : _baseSlice(array, start, end); } var _castSlice = castSlice; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsEndIndex = charsEndIndex; /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsStartIndex = charsStartIndex; /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff', rsComboMarksRange$1 = '\\u0300-\\u036f', reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']', rsCombo = '[' + rsComboRange$1 + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange$1 + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange$1 + ']?', rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } var _unicodeToArray = unicodeToArray; /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } if (!string || !(chars = _baseToString(chars))) { return string; } var strSymbols = _stringToArray(string), chrSymbols = _stringToArray(chars), start = _charsStartIndex(strSymbols, chrSymbols), end = _charsEndIndex(strSymbols, chrSymbols) + 1; return _castSlice(strSymbols, start, end).join(''); } var trim_1 = trim; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** Used for built-in method references. */ var objectProto$h = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$f = objectProto$h.hasOwnProperty; /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = _baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn_1(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq_1(value, objectProto$h[key]) && !hasOwnProperty$f.call(object, key))) { object[key] = source[key]; } } } return object; }); var defaults_1 = defaults; /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * Gets the value at `key`, unless `key` is "__proto__". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { return key == '__proto__' ? undefined : object[key]; } var _safeGet = safeGet; /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return _copyObject(value, keysIn_1(value)); } var toPlainObject_1 = toPlainObject; /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = _safeGet(object, key), srcValue = _safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { _assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(objValue)) { newValue = _copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = _cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = _cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || (srcIndex && isFunction_1(objValue))) { newValue = _initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } _assignMergeValue(object, key, newValue); } var _baseMergeDeep = baseMergeDeep; /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } _baseFor(source, function(srcValue, key) { if (isObject_1(srcValue)) { stack || (stack = new _Stack); _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(_safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } _assignMergeValue(object, key, newValue); } }, keysIn_1); } var _baseMerge = baseMerge; /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return _baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var _createAssigner = createAssigner; /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = _createAssigner(function(object, source, srcIndex) { _baseMerge(object, source, srcIndex); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (Array.isArray(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated refinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults_1({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * kinds of behavior can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optional parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined_1(attribute)) { if (isEmpty_1(refinementList)) return refinementList; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(refinementList[attribute])) return refinementList; return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newRefinementList = reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(facetList)) { if (facetList.length !== values.length) hasChanged = true; memo[key] = facetList; } else hasChanged = true; return memo; }, {}); if (hasChanged) return newRefinementList; return refinementList; } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find_1(array, function(currentValue) { return isEqual_1(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * separated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each faceted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys_1(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); // there's two formats of insideBoundingBox, we need to parse // the one which is an array of float geo rectangles if (Array.isArray(partialState.insideBoundingBox)) { numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) { return geoRect.map(function(value) { return parseFloat(value); }); }); } if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (Array.isArray(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach_1(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; var patch = { numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }; if (patch.numericRefinements === this.numericRefinements && patch.facetsRefinements === this.facetsRefinements && patch.facetsExcludes === this.facetsExcludes && patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements && patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements) { return this; } return this.setQueryParameters(patch); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) faceting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber_1(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined_1(attribute)) { if (isEmpty_1(this.numericRefinements)) return this.numericRefinements; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(this.numericRefinements[attribute])) return this.numericRefinements; return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newNumericRefinements = reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) { if (outValues.length !== values.length) hasChanged = true; operatorList[operator] = outValues; } else hasChanged = true; }); if (!isEmpty_1(operatorList)) memo[key] = operatorList; return memo; }, {}); if (hasChanged) return newNumericRefinements; return this.numericRefinements; } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter_1(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the faceted attribute. * @method * @param {string} facet name of the attribute used for faceting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf_1(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf_1(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value, optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf_1(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf_1(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys_1(params); forEach_1(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState_1(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find_1( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map_1(path, trim_1); }, toString: function() { return JSON.stringify(this, null, 2); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ var SearchParameters_1 = SearchParameters; /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } var compact_1 = compact; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? _baseSum(array, _baseIteratee(iteratee, 2)) : 0; } var sumBy_1 = sumBy; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !_metaMap ? identity_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = _baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax$4(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax$5(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } var _composeArgsRight = composeArgsRight; /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$i = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$g = objectProto$i.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = _realNames[result], length = hasOwnProperty$g.call(_realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } var _getFuncName = getFuncName; /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = _baseCreate(_baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; var _LodashWrapper = LodashWrapper; /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof _LazyWrapper) { return wrapper.clone(); } var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = _copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$j = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$h = objectProto$j.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$h.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = _getFuncName(func), other = wrapperLodash[funcName]; if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = _getData(other); return !!data && func === data[0]; } var _isLaziable = isLaziable; /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = _shortOut(_baseSetData); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } var _getWrapDetails = getWrapDetails; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG$1], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { _arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } var _updateWrapDetails = updateWrapDetails; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1, WRAP_BIND_KEY_FLAG$1 = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG$1 = 8, WRAP_PARTIAL_FLAG$1 = 32, WRAP_PARTIAL_RIGHT_FLAG$1 = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG$1, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (_isLaziable(func)) { _setData(result, newData); } result.placeholder = placeholder; return _setWrapToString(result, func, bitmask); } var _createRecurry = createRecurry; /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1, WRAP_BIND_KEY_FLAG$2 = 2, WRAP_CURRY_FLAG$2 = 8, WRAP_CURRY_RIGHT_FLAG$1 = 16, WRAP_ARY_FLAG$1 = 128, WRAP_FLIP_FLAG$1 = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG$1, isBind = bitmask & WRAP_BIND_FLAG$3, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2, isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1), isFlip = bitmask & WRAP_FLIP_FLAG$1, Ctor = isBindKey ? undefined : _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = _getHolder(wrapper), holdersCount = _countHolders(args, placeholder); } if (partials) { args = _composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = _composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = _replaceHolders(args, placeholder); return _createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = _reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== _root && this instanceof wrapper) { fn = Ctor || _createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } var _createHybrid = createHybrid; /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = _getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : _replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return _createRecurry( func, bitmask, _createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return _apply(fn, this, args); } return wrapper; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG$4, Ctor = _createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return _apply(fn, isBind ? thisArg : this, args); } return wrapper; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 1, WRAP_BIND_KEY_FLAG$3 = 2, WRAP_CURRY_BOUND_FLAG$1 = 4, WRAP_CURRY_FLAG$3 = 8, WRAP_ARY_FLAG$2 = 128, WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$5) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? _composeArgs(partials, value, source[4]) : value; data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1, WRAP_BIND_KEY_FLAG$4 = 2, WRAP_CURRY_FLAG$4 = 8, WRAP_CURRY_RIGHT_FLAG$2 = 16, WRAP_PARTIAL_FLAG$2 = 32, WRAP_PARTIAL_RIGHT_FLAG$2 = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$6(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : _getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { _mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax$6(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) { bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2); } if (!bitmask || bitmask == WRAP_BIND_FLAG$6) { var result = _createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) { result = _createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) { result = _createPartial(func, bitmask, thisArg, partials); } else { result = _createHybrid.apply(undefined, newData); } var setter = data ? _baseSetData : _setData; return _setWrapToString(setter(result, newData), func, bitmask); } var _createWrap = createWrap; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG$3 = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partial)); return _createWrap(func, WRAP_PARTIAL_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partialRight)); return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } var _baseClamp = baseClamp; /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject_1(object)) { return object; } path = _castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = _toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = _baseGet(object, path); if (predicate(value, path)) { _baseSet(result, _castPath(path, object), value); } } return result; } var _basePickBy = basePickBy; /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = _arrayMap(_getAllKeysIn(object), function(prop) { return [prop]; }); predicate = _baseIteratee(predicate); return _basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce_1(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find_1(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy_1( map_1( pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the faceting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objects matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} name the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric filters. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach_1(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy_1(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @deprecated * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @deprecated * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * True if the counts of the facets is exhaustive * @member {boolean} */ this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount; /** * True if the number of hits is exhaustive * @member {boolean} */ this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * queryID is the unique identifier of the query used to generate the current search results. * This value is only available if the `clickAnalytics` search parameter is set to `true`. * @member {string} */ this.queryID = mainSubResponse.queryID; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the faceted attribute * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the faceted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find_1(results.facets, predicate); if (!facet) return []; return map_1(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (Array.isArray(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (Array.isArray(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (Array.isArray(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the faceted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find_1(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var util = createCommonjsModule(function (module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(commonjsGlobal.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function(prev, cur) { if (cur.indexOf('\n') >= 0) ; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = inherits_browser; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } var events = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber$1(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject$1(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined$1(handler)) return false; if (isFunction$1(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject$1(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction$1(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject$1(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject$1(this._events[type]) && !this._events[type].warned) { if (!isUndefined$1(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction$1(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction$1(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$1(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction$1(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction$1(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction$1(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$1(arg) { return typeof arg === 'function'; } function isNumber$1(arg) { return typeof arg === 'number'; } function isObject$1(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$1(arg) { return arg === void 0; } /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; var DerivedHelper_1 = DerivedHelper; var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters, analytics: false, clickAnalytics: false }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (Array.isArray(value)) { var vs = map_1(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce_1( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var searchForFacetSearchParameters = { facetQuery: query, facetName: facetName }; if (typeof maxFacetHits === 'number') { searchForFacetSearchParameters.maxFacetHits = maxFacetHits; } var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { _baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } var _baseInverter = baseInverter; /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return _baseInverter(object, setter, toIteratee(iteratee), {}); }; } var _createInverter = createInverter; /** Used for built-in method references. */ var objectProto$k = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$2 = objectProto$k.toString; /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = _createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString$2.call(value); } result[value] = key; }, constant_1(identity_1)); var invert_1 = invert; var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; var utils = createCommonjsModule(function (module, exports) { var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults$1 = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; var stringify_1 = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults$1.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$1.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$1.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$1.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$1.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$1.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$1.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; var has = Object.prototype.hasOwnProperty; var defaults$2 = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults$2.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$2.decoder); val = options.decoder(part.slice(pos + 1), defaults$2.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var parse = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$2.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$2.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$2.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$2.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$2.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$2.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$2.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$2.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1, WRAP_PARTIAL_FLAG$4 = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = _baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return _basePickBy(object, paths, function(value, path) { return hasIn_1(object, path); }); } var _basePick = basePick; /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = _flatRest(function(object, paths) { return object == null ? {} : _basePick(object, paths); }); var pick_1 = pick; /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, iteratee(value, key, object), value); }); return result; } var mapKeys_1 = mapKeys; /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (Array.isArray(input)) { return map_1(input, recursiveEncode); } if (isString_1(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ var getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.26.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {SearchParameters} state the parameters used for this search * it is the first search. * @property {string} facet the facet searched into * @property {string} query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(state, facet, query) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {SearchParameters} state the parameters used for this search * it is the first search. * @example * helper.on('searchOnce', function(state) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Event triggered when the queue of queries have been depleted (with any result or outdated queries) * @event AlgoliaSearchHelper#event:searchQueueEmpty * @example * helper.on('searchQueueEmpty', function() { * console.log('No more search pending'); * // This is received before the result event if we're not expecting new results * }); * * helper.search(); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (client.addAlgoliaAgent && !doesClientAgentContainsHelper(client)) { client.addAlgoliaAgent('JS Helper ' + version$1); } this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; this._currentNbQueries = 0; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder_1._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occurred it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder_1._getQueries(tempState.index, tempState); var self = this; this._currentNbQueries++; this.emit('searchOnce', tempState); if (cb) { this.client .search(queries) .then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(null, new SearchResults_1(tempState, content.results), tempState); }) .catch(function(err) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(err, null, tempState); }); return undefined; } return this.client.search(queries).then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); return { content: new SearchResults_1(tempState, content.results), state: tempState, _originalResponse: content }; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurrence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {object} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query inside the engine */ /** * Search for facet values based on an query and the name of a faceted attribute. This * triggers a search and will return a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed down to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} facet the name of the faceted attribute * @param {string} query the string query for the search * @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100 * @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes * it in the generated query. * @return {promise.<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) { var state = this.state.setQueryParameters(userState || {}); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, state); this._currentNbQueries++; var self = this; this.emit('searchForFacetValues', state, facet, query); var searchForFacetValuesPromise = typeof this.client.searchForFacetValues === 'function' ? this.client.searchForFacetValues([{indexName: state.index, params: algoliaQuery}]) : this.client.initIndex(state.index).searchForFacetValues(algoliaQuery); return searchForFacetValuesPromise.then(function addIsRefined(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); content = Array.isArray(content) ? content[0] : content; content.facetHits = forEach_1(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this._change(this.state.setPage(0).setQuery(q)); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this._change(this.state.setPage(0).clearRefinements(name)); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this._change(this.state.setPage(0).clearTags()); return this; }; /** * Adds a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addHierarchicalFacetRefinement(facet, value)); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).addNumericRefinement(attribute, operator, value)); return this; }; /** * Adds a filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).addExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this._change(this.state.setPage(0).addTagRefinement(tag)); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optional, triggering different behavior: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).removeNumericRefinement(attribute, operator, value)); return this; }; /** * Removes a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this._change(this.state.setPage(0).removeHierarchicalFacetRefinement(facet)); return this; }; /** * Removes a filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).removeExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this._change(this.state.setPage(0).removeTagRefinement(tag)); return this; }; /** * Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).toggleExcludeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).toggleFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this._change(this.state.setPage(0).toggleTagRefinement(tag)); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this._change(this.state.setPage(page)); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this._change(this.state.setPage(0).setIndex(name)); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { this._change(this.state.setPage(0).setQueryParameter(parameter, value)); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this._change(SearchParameters_1.make(newState)); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optional filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optional parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters_1(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty_1(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific faceted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for faceting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten_1(derivedQueries)); var queryId = this._queryId++; this._currentNbQueries++; try { this.client.search(queries) .then(this._dispatchAlgoliaResponse.bind(this, states, queryId)) .catch(this._dispatchAlgoliaError.bind(this, queryId)); } catch (err) { // If we reach this part, we're in an internal error state this.emit('error', err); } }; /** * Transform the responses as sent by the server and transform them into a user * usable object that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, content) { // FIXME remove the number of outdated queries discarded instead of just one if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= (queryId - this._lastQueryIdReceived); this._lastQueryIdReceived = queryId; if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); var results = content.results; forEach_1(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults); helper.emit('result', formattedResponse, state); }); }; AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function(queryId, err) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= queryId - this._lastQueryIdReceived; this._lastQueryIdReceived = queryId; this.emit('error', err); if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function(newState) { if (newState !== this.state) { this.state = newState; this.emit('change', this.state, this.lastResults); } }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache && this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper_1(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * This method returns true if there is currently at least one on-going search. * @return {boolean} true if there is a search pending */ AlgoliaSearchHelper.prototype.hasPendingRequests = function() { return this._currentNbQueries > 0; }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the faceting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } var algoliasearch_helper = AlgoliaSearchHelper; /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters; // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js var shallowEqual = function shallowEqual(objA, objB) { if (objA === objB) { return true; } 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. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; }; var getDisplayName = function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; }; var resolved = Promise.resolve(); var defer = function defer(f) { resolved.then(f); }; var removeEmptyKey = function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; }; function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; defer(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } var HIGHLIGHT_TAGS = { highlightPreTag: '<ais-highlight-0000000000>', highlightPostTag: '</ais-highlight-0000000000>' }; /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref) { var preTag = _ref.preTag, postTag = _ref.postTag, _ref$highlightedValue = _ref.highlightedValue, highlightedValue = _ref$highlightedValue === undefined ? '' : _ref$highlightedValue; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } /** * Find an highlighted attribute given an `attribute` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attribute - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isHighlighted: boolean}. */ function parseAlgoliaHit(_ref2) { var _ref2$preTag = _ref2.preTag, preTag = _ref2$preTag === undefined ? '<em>' : _ref2$preTag, _ref2$postTag = _ref2.postTag, postTag = _ref2$postTag === undefined ? '</em>' : _ref2$postTag, highlightProperty = _ref2.highlightProperty, attribute = _ref2.attribute, hit = _ref2.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = get_1(hit[highlightProperty], attribute, {}); if (Array.isArray(highlightObject)) { return highlightObject.map(function (item) { return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: item.value }); }); } return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightObject.value }); } 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; }; function _defineProperty$1(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; } /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @param {number} stalledSearchDelay - time (in ms) after the search is stalled * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName, _ref$initialState = _ref.initialState, initialState = _ref$initialState === undefined ? {} : _ref$initialState, searchClient = _ref.searchClient, resultsState = _ref.resultsState, stalledSearchDelay = _ref.stalledSearchDelay; var baseSP = new algoliasearchHelper_4(_extends({ index: indexName }, HIGHLIGHT_TAGS)); var stalledSearchTimer = null; var helper = algoliasearchHelper_1(searchClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); helper.on('search', handleNewSearch); var derivedHelpers = {}; var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used. var initialSearchParameters = helper.state; var widgetsManager = createWidgetsManager(onWidgetsUpdate); var store = createStore({ widgets: initialState, metadata: [], results: resultsState || null, error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); var skip = false; function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function clearCache() { helper.clearCache(); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { indexMapping = {}; var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !widget.context.multiIndexContext && (widget.props.indexName === indexName || !widget.props.indexName); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); indexMapping[sharedParameters.index] = indexName; var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex !== indexName || widget.props.indexName && widget.props.indexName !== indexName; }).reduce(function (indices, widget) { var targetedIndex = widget.context.multiIndexContext ? widget.context.multiIndexContext.targetedIndex : widget.props.indexName; var index = find_1(indices, function (i) { return i.targetedIndex === targetedIndex; }); if (index) { index.widgets.push(widget); } else { indices.push({ targetedIndex: targetedIndex, widgets: [widget] }); } return indices; }, []); var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex === indexName || widget.props.indexName && widget.props.indexName === indexName; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[mainIndexParameters.index] = indexName; return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state), sharedParameters = _getSearchParameters.sharedParameters, mainIndexParameters = _getSearchParameters.mainIndexParameters, derivatedWidgets = _getSearchParameters.derivatedWidgets; Object.keys(derivedHelpers).forEach(function (key) { return derivedHelpers[key].detach(); }); derivedHelpers = {}; helper.setState(sharedParameters); derivatedWidgets.forEach(function (derivatedSearchParameters) { var index = derivatedSearchParameters.targetedIndex; var derivedHelper = helper.derive(function () { var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[parameters.index] = index; return parameters; }); derivedHelper.on('result', handleSearchSuccess); derivedHelper.on('error', handleSearchError); derivedHelpers[index] = derivedHelper; }); helper.setState(mainIndexParameters); helper.search(); } } function handleSearchSuccess(content) { var state = store.getState(); var results = state.results ? state.results : {}; /* if switching from mono index to multi index and vice versa, results needs to reset to {}*/ results = !isEmpty_1(derivedHelpers) && results.getFacetByName ? {} : results; if (!isEmpty_1(derivedHelpers)) { results[indexMapping[content.index]] = content; } else { results = content; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var nextState = omit_1(_extends({}, store.getState(), { isSearchStalled: true }), 'resultsFacetValues'); store.setState(nextState); }, stalledSearchDelay); } } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(_ref2) { var facetName = _ref2.facetName, query = _ref2.query, maxFacetHits = _ref2.maxFacetHits; store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(facetName, query, maxFacetHits).then(function (content) { var _extends2; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty$1(_extends2, facetName, content.facetHits), _defineProperty$1(_extends2, 'query', query), _extends2)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends$2 = 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; }; }(); 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 === "undefined" ? "undefined" : _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 === "undefined" ? "undefined" : _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; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } else if (props.searchState && !nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @name <InstantSearch> * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one (deprecated in favor of `searchClient`). * @propType {object} [searchClient] - Provide a custom search client. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html). * @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); */ var InstantSearch = function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { _classCallCheck(this, InstantSearch); var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = createInstantSearchManager({ indexName: props.indexName, searchClient: props.searchClient, initialState: initialState, resultsState: props.resultsState, stalledSearchDelay: props.stalledSearchDelay }); return _this; } _createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.props.refresh !== nextProps.refresh) { if (nextProps.refresh) { this.aisManager.clearCache(); } } if (this.props.searchClient !== nextProps.searchClient) { this.aisManager.updateClient(nextProps.searchClient); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this), onSearchParameters: this.onSearchParameters.bind(this) } }; } return { ais: _extends$2({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchParameters', value: function onSearchParameters(getSearchParameters, context, props) { if (this.props.onSearchParameters) { var searchState = this.props.searchState ? this.props.searchState : {}; this.props.onSearchParameters(getSearchParameters, context, props, searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return InstantSearch; }(React.Component); InstantSearch.defaultProps = { stalledSearchDelay: 200 }; InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, searchClient: propTypes.object.isRequired, createURL: propTypes.func, refresh: propTypes.bool.isRequired, searchState: propTypes.object, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired, stalledSearchDelay: propTypes.number }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; var _createClass$2 = 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; }; }(); function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self; } function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _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; } /* eslint valid-jsdoc: 0 */ /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure hitsPerPage={5} /> * <SearchBox /> * <Index indexName="ikea"> * <Hits /> * </Index> * <Index indexName="bestbuy"> * <Hits /> * </Index> * </InstantSearch> * ); */ var Index = function (_Component) { _inherits$2(Index, _Component); function Index(props, context) { _classCallCheck$2(this, Index); var _this = _possibleConstructorReturn$2(this, (Index.__proto__ || Object.getPrototypeOf(Index)).call(this, props)); var widgetsManager = context.ais.widgetsManager; /* we want <Index> to be seen as a regular widget. It means that with only <Index> present a new query will be sent to Algolia. That way you don't need a virtual hits widget to use the connectAutoComplete. */ _this.unregisterWidget = widgetsManager.registerWidget(_this); return _this; } _createClass$2(Index, [{ key: 'componentWillMount', value: function componentWillMount() { this.context.ais.onSearchParameters(this.getSearchParameters, this.getChildContext(), this.props); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.indexName !== nextProps.indexName) { this.context.ais.widgetsManager.update(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unregisterWidget(); } }, { key: 'getChildContext', value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexName } }; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters, props) { return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return Index; }(React.Component); Index.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired }; Index.childContextTypes = { multiIndexContext: propTypes.object.isRequired }; Index.contextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; /** Used for built-in method references. */ var objectProto$l = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$i = objectProto$l.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$i.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has$1(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has$1; var _extends$3 = 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$3 = 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; }; }(); function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn$3(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self; } function _inherits$3(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _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; } /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { _inherits$3(Connector, _Component); function Connector(props, context) { _classCallCheck$3(this, Connector); var _this = _possibleConstructorReturn$3(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; var canRender = false; _this.state = { props: _this.getProvidedProps(_extends$3({}, props, { canRender: canRender })), canRender: canRender // use to know if a component is rendered (browser), or not (server). }; _this.unsubscribe = store.subscribe(function () { if (_this.state.canRender) { _this.setState({ props: _this.getProvidedProps(_extends$3({}, _this.props, { canRender: _this.state.canRender })) }); } }); if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget(_this); } return _this; } _createClass$3(Connector, [{ key: 'getMetadata', value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: 'transitionState', value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: 'componentDidMount', value: function componentDidMount() { this.setState({ canRender: true }); } }, { key: 'componentWillMount', value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); // will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends$3({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange(removeEmptyKey(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: 'render', value: function render() { if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends$3({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }, _initialiseProps = function _initialiseProps() { var _this2 = this; this.getProvidedProps = function (props) { var store = _this2.context.ais.store; var _store$getState = store.getState(), results = _store$getState.results, searching = _store$getState.searching, error = _store$getState.error, widgets = _store$getState.widgets, metadata = _store$getState.metadata, resultsFacetValues = _store$getState.resultsFacetValues, searchingForFacetValues = _store$getState.searchingForFacetValues, isSearchStalled = _store$getState.isSearchStalled; var searchResults = { results: results, searching: searching, error: error, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled }; return connectorDesc.getProvidedProps.call(_this2, props, widgets, searchResults, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this2.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this2.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this2].concat(args)); }; }, _temp; }; } /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = _arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = _arrayMap(values, _baseUnary(iteratee)); } if (comparator) { includes = _arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE$1) { includes = _cacheHas; isCommon = false; values = new _SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } var _baseDifference = baseDifference; /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = _baseRest(function(array, values) { return isArrayLikeObject_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; var _extends$4 = 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; }; function _defineProperty$2(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 getIndex(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndex(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndex(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { // When we have a multi index page with shared widgets we should also // reset their page to 1 if the resetPage is provided. Otherwise the // indices will always be reset // see: https://github.com/algolia/react-instantsearch/issues/310 // see: https://github.com/algolia/react-instantsearch/issues/637 if (searchState.indices && resetPage) { Object.keys(searchState.indices).forEach(function (targetedIndex) { searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace); }); } return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var index = getIndex(context); var state = has_1(searchState, 'indices.' + index) ? _extends$4({}, searchState.indices, _defineProperty$2({}, index, _extends$4({}, searchState.indices[index], nextRefinement, page))) : _extends$4({}, searchState.indices, _defineProperty$2({}, index, _extends$4({}, nextRefinement, page))); return _extends$4({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _extends$4({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) { var _extends4; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = has_1(searchState, 'indices.' + index) ? _extends$4({}, searchState.indices, _defineProperty$2({}, index, _extends$4({}, searchState.indices[index], (_extends4 = {}, _defineProperty$2(_extends4, namespace, _extends$4({}, searchState.indices[index][namespace], nextRefinement)), _defineProperty$2(_extends4, 'page', 1), _extends4)))) : _extends$4({}, searchState.indices, _defineProperty$2({}, index, _extends$4(_defineProperty$2({}, namespace, nextRefinement), page))); return _extends$4({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends$4({}, searchState, _defineProperty$2({}, namespace, _extends$4({}, searchState[namespace], nextRefinement)), page); } function getNamespaceAndAttributeName(id) { var parts = id.match(/^([^.]*)\.(.*)/); var namespace = parts && parts[1]; var attributeName = parts && parts[2]; return { namespace: namespace, attributeName: attributeName }; } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) { var index = getIndex(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id); if (refinements) { var currentRefinement = void 0; if (hasMultipleIndex(context)) { currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id); } else { currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id); } return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var indexName = getIndex(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndex(context) && Boolean(searchState.indices)) { return cleanUpValueWithMutliIndex({ attribute: attributeName, searchState: searchState, indexName: indexName, id: id, namespace: namespace }); } return cleanUpValueWithSingleIndex({ attribute: attributeName, searchState: searchState, id: id, namespace: namespace }); } function cleanUpValueWithSingleIndex(_ref) { var searchState = _ref.searchState, id = _ref.id, namespace = _ref.namespace, attribute = _ref.attribute; if (namespace) { return _extends$4({}, searchState, _defineProperty$2({}, namespace, omit_1(searchState[namespace], attribute))); } return omit_1(searchState, id); } function cleanUpValueWithMutliIndex(_ref2) { var searchState = _ref2.searchState, indexName = _ref2.indexName, id = _ref2.id, namespace = _ref2.namespace, attribute = _ref2.attribute; var index = searchState.indices[indexName]; if (namespace && index) { return _extends$4({}, searchState, { indices: _extends$4({}, searchState.indices, _defineProperty$2({}, indexName, _extends$4({}, index, _defineProperty$2({}, namespace, omit_1(index[namespace], attribute))))) }); } return omit_1(searchState, 'indices.' + indexName + '.' + id); } var _extends$5 = 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; }; function _defineProperty$3(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 getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = _defineProperty$3({}, id, _extends$5({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = getIndex(this.context); var subState = hasMultipleIndex(this.context) && searchState.indices ? searchState.indices[index] : searchState; var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = subState[id][item]; } return acc; }, {}); var nextValue = _defineProperty$3({}, id, configureState); return refineValue(searchState, nextValue, this.context); } }); /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * import { InstantSearch, Configure, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure hitsPerPage={5} /> * <Hits /> * </InstantSearch> * ); */ connectConfigure(function () { return null; }); function _defineProperty$4(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); } } var getId$1 = function getId() { return 'query'; }; function getCurrentRefinement(props, searchState, context) { var id = getId$1(); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function getHits(searchResults) { if (searchResults.results) { if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) { return searchResults.results.hits; } else { return Object.keys(searchResults.results).reduce(function (hits, index) { return [].concat(_toConsumableArray(hits), [{ index: index, hits: searchResults.results[index].hits }]); }, []); } } else { return []; } } function _refine(props, searchState, nextRefinement, context) { var id = getId$1(); var nextValue = _defineProperty$4({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, getId$1()); } /** * connectAutoComplete connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * @name connectAutoComplete * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state. * @providedPropType {function} refine - a function to change the query. * @providedPropType {string} currentRefinement - the query to search for. */ var connectAutoComplete = createConnector({ displayName: 'AlgoliaAutoComplete', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { hits: getHits(searchResults), currentRefinement: getCurrentRefinement(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, /* connectAutoComplete needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context)); } }); function _defineProperty$5(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; } var getId$2 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function _refine$1(props, searchState, nextRefinement, context) { var id = getId$2(props); var nextValue = _defineProperty$5({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace); } function transformValue(values) { return values.reduce(function (acc, item) { if (item.isRefined) { acc.push({ label: item.name, // If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label // If dealing with the first level, "value" is equal to the current label value: item.path }); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one if (item.data) { acc = acc.concat(transformValue(item.data, acc)); } } return acc; }, []); } /** * The breadcrumb component is s a type of secondary navigation scheme that * reveals the user’s location in a website or web application. * * @name connectBreadcrumb * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a Breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display. */ var connectBreadcrumb = createConnector({ displayName: 'AlgoliaBreadcrumb', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$2(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], canRefine: false }; } var values = results.getFacetValues(id); var items = values.data ? transformValue(values.data) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { canRefine: transformedItems.length > 0, items: transformedItems }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); } }); var _extends$6 = 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; }; /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items.map(function (item) { return _extends$6({}, item, { id: meta.id, index: meta.index }); })); } } return res; }, []); return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); var _extends$7 = 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; }; function _defineProperty$6(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; } var getId$3 = function getId(props) { return props.attributes[0]; }; var namespace$1 = 'hierarchicalMenu'; function getCurrentRefinement$1(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$3(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$1(path, props, searchState, context) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement$1(props, searchState, context); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_4({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue$1(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue$1(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue$1(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _extends$7({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine$2(props, searchState, nextRefinement, context) { var id = getId$3(props); var nextValue = _defineProperty$6({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, namespace$1 + '.' + getId$3(props)); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit. * @propType {number} [limit=10] - The maximum number of items displayed. * @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ var connectHierarchicalMenu = createConnector({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: propTypes.string, rootPath: propTypes.string, showParentLevel: propTypes.bool, defaultRefinement: propTypes.string, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; var id = getId$3(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement$1(props, searchState, this.context), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue$1(value.data, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement$1(props, searchState, this.context), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; var id = getId$3(props); var itemsLimit = showMore ? showMoreLimit : limit; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit) }); var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId$3(props); var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attribute: rootAttribute, value: function value(nextState) { return _refine$2(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty, _ref$preTag = _ref.preTag, preTag = _ref$preTag === undefined ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === undefined ? HIGHLIGHT_TAGS.highlightPostTag : _ref$postTag; return parseAlgoliaHit({ attribute: attribute, highlightProperty: highlightProperty, hit: hit, preTag: preTag, postTag: postTag }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attribute` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects. * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom'; * * const CustomHighlight = connectHighlight( * ({ highlight, attribute, hit, highlightProperty }) => { * const highlights = highlight({ * highlightProperty: '_highlightResult', * attribute, * hit * }); * * return highlights.map(part => part.isHighlighted ? ( * <mark>{part.value}</mark> * ) : ( * <span>{part.value}</span> * )); * } * ); * * const Hit = ({ hit }) => ( * <p> * <CustomHighlight attribute="name" hit={hit} /> * </p> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox defaultRefinement="legi" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom'; * * const CustomHits = connectHits(({ hits }) => ( * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="name" hit={hit} /> * </p> * )} * </div> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); var hits = results ? results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); var _extends$8 = 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; }; function _defineProperty$7(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 getId$4() { return 'hitsPerPage'; } function getCurrentRefinement$2(props, searchState, context) { var id = getId$4(); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectHitsPerPage = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$2(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends$8({}, item, { isRefined: true }) : _extends$8({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$4(); var nextValue = _defineProperty$7({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$4()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$2(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId$4() }; } }); function _defineProperty$8(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$1(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 getId$5() { return 'page'; } function getCurrentRefinement$3(props, searchState, context) { var id = getId$5(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ var connectInfiniteHits = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); this._allResults = this._allResults || []; this._previousPage = this._previousPage || 0; if (!results) { return { hits: [], hasMore: false }; } var hits = results.hits, page = results.page, nbPages = results.nbPages; if (page === 0) { this._allResults = hits; } else if (page > this._previousPage) { this._allResults = [].concat(_toConsumableArray$1(this._allResults), _toConsumableArray$1(hits)); } else if (page < this._previousPage) { this._allResults = hits; } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; this._previousPage = page; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$3(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId$5(); var nextPage = getCurrentRefinement$3(props, searchState, this.context) + 1; var nextValue = _defineProperty$8({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, this.context, resetPage); } }); function _defineProperty$9(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; } var namespace$2 = 'menu'; function getId$6(props) { return props.attribute; } function getCurrentRefinement$4(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$6(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$2(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$4(props, searchState, context); return name === currentRefinement ? '' : name; } function getLimit(_ref) { var showMore = _ref.showMore, limit = _ref.limit, showMoreLimit = _ref.showMoreLimit; return showMore ? showMoreLimit : limit; } function _refine$3(props, searchState, nextRefinement, context) { var id = getId$6(props); var nextValue = _defineProperty$9({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, namespace$2 + '.' + getId$6(props)); } var sortBy$1 = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user the ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of diplayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [searchable=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attribute: propTypes.string.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, searchable: propTypes.bool }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$4(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$2(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$2(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = searchable && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$4(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$3(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props)) }); searchParameters = searchParameters.addDisjunctiveFacet(attribute); var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId$6(props); var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: props.attribute + ': ' + currentRefinement, attribute: props.attribute, value: function value(nextState) { return _refine$3(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); function _defineProperty$a(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 stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'), _value$split2 = _slicedToArray(_value$split, 2), startStr = _value$split2[0], endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace$3 = 'multiRange'; function getId$7(props) { return props.attribute; } function getCurrentRefinement$5(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$7(props), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attribute, results, value) { var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine$4(props, searchState, nextRefinement, context) { var nextValue = _defineProperty$a({}, getId$7(props, searchState), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, namespace$3 + '.' + getId$7(props)); } /** * connectNumericMenu connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectNumericMenu * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @kind connector * @propType {string} attribute - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the NumericMenu can display. */ var connectNumericMenu = createConnector({ displayName: 'AlgoliaNumericMenu', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute; var currentRefinement = getCurrentRefinement$5(props, searchState, this.context); var results = getResults(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId$7(props), results, value) : false }; }); var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$4(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$5(props, searchState, this.context)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attribute); if (start) { searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$7(props); var value = getCurrentRefinement$5(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (value !== '') { var _find2 = find_1(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: props.attribute + ': ' + label, attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$4(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); function _defineProperty$b(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 getId$8() { return 'page'; } function getCurrentRefinement$6(props, searchState, context) { var id = getId$8(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine$5(props, searchState, nextPage, context) { var id = getId$8(); var nextValue = _defineProperty$b({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, context, resetPage); } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [padding=3] - How many page links to display around the current page. * @propType {number} [totalPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ var connectPagination = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$6(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$5(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$8()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$6(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$8() }; } }); /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ var connectPoweredBy = createConnector({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps(props) { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite; function _defineProperty$c(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; } /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attribute` prop must be present in “attributes for faceting” * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * The values inside the attribute must be JavaScript numbers (not strings). * @propType {string} attribute - Name of the attribute for faceting * @propType {{min?: number, max?: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {number} [precision=0] - Number of digits after decimal point to use. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {number} min - the minimum value available. * @providedPropType {number} max - the maximum value available. * @providedPropType {number} precision - Number of digits after decimal point to use. */ function getId$9(props) { return props.attribute; } var namespace$4 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min = void 0; if (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max = void 0; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$7(props, searchState, currentRange, context) { var refinement = getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$9(props), {}, function (currentRefinement) { var min = currentRefinement.min, max = currentRefinement.max; var isFloatPrecision = Boolean(props.precision); var nextMin = min; if (typeof nextMin === 'string') { nextMin = isFloatPrecision ? parseFloat(nextMin) : parseInt(nextMin, 10); } var nextMax = max; if (typeof nextMax === 'string') { nextMax = isFloatPrecision ? parseFloat(nextMax) : parseInt(nextMax, 10); } return { min: nextMin, max: nextMax }; }); var hasMinBound = props.min !== undefined; var hasMaxBound = props.max !== undefined; var hasMinRefinment = refinement.min !== undefined; var hasMaxRefinment = refinement.max !== undefined; if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) { throw Error("You can't provide min value lower than range."); } if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) { throw Error("You can't provide max value greater than range."); } if (hasMinBound && !hasMinRefinment) { refinement.min = currentRange.min; } if (hasMaxBound && !hasMaxRefinment) { refinement.max = currentRange.max; } return refinement; } function getCurrentRefinementWithRange(refinement, range) { return { min: refinement.min !== undefined ? refinement.min : range.min, max: refinement.max !== undefined ? refinement.max : range.max }; } function nextValueForRefinement(hasBound, isReset, range, value) { var next = void 0; if (!hasBound && range === value) { next = undefined; } else if (hasBound && isReset) { next = range; } else { next = value; } return next; } function _refine$6(props, searchState, nextRefinement, currentRange, context) { var nextMin = nextRefinement.min, nextMax = nextRefinement.max; var currentMinRange = currentRange.min, currentMaxRange = currentRange.max; var isMinReset = nextMin === undefined || nextMin === ''; var isMaxReset = nextMax === undefined || nextMax === ''; var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined; var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined; var isNextMinValid = isMinReset || _isFinite(nextMinAsNumber); var isNextMaxValid = isMaxReset || _isFinite(nextMaxAsNumber); if (!isNextMinValid || !isNextMaxValid) { throw Error("You can't provide non finite values to the range connector."); } if (nextMinAsNumber < currentMinRange) { throw Error("You can't provide min value lower than range."); } if (nextMaxAsNumber > currentMaxRange) { throw Error("You can't provide max value greater than range."); } var id = getId$9(props); var resetPage = true; var nextValue = _defineProperty$c({}, id, { min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber), max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber) }); return refineValue(searchState, nextValue, context, resetPage, namespace$4); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, namespace$4 + '.' + getId$9(props)); } var connectRange = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), min: propTypes.number, max: propTypes.number, precision: propTypes.number, header: propTypes.node, footer: propTypes.node }, defaultProps: { precision: 0 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var hasFacet = results && results.getFacetByName(attribute); var stats = hasFacet ? results.getFacetStats(attribute) || {} : {}; var facetValues = hasFacet ? results.getFacetValues(attribute) : []; var count = facetValues.map(function (v) { return { value: v.name, count: v.count }; }); var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var currentRefinement = getCurrentRefinement$7(props, searchState, this._currentRange, this.context); return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange), count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), min = _getCurrentRefinement.min, max = _getCurrentRefinement.max; params = params.addDisjunctiveFacet(attribute); if (min !== undefined) { params = params.addNumericRefinement(attribute, '>=', min); } if (max !== undefined) { params = params.addNumericRefinement(attribute, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var _currentRange = this._currentRange, minRange = _currentRange.min, maxRange = _currentRange.max; var _getCurrentRefinement2 = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), minValue = _getCurrentRefinement2.min, maxValue = _getCurrentRefinement2.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? minValue + ' <= ' : '', props.attribute, hasMax ? ' <= ' + maxValue : '']; items.push({ label: fragments.join(''), attribute: props.attribute, value: function value(nextState) { return _refine$6(props, nextState, {}, _this._currentRange, _this.context); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$9(props), index: getIndex(this.context), items: items }; } }); function _defineProperty$d(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; } var namespace$5 = 'refinementList'; function getId$a(props) { return props.attribute; } function getCurrentRefinement$8(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$5 + '.' + getId$a(props), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue$3(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$8(props, searchState, context); var isAnewValue = currentRefinement.indexOf(name) === -1; var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates : currentRefinement.filter(function (selectedValue) { return selectedValue !== name; }); // cannot use .splice(), it mutates return nextRefinement; } function getLimit$1(_ref) { var showMore = _ref.showMore, limit = _ref.limit, showMoreLimit = _ref.showMoreLimit; return showMore ? showMoreLimit : limit; } function _refine$7(props, searchState, nextRefinement, context) { var id = getId$a(props); // Setting the value to an empty string ensures that it is persisted in // the URL as an empty value. // This is necessary in the case where `defaultRefinement` contains one // item and we try to deselect it. `nextSelected` would be an empty array, // which would not be persisted to the URL. // {foo: ['bar']} => "foo[0]=bar" // {foo: []} => "" var nextValue = _defineProperty$d({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, namespace$5 + '.' + getId$a(props)); } /** * connectRefinementList connector provides the logic to build a widget that will * give the user the ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [searchable=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of displayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), searchable: propTypes.bool, transformItems: propTypes.func }, defaultProps: { operator: 'or', showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$8(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$8(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$8(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$a(props); var context = this.context; return { id: id, index: getIndex(this.context), items: getCurrentRefinement$8(props, searchState, context).length > 0 ? [{ attribute: props.attribute, label: props.attribute + ': ', currentRefinement: getCurrentRefinement$8(props, searchState, context), value: function value(nextState) { return _refine$7(props, nextState, [], context); }, items: getCurrentRefinement$8(props, searchState, context).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$8(props, nextState, context).filter(function (other) { return other !== item; }); return _refine$7(props, searchState, nextSelectedItems, context); } }; }) }] : [] }; } }); /** * connectScrollTo connector provides the logic to build a widget that will * let the page scroll to a certain point. * @name connectScrollTo * @kind connector * @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget. * @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo * @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default) */ var connectScrollTo = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); if (!this._prevSearchState) { this._prevSearchState = {}; } /* Get the subpart of the state that interest us*/ if (hasMultipleIndex(this.context)) { var index = getIndex(this.context); searchState = searchState.indices ? searchState.indices[index] : {}; } /* if there is a change in the app that has been triggered by another element than "props.scrollOn (id) or the Configure widget, we need to keep track of the search state to know if there's a change in the app that was not triggered by the props.scrollOn (id) or the Configure widget. This is useful when using ScrollTo in combination of Pagination. As pagination can be change by every widget, we want to scroll only if it cames from the pagination widget itself. We also remove the configure key from the search state to do this comparaison because for now configure values are not present in the search state before a first refinement has been made and will false the results. See: https://github.com/algolia/react-instantsearch/issues/164 */ var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); function _defineProperty$e(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 getId$b() { return 'query'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$b(props); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine$8(props, searchState, nextRefinement, context) { var id = getId$b(); var nextValue = _defineProperty$e({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$6(props, searchState, context) { return cleanUpValue(searchState, context, getId$b()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query * @name connectSearchBox * @kind connector * @providedPropType {function} refine - a function to change the current query * @providedPropType {string} currentRefinement - the current query used * @providedPropType {boolean} isSearchStalled - a flag that indicates if InstantSearch has detected that searches are stalled */ var connectSearchBox = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$9(props, searchState, this.context), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$9(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$b(props); var currentRefinement = getCurrentRefinement$9(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine$8(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var _extends$9 = 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; }; function _defineProperty$f(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 getId$c() { return 'sortBy'; } function getCurrentRefinement$a(props, searchState, context) { var id = getId$c(props); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * The connectSortBy connector provides the logic to build a widget that will * display a list of indices. This allows a user to change how the hits are being sorted. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectSortBy = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$a(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends$9({}, item, { isRefined: true }) : _extends$9({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$c(); var nextValue = _defineProperty$f({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$c()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$a(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$c() }; } }); /** * The `connectStateResults` connector provides a way to access the `searchState` and the `searchResults` * of InstantSearch. * For instance this connector allows you to create results/noResults or query/noQuery pages. * @name connectStateResults * @kind connector * @providedPropType {object} searchState - The search state of the instant search component. <br/><br/> See: [Search state structure](https://community.algolia.com/react-instantsearch/guide/Search_state.html) * @providedPropType {object} searchResults - The search results. <br/><br/> In case of multiple indices: if used under `<Index>`, results will be those of the corresponding index otherwise it'll be those of the root index See: [Search results structure](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults) * @providedPropType {object} allSearchResults - In case of multiple indices you can retrieve all the results * @providedPropType {string} error - If the search failed, the error will be logged here. * @providedPropType {boolean} searching - If there is a search in progress. * @providedPropType {boolean} isSearchStalled - Flag that indicates if React InstantSearch has detected that searches are stalled. * @providedPropType {boolean} searchingForFacetValues - If there is a search in a list in progress. * @providedPropType {object} props - component props. * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits, connectStateResults } from 'react-instantsearch-dom'; * * const Content = connectStateResults(({ searchState, searchResults }) => { * const hasResults = searchResults && searchResults.nbHits !== 0; * * return ( * <div> * <div hidden={!hasResults}> * <Hits /> * </div> * <div hidden={hasResults}> * <div>No results has been found for {searchState.query}</div> * </div> * </div> * ); * }); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * <Content /> * </InstantSearch> * ); */ var connectStateResults = createConnector({ displayName: 'AlgoliaStateResults', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); return { searchState: searchState, searchResults: results, allSearchResults: searchResults.results, searching: searchResults.searching, isSearchStalled: searchResults.isSearchStalled, error: searchResults.error, searchingForFacetValues: searchResults.searchingForFacetValues, props: props }; } }); /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ var connectStats = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function _defineProperty$g(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 getId$d(props) { return props.attribute; } var namespace$6 = 'toggle'; function getCurrentRefinement$b(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$6 + '.' + getId$d(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } function _refine$9(props, searchState, nextRefinement, context) { var id = getId$d(props); var nextValue = _defineProperty$g({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function _cleanUp$7(props, searchState, context) { return cleanUpValue(searchState, context, namespace$6 + '.' + getId$d(props)); } /** * connectToggleRefinement connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. * @name connectToggleRefinement * @kind connector * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attribute`. * @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise */ var connectToggleRefinement = createConnector({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string, filter: propTypes.func, attribute: propTypes.string, value: propTypes.any, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$b(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$9(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$7(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$b(props, searchState, this.context); if (checked) { if (attribute) { searchParameters = searchParameters.addFacet(attribute).addFacetRefinement(attribute, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$d(props); var checked = getCurrentRefinement$b(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$9(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); // Core exports.connectAutoComplete = connectAutoComplete; exports.connectBreadcrumb = connectBreadcrumb; exports.connectConfigure = connectConfigure; exports.connectCurrentRefinements = connectCurrentRefinements; exports.connectHierarchicalMenu = connectHierarchicalMenu; exports.connectHighlight = connectHighlight; exports.connectHits = connectHits; exports.connectHitsPerPage = connectHitsPerPage; exports.connectInfiniteHits = connectInfiniteHits; exports.connectMenu = connectMenu; exports.connectNumericMenu = connectNumericMenu; exports.connectPagination = connectPagination; exports.connectPoweredBy = connectPoweredBy; exports.connectRange = connectRange; exports.connectRefinementList = connectRefinementList; exports.connectScrollTo = connectScrollTo; exports.connectSearchBox = connectSearchBox; exports.connectSortBy = connectSortBy; exports.connectStateResults = connectStateResults; exports.connectStats = connectStats; exports.connectToggleRefinement = connectToggleRefinement; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Connectors.js.map
ajax/libs/react-native-web/0.11.7/exports/ImageBackground/index.js
cdnjs/cdnjs
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import ensureComponentIsNative from '../../modules/ensureComponentIsNative'; import Image from '../Image'; import StyleSheet from '../StyleSheet'; import View from '../View'; import ViewPropTypes from '../ViewPropTypes'; import React, { Component } from 'react'; var emptyObject = {}; /** * Very simple drop-in replacement for <Image> which supports nesting views. */ var ImageBackground = /*#__PURE__*/ function (_Component) { _inheritsLoose(ImageBackground, _Component); function ImageBackground() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _Component.call.apply(_Component, [this].concat(args)) || this; _this._viewRef = null; _this._captureRef = function (ref) { _this._viewRef = ref; }; return _this; } var _proto = ImageBackground.prototype; _proto.setNativeProps = function setNativeProps(props) { // Work-around flow var viewRef = this._viewRef; if (viewRef) { ensureComponentIsNative(viewRef); viewRef.setNativeProps(props); } }; _proto.render = function render() { var _this$props = this.props, children = _this$props.children, style = _this$props.style, imageStyle = _this$props.imageStyle, imageRef = _this$props.imageRef, props = _objectWithoutPropertiesLoose(_this$props, ["children", "style", "imageStyle", "imageRef"]); return React.createElement(View, { ref: this._captureRef, style: style }, React.createElement(Image, _extends({}, props, { ref: imageRef, style: [StyleSheet.absoluteFill, { // Temporary Workaround: // Current (imperfect yet) implementation of <Image> overwrites width and height styles // (which is not quite correct), and these styles conflict with explicitly set styles // of <ImageBackground> and with our internal layout model here. // So, we have to proxy/reapply these styles explicitly for actual <Image> component. // This workaround should be removed after implementing proper support of // intrinsic content size of the <Image>. width: style.width, height: style.height, zIndex: -1 }, imageStyle] })), children); }; return ImageBackground; }(Component); ImageBackground.defaultProps = { style: emptyObject }; ImageBackground.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, Image.propTypes, { imageStyle: Image.propTypes.style, style: ViewPropTypes.style }) : {}; export default ImageBackground;
ajax/libs/material-ui/5.0.0-alpha.16/legacy/styles/useTheme.js
cdnjs/cdnjs
import { useTheme as useThemeWithoutDefault } from '@material-ui/styles'; import React from 'react'; import defaultTheme from './defaultTheme'; export default function useTheme() { var theme = useThemeWithoutDefault() || defaultTheme; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue(theme); } return theme; }
ajax/libs/material-ui/4.9.2/esm/CardActions/CardActions.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export var styles = { /* Styles applied to the root element. */ root: { display: 'flex', alignItems: 'center', padding: 8 }, /* Styles applied to the root element if `disableSpacing={false}`. */ spacing: { '& > :not(:first-child)': { marginLeft: 8 } } }; var CardActions = React.forwardRef(function CardActions(props, ref) { var _props$disableSpacing = props.disableSpacing, disableSpacing = _props$disableSpacing === void 0 ? false : _props$disableSpacing, classes = props.classes, className = props.className, other = _objectWithoutProperties(props, ["disableSpacing", "classes", "className"]); return React.createElement("div", _extends({ className: clsx(classes.root, className, !disableSpacing && classes.spacing), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? CardActions.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, the actions do not have additional margin. */ disableSpacing: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiCardActions' })(CardActions);
ajax/libs/react-native-web/0.11.2/exports/Switch/index.js
cdnjs/cdnjs
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import applyNativeMethods from '../../modules/applyNativeMethods'; import ColorPropType from '../ColorPropType'; import createElement from '../createElement'; import multiplyStyleLengthValue from '../../modules/multiplyStyleLengthValue'; import StyleSheet from '../StyleSheet'; import UIManager from '../UIManager'; import View from '../View'; import ViewPropTypes from '../ViewPropTypes'; import React, { Component } from 'react'; import { bool, func } from 'prop-types'; var emptyObject = {}; var thumbDefaultBoxShadow = '0px 1px 3px rgba(0,0,0,0.5)'; var thumbFocusedBoxShadow = thumbDefaultBoxShadow + ", 0 0 0 10px rgba(0,0,0,0.1)"; var Switch = /*#__PURE__*/ function (_Component) { _inheritsLoose(Switch, _Component); function Switch() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _Component.call.apply(_Component, [this].concat(args)) || this; _this._handleChange = function (event) { var onValueChange = _this.props.onValueChange; onValueChange && onValueChange(event.nativeEvent.target.checked); }; _this._handleFocusState = function (event) { var isFocused = event.nativeEvent.type === 'focus'; var boxShadow = isFocused ? thumbFocusedBoxShadow : thumbDefaultBoxShadow; if (_this._thumbElement) { _this._thumbElement.setNativeProps({ style: { boxShadow: boxShadow } }); } }; _this._setCheckboxRef = function (element) { _this._checkboxElement = element; }; _this._setThumbRef = function (element) { _this._thumbElement = element; }; return _this; } var _proto = Switch.prototype; _proto.blur = function blur() { UIManager.blur(this._checkboxElement); }; _proto.focus = function focus() { UIManager.focus(this._checkboxElement); }; _proto.render = function render() { var _this$props = this.props, accessibilityLabel = _this$props.accessibilityLabel, activeThumbColor = _this$props.activeThumbColor, activeTrackColor = _this$props.activeTrackColor, disabled = _this$props.disabled, onValueChange = _this$props.onValueChange, style = _this$props.style, thumbColor = _this$props.thumbColor, trackColor = _this$props.trackColor, value = _this$props.value, onTintColor = _this$props.onTintColor, thumbTintColor = _this$props.thumbTintColor, tintColor = _this$props.tintColor, other = _objectWithoutPropertiesLoose(_this$props, ["accessibilityLabel", "activeThumbColor", "activeTrackColor", "disabled", "onValueChange", "style", "thumbColor", "trackColor", "value", "onTintColor", "thumbTintColor", "tintColor"]); var _StyleSheet$flatten = StyleSheet.flatten(style), styleHeight = _StyleSheet$flatten.height, styleWidth = _StyleSheet$flatten.width; var height = styleHeight || 20; var minWidth = multiplyStyleLengthValue(height, 2); var width = styleWidth > minWidth ? styleWidth : minWidth; var trackBorderRadius = multiplyStyleLengthValue(height, 0.5); var trackCurrentColor = value ? onTintColor || activeTrackColor : tintColor || trackColor; var thumbCurrentColor = value ? activeThumbColor : thumbTintColor || thumbColor; var thumbHeight = height; var thumbWidth = thumbHeight; var rootStyle = [styles.root, style, { height: height, width: width }, disabled && styles.cursorDefault]; var trackStyle = [styles.track, { backgroundColor: trackCurrentColor, borderRadius: trackBorderRadius }, disabled && styles.disabledTrack]; var thumbStyle = [styles.thumb, { backgroundColor: thumbCurrentColor, height: thumbHeight, width: thumbWidth }, disabled && styles.disabledThumb]; var nativeControl = createElement('input', { accessibilityLabel: accessibilityLabel, checked: value, disabled: disabled, onBlur: this._handleFocusState, onChange: this._handleChange, onFocus: this._handleFocusState, ref: this._setCheckboxRef, style: [styles.nativeControl, styles.cursorInherit], type: 'checkbox' }); return React.createElement(View, _extends({}, other, { style: rootStyle }), React.createElement(View, { style: trackStyle }), React.createElement(View, { ref: this._setThumbRef, style: [thumbStyle, value && styles.thumbOn, { marginStart: value ? multiplyStyleLengthValue(thumbWidth, -1) : 0 }] }), nativeControl); }; return Switch; }(Component); Switch.displayName = 'Switch'; Switch.defaultProps = { activeThumbColor: '#009688', activeTrackColor: '#A3D3CF', disabled: false, style: emptyObject, thumbColor: '#FAFAFA', trackColor: '#939393', value: false }; Switch.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, ViewPropTypes, { activeThumbColor: ColorPropType, activeTrackColor: ColorPropType, disabled: bool, onValueChange: func, thumbColor: ColorPropType, trackColor: ColorPropType, value: bool, /* eslint-disable react/sort-prop-types */ // Equivalent of 'activeTrackColor' onTintColor: ColorPropType, // Equivalent of 'thumbColor' thumbTintColor: ColorPropType, // Equivalent of 'trackColor' tintColor: ColorPropType }) : {}; var styles = StyleSheet.create({ root: { cursor: 'pointer', userSelect: 'none' }, cursorDefault: { cursor: 'default' }, cursorInherit: { cursor: 'inherit' }, track: _objectSpread({}, StyleSheet.absoluteFillObject, { height: '70%', margin: 'auto', transitionDuration: '0.1s', width: '100%' }), disabledTrack: { backgroundColor: '#D5D5D5' }, thumb: { alignSelf: 'flex-start', borderRadius: '100%', boxShadow: thumbDefaultBoxShadow, start: '0%', transform: [{ translateZ: 0 }], transitionDuration: '0.1s' }, thumbOn: { start: '100%' }, disabledThumb: { backgroundColor: '#BDBDBD' }, nativeControl: _objectSpread({}, StyleSheet.absoluteFillObject, { height: '100%', margin: 0, opacity: 0, padding: 0, width: '100%' }) }); export default applyNativeMethods(Switch);
ajax/libs/primereact/7.0.0-rc.2/dialog/dialog.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { UniqueComponentId, DomHandler, ZIndexUtils, Ripple, classNames, ObjectUtils, CSSTransition, Portal } from 'primereact/core'; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Dialog = /*#__PURE__*/function (_Component) { _inherits(Dialog, _Component); var _super = _createSuper(Dialog); function Dialog(props) { var _this; _classCallCheck(this, Dialog); _this = _super.call(this, props); _this.state = { id: props.id, maskVisible: props.visible, visible: false }; if (!_this.props.onMaximize) { _this.state.maximized = props.maximized; } _this.onClose = _this.onClose.bind(_assertThisInitialized(_this)); _this.toggleMaximize = _this.toggleMaximize.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onResizeStart = _this.onResizeStart.bind(_assertThisInitialized(_this)); _this.onMaskClick = _this.onMaskClick.bind(_assertThisInitialized(_this)); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); _this.attributeSelector = UniqueComponentId(); _this.dialogRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Dialog, [{ key: "onClose", value: function onClose(event) { this.props.onHide(); event.preventDefault(); } }, { key: "focus", value: function focus() { var activeElement = document.activeElement; var isActiveElementInDialog = activeElement && this.dialogRef && this.dialogRef.current.contains(activeElement); if (!isActiveElementInDialog && this.props.closable && this.props.showHeader) { this.closeElement.focus(); } } }, { key: "onMaskClick", value: function onMaskClick(event) { if (this.props.dismissableMask && this.props.modal && this.mask === event.target) { this.onClose(event); } this.props.onMaskClick && this.props.onMaskClick(event); } }, { key: "toggleMaximize", value: function toggleMaximize(event) { var maximized = !this.maximized; if (this.props.onMaximize) { this.props.onMaximize({ originalEvent: event, maximized: maximized }); } else { this.setState({ maximized: maximized }, this.changeScrollOnMaximizable); } event.preventDefault(); } }, { key: "onDragStart", value: function onDragStart(event) { if (DomHandler.hasClass(event.target, 'p-dialog-header-icon') || DomHandler.hasClass(event.target.parentElement, 'p-dialog-header-icon')) { return; } if (this.props.draggable) { this.dragging = true; this.lastPageX = event.pageX; this.lastPageY = event.pageY; this.dialogEl.style.margin = '0'; DomHandler.addClass(document.body, 'p-unselectable-text'); if (this.props.onDragStart) { this.props.onDragStart(event); } } } }, { key: "onDrag", value: function onDrag(event) { if (this.dragging) { var width = DomHandler.getOuterWidth(this.dialogEl); var height = DomHandler.getOuterHeight(this.dialogEl); var deltaX = event.pageX - this.lastPageX; var deltaY = event.pageY - this.lastPageY; var offset = this.dialogEl.getBoundingClientRect(); var leftPos = offset.left + deltaX; var topPos = offset.top + deltaY; var viewport = DomHandler.getViewport(); this.dialogEl.style.position = 'fixed'; if (this.props.keepInViewport) { if (leftPos >= this.props.minX && leftPos + width < viewport.width) { this.lastPageX = event.pageX; this.dialogEl.style.left = leftPos + 'px'; } if (topPos >= this.props.minY && topPos + height < viewport.height) { this.lastPageY = event.pageY; this.dialogEl.style.top = topPos + 'px'; } } else { this.lastPageX = event.pageX; this.dialogEl.style.left = leftPos + 'px'; this.lastPageY = event.pageY; this.dialogEl.style.top = topPos + 'px'; } if (this.props.onDrag) { this.props.onDrag(event); } } } }, { key: "onDragEnd", value: function onDragEnd(event) { if (this.dragging) { this.dragging = false; DomHandler.removeClass(document.body, 'p-unselectable-text'); if (this.props.onDragEnd) { this.props.onDragEnd(event); } } } }, { key: "onResizeStart", value: function onResizeStart(event) { if (this.props.resizable) { this.resizing = true; this.lastPageX = event.pageX; this.lastPageY = event.pageY; DomHandler.addClass(document.body, 'p-unselectable-text'); if (this.props.onResizeStart) { this.props.onResizeStart(event); } } } }, { key: "convertToPx", value: function convertToPx(value, property, viewport) { !viewport && (viewport = DomHandler.getViewport()); var val = parseInt(value); if (/^(\d+|(\.\d+))(\.\d+)?%$/.test(value)) { return val * (viewport[property] / 100); } return val; } }, { key: "onResize", value: function onResize(event) { if (this.resizing) { var deltaX = event.pageX - this.lastPageX; var deltaY = event.pageY - this.lastPageY; var width = DomHandler.getOuterWidth(this.dialogEl); var height = DomHandler.getOuterHeight(this.dialogEl); var offset = this.dialogEl.getBoundingClientRect(); var viewport = DomHandler.getViewport(); var newWidth = width + deltaX; var newHeight = height + deltaY; var minWidth = this.convertToPx(this.dialogEl.style.minWidth, 'width', viewport); var minHeight = this.convertToPx(this.dialogEl.style.minHeight, 'height', viewport); var hasBeenDragged = !parseInt(this.dialogEl.style.top) || !parseInt(this.dialogEl.style.left); if (hasBeenDragged) { newWidth += deltaX; newHeight += deltaY; } if ((!minWidth || newWidth > minWidth) && offset.left + newWidth < viewport.width) { this.dialogEl.style.width = newWidth + 'px'; } if ((!minHeight || newHeight > minHeight) && offset.top + newHeight < viewport.height) { this.dialogEl.style.height = newHeight + 'px'; } this.lastPageX = event.pageX; this.lastPageY = event.pageY; if (this.props.onResize) { this.props.onResize(event); } } } }, { key: "onResizeEnd", value: function onResizeEnd(event) { if (this.resizing) { this.resizing = false; DomHandler.removeClass(document.body, 'p-unselectable-text'); if (this.props.onResizeEnd) { this.props.onResizeEnd(event); } } } }, { key: "resetPosition", value: function resetPosition() { this.dialogEl.style.position = ''; this.dialogEl.style.left = ''; this.dialogEl.style.top = ''; this.dialogEl.style.margin = ''; } }, { key: "getPositionClass", value: function getPositionClass() { var _this2 = this; var positions = ['center', 'left', 'right', 'top', 'top-left', 'top-right', 'bottom', 'bottom-left', 'bottom-right']; var pos = positions.find(function (item) { return item === _this2.props.position || item.replace('-', '') === _this2.props.position; }); return pos ? "p-dialog-".concat(pos) : ''; } }, { key: "maximized", get: function get() { return this.props.onMaximize ? this.props.maximized : this.state.maximized; } }, { key: "dialogEl", get: function get() { return this.dialogRef.current; } }, { key: "onEnter", value: function onEnter() { this.dialogEl.setAttribute(this.attributeSelector, ''); } }, { key: "onEntered", value: function onEntered() { if (this.props.onShow) { this.props.onShow(); } if (this.props.focusOnShow) { this.focus(); } this.enableDocumentSettings(); } }, { key: "onExiting", value: function onExiting() { if (this.props.modal) { DomHandler.addClass(this.mask, 'p-component-overlay-leave'); } } }, { key: "onExited", value: function onExited() { this.dragging = false; ZIndexUtils.clear(this.mask); this.setState({ maskVisible: false }); this.disableDocumentSettings(); } }, { key: "enableDocumentSettings", value: function enableDocumentSettings() { this.bindGlobalListeners(); if (this.props.blockScroll || this.props.maximizable && this.maximized) { DomHandler.addClass(document.body, 'p-overflow-hidden'); } } }, { key: "disableDocumentSettings", value: function disableDocumentSettings() { this.unbindGlobalListeners(); if (this.props.modal) { var hasBlockScroll = document.primeDialogParams && document.primeDialogParams.some(function (param) { return param.hasBlockScroll; }); if (!hasBlockScroll) { DomHandler.removeClass(document.body, 'p-overflow-hidden'); } } else if (this.props.blockScroll || this.props.maximizable && this.maximized) { DomHandler.removeClass(document.body, 'p-overflow-hidden'); } } }, { key: "bindGlobalListeners", value: function bindGlobalListeners() { if (this.props.draggable) { this.bindDocumentDragListener(); } if (this.props.resizable) { this.bindDocumentResizeListeners(); } if (this.props.closeOnEscape && this.props.closable) { this.bindDocumentKeyDownListener(); } } }, { key: "unbindGlobalListeners", value: function unbindGlobalListeners() { this.unbindDocumentDragListener(); this.unbindDocumentResizeListeners(); this.unbindDocumentKeyDownListener(); } }, { key: "bindDocumentDragListener", value: function bindDocumentDragListener() { this.documentDragListener = this.onDrag.bind(this); this.documentDragEndListener = this.onDragEnd.bind(this); window.document.addEventListener('mousemove', this.documentDragListener); window.document.addEventListener('mouseup', this.documentDragEndListener); } }, { key: "unbindDocumentDragListener", value: function unbindDocumentDragListener() { if (this.documentDragListener && this.documentDragEndListener) { window.document.removeEventListener('mousemove', this.documentDragListener); window.document.removeEventListener('mouseup', this.documentDragEndListener); this.documentDragListener = null; this.documentDragEndListener = null; } } }, { key: "bindDocumentResizeListeners", value: function bindDocumentResizeListeners() { this.documentResizeListener = this.onResize.bind(this); this.documentResizeEndListener = this.onResizeEnd.bind(this); window.document.addEventListener('mousemove', this.documentResizeListener); window.document.addEventListener('mouseup', this.documentResizeEndListener); } }, { key: "unbindDocumentResizeListeners", value: function unbindDocumentResizeListeners() { if (this.documentResizeListener && this.documentResizeEndListener) { window.document.removeEventListener('mousemove', this.documentResizeListener); window.document.removeEventListener('mouseup', this.documentResizeEndListener); this.documentResizeListener = null; this.documentResizeEndListener = null; } } }, { key: "bindDocumentKeyDownListener", value: function bindDocumentKeyDownListener() { var _this3 = this; this.documentKeyDownListener = function (event) { var currentTarget = event.currentTarget; if (currentTarget && currentTarget.primeDialogParams) { var params = currentTarget.primeDialogParams; var paramLength = params.length; var dialogId = params[paramLength - 1] ? params[paramLength - 1].id : undefined; if (dialogId === _this3.state.id) { var dialog = document.getElementById(dialogId); if (event.which === 27) { _this3.onClose(event); event.stopImmediatePropagation(); params.splice(paramLength - 1, 1); } else if (event.which === 9) { event.preventDefault(); var focusableElements = DomHandler.getFocusableElements(dialog); if (focusableElements && focusableElements.length > 0) { if (!document.activeElement) { focusableElements[0].focus(); } else { var focusedIndex = focusableElements.indexOf(document.activeElement); if (event.shiftKey) { if (focusedIndex === -1 || focusedIndex === 0) focusableElements[focusableElements.length - 1].focus();else focusableElements[focusedIndex - 1].focus(); } else { if (focusedIndex === -1 || focusedIndex === focusableElements.length - 1) focusableElements[0].focus();else focusableElements[focusedIndex + 1].focus(); } } } } } } }; var newParam = { id: this.state.id, hasBlockScroll: this.props.blockScroll }; document.primeDialogParams = document.primeDialogParams ? [].concat(_toConsumableArray(document.primeDialogParams), [newParam]) : [newParam]; document.addEventListener('keydown', this.documentKeyDownListener); } }, { key: "unbindDocumentKeyDownListener", value: function unbindDocumentKeyDownListener() { var _this4 = this; if (this.documentKeyDownListener) { document.removeEventListener('keydown', this.documentKeyDownListener); document.primeDialogParams = document.primeDialogParams && document.primeDialogParams.filter(function (param) { return param.id !== _this4.state.id; }); this.documentKeyDownListener = null; } } }, { key: "createStyle", value: function createStyle() { if (!this.styleElement) { this.styleElement = document.createElement('style'); document.head.appendChild(this.styleElement); var innerHTML = ''; for (var breakpoint in this.props.breakpoints) { innerHTML += "\n @media screen and (max-width: ".concat(breakpoint, ") {\n .p-dialog[").concat(this.attributeSelector, "] {\n width: ").concat(this.props.breakpoints[breakpoint], " !important;\n }\n }\n "); } this.styleElement.innerHTML = innerHTML; } } }, { key: "componentDidMount", value: function componentDidMount() { var _this5 = this; if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } if (this.props.visible) { this.setState({ visible: true }, function () { ZIndexUtils.set('modal', _this5.mask, _this5.props.baseZIndex); }); } if (this.props.breakpoints) { this.createStyle(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var _this6 = this; if (this.props.visible && !this.state.maskVisible) { this.setState({ maskVisible: true }, function () { ZIndexUtils.set('modal', _this6.mask, _this6.props.baseZIndex); }); } if (this.props.visible !== this.state.visible && this.state.maskVisible) { this.setState({ visible: this.props.visible }); } if (prevProps.maximized !== this.props.maximized && this.props.onMaximize) { this.changeScrollOnMaximizable(); } } }, { key: "changeScrollOnMaximizable", value: function changeScrollOnMaximizable() { if (!this.props.blockScroll) { var funcName = this.maximized ? 'addClass' : 'removeClass'; DomHandler[funcName](document.body, 'p-overflow-hidden'); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.disableDocumentSettings(); if (this.styleElement) { document.head.removeChild(this.styleElement); this.styleElement = null; } ZIndexUtils.clear(this.mask); } }, { key: "renderCloseIcon", value: function renderCloseIcon() { var _this7 = this; if (this.props.closable) { return /*#__PURE__*/React.createElement("button", { ref: function ref(el) { return _this7.closeElement = el; }, type: "button", className: "p-dialog-header-icon p-dialog-header-close p-link", "aria-label": this.props.ariaCloseIconLabel, onClick: this.onClose }, /*#__PURE__*/React.createElement("span", { className: "p-dialog-header-close-icon pi pi-times" }), /*#__PURE__*/React.createElement(Ripple, null)); } return null; } }, { key: "renderMaximizeIcon", value: function renderMaximizeIcon() { var iconClassName = classNames('p-dialog-header-maximize-icon pi', { 'pi-window-maximize': !this.maximized, 'pi-window-minimize': this.maximized }); if (this.props.maximizable) { return /*#__PURE__*/React.createElement("button", { type: "button", className: "p-dialog-header-icon p-dialog-header-maximize p-link", onClick: this.toggleMaximize }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } return null; } }, { key: "renderHeader", value: function renderHeader() { var _this8 = this; if (this.props.showHeader) { var closeIcon = this.renderCloseIcon(); var maximizeIcon = this.renderMaximizeIcon(); var icons = ObjectUtils.getJSXElement(this.props.icons, this.props); var header = ObjectUtils.getJSXElement(this.props.header, this.props); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this8.headerEl = el; }, className: "p-dialog-header", onMouseDown: this.onDragStart }, /*#__PURE__*/React.createElement("div", { id: this.state.id + '_header', className: "p-dialog-title" }, header), /*#__PURE__*/React.createElement("div", { className: "p-dialog-header-icons" }, icons, maximizeIcon, closeIcon)); } return null; } }, { key: "renderContent", value: function renderContent() { var _this9 = this; var contentClassName = classNames('p-dialog-content', this.props.contentClassName); return /*#__PURE__*/React.createElement("div", { id: this.state.id + '_content', ref: function ref(el) { return _this9.contentEl = el; }, className: contentClassName, style: this.props.contentStyle }, this.props.children); } }, { key: "renderFooter", value: function renderFooter() { var _this10 = this; var footer = ObjectUtils.getJSXElement(this.props.footer, this.props); return footer && /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this10.footerElement = el; }, className: "p-dialog-footer" }, footer); } }, { key: "renderResizer", value: function renderResizer() { if (this.props.resizable) { return /*#__PURE__*/React.createElement("div", { className: "p-resizable-handle", style: { zIndex: 90 }, onMouseDown: this.onResizeStart }); } return null; } }, { key: "renderElement", value: function renderElement() { var _this11 = this; var className = classNames('p-dialog p-component', this.props.className, { 'p-dialog-rtl': this.props.rtl, 'p-dialog-maximized': this.maximized }); var maskClassName = classNames('p-dialog-mask', { 'p-component-overlay p-component-overlay-enter': this.props.modal, 'p-dialog-visible': this.state.maskVisible, 'p-dialog-draggable': this.props.draggable, 'p-dialog-resizable': this.props.resizable }, this.props.maskClassName, this.getPositionClass()); var header = this.renderHeader(); var content = this.renderContent(); var footer = this.renderFooter(); var resizer = this.renderResizer(); var transitionTimeout = { enter: this.props.position === 'center' ? 150 : 300, exit: this.props.position === 'center' ? 150 : 300 }; return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this11.mask = el; }, className: maskClassName, onClick: this.onMaskClick }, /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.dialogRef, classNames: "p-dialog", timeout: transitionTimeout, in: this.state.visible, options: this.props.transitionOptions, unmountOnExit: true, onEnter: this.onEnter, onEntered: this.onEntered, onExiting: this.onExiting, onExited: this.onExited }, /*#__PURE__*/React.createElement("div", { ref: this.dialogRef, id: this.state.id, className: className, style: this.props.style, onClick: this.props.onClick, role: "dialog", "aria-labelledby": this.state.id + '_header', "aria-describedby": this.state.id + '_content', "aria-modal": this.props.modal }, header, content, footer, resizer))); } }, { key: "render", value: function render() { if (this.state.maskVisible) { var element = this.renderElement(); return /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: this.props.appendTo, visible: true }); } return null; } }]); return Dialog; }(Component); _defineProperty(Dialog, "defaultProps", { id: null, header: null, footer: null, visible: false, position: 'center', draggable: true, resizable: true, modal: true, onHide: null, onShow: null, contentStyle: null, contentClassName: null, closeOnEscape: true, dismissableMask: false, rtl: false, closable: true, style: null, className: null, maskClassName: null, showHeader: true, appendTo: null, baseZIndex: 0, maximizable: false, blockScroll: false, icons: null, ariaCloseIconLabel: 'Close', focusOnShow: true, minX: 0, minY: 0, keepInViewport: true, maximized: false, breakpoints: null, transitionOptions: null, onMaximize: null, onDragStart: null, onDrag: null, onDragEnd: null, onResizeStart: null, onResize: null, onResizeEnd: null, onClick: null, onMaskClick: null }); export { Dialog };
ajax/libs/boardgame-io/0.43.1/boardgameio.es.js
cdnjs/cdnjs
import { nanoid } from 'nanoid'; import { applyMiddleware, compose, createStore } from 'redux'; import produce from 'immer'; import { stringify, parse } from 'flatted'; import React from 'react'; import PropTypes from 'prop-types'; import ioNamespace__default from 'socket.io-client'; function noop() { } const identity = x => x; function assign(tar, src) { // @ts-ignore for (const k in src) tar[k] = src[k]; return tar; } function run(fn) { return fn(); } function blank_object() { return Object.create(null); } function run_all(fns) { fns.forEach(run); } function is_function(thing) { return typeof thing === 'function'; } function safe_not_equal(a, b) { return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); } function subscribe(store, ...callbacks) { if (store == null) { return noop; } const unsub = store.subscribe(...callbacks); return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; } function component_subscribe(component, store, callback) { component.$$.on_destroy.push(subscribe(store, callback)); } function create_slot(definition, ctx, $$scope, fn) { if (definition) { const slot_ctx = get_slot_context(definition, ctx, $$scope, fn); return definition[0](slot_ctx); } } function get_slot_context(definition, ctx, $$scope, fn) { return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx; } function get_slot_changes(definition, $$scope, dirty, fn) { if (definition[2] && fn) { const lets = definition[2](fn(dirty)); if ($$scope.dirty === undefined) { return lets; } if (typeof lets === 'object') { const merged = []; const len = Math.max($$scope.dirty.length, lets.length); for (let i = 0; i < len; i += 1) { merged[i] = $$scope.dirty[i] | lets[i]; } return merged; } return $$scope.dirty | lets; } return $$scope.dirty; } function update_slot(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) { const slot_changes = get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn); if (slot_changes) { const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn); slot.p(slot_context, slot_changes); } } function exclude_internal_props(props) { const result = {}; for (const k in props) if (k[0] !== '$') result[k] = props[k]; return result; } function null_to_empty(value) { return value == null ? '' : value; } const is_client = typeof window !== 'undefined'; let now = is_client ? () => window.performance.now() : () => Date.now(); let raf = is_client ? cb => requestAnimationFrame(cb) : noop; const tasks = new Set(); function run_tasks(now) { tasks.forEach(task => { if (!task.c(now)) { tasks.delete(task); task.f(); } }); if (tasks.size !== 0) raf(run_tasks); } /** * Creates a new task that runs on each raf frame * until it returns a falsy value or is aborted */ function loop(callback) { let task; if (tasks.size === 0) raf(run_tasks); return { promise: new Promise(fulfill => { tasks.add(task = { c: callback, f: fulfill }); }), abort() { tasks.delete(task); } }; } function append(target, node) { target.appendChild(node); } function insert(target, node, anchor) { target.insertBefore(node, anchor || null); } function detach(node) { node.parentNode.removeChild(node); } function destroy_each(iterations, detaching) { for (let i = 0; i < iterations.length; i += 1) { if (iterations[i]) iterations[i].d(detaching); } } function element(name) { return document.createElement(name); } function svg_element(name) { return document.createElementNS('http://www.w3.org/2000/svg', name); } function text(data) { return document.createTextNode(data); } function space() { return text(' '); } function empty() { return text(''); } function listen(node, event, handler, options) { node.addEventListener(event, handler, options); return () => node.removeEventListener(event, handler, options); } function stop_propagation(fn) { return function (event) { event.stopPropagation(); // @ts-ignore return fn.call(this, event); }; } function attr(node, attribute, value) { if (value == null) node.removeAttribute(attribute); else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value); } function to_number(value) { return value === '' ? undefined : +value; } function children(element) { return Array.from(element.childNodes); } function set_data(text, data) { data = '' + data; if (text.wholeText !== data) text.data = data; } function set_input_value(input, value) { input.value = value == null ? '' : value; } function select_option(select, value) { for (let i = 0; i < select.options.length; i += 1) { const option = select.options[i]; if (option.__value === value) { option.selected = true; return; } } } function select_value(select) { const selected_option = select.querySelector(':checked') || select.options[0]; return selected_option && selected_option.__value; } function toggle_class(element, name, toggle) { element.classList[toggle ? 'add' : 'remove'](name); } function custom_event(type, detail) { const e = document.createEvent('CustomEvent'); e.initCustomEvent(type, false, false, detail); return e; } const active_docs = new Set(); let active = 0; // https://github.com/darkskyapp/string-hash/blob/master/index.js function hash(str) { let hash = 5381; let i = str.length; while (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i); return hash >>> 0; } function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) { const step = 16.666 / duration; let keyframes = '{\n'; for (let p = 0; p <= 1; p += step) { const t = a + (b - a) * ease(p); keyframes += p * 100 + `%{${fn(t, 1 - t)}}\n`; } const rule = keyframes + `100% {${fn(b, 1 - b)}}\n}`; const name = `__svelte_${hash(rule)}_${uid}`; const doc = node.ownerDocument; active_docs.add(doc); const stylesheet = doc.__svelte_stylesheet || (doc.__svelte_stylesheet = doc.head.appendChild(element('style')).sheet); const current_rules = doc.__svelte_rules || (doc.__svelte_rules = {}); if (!current_rules[name]) { current_rules[name] = true; stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length); } const animation = node.style.animation || ''; node.style.animation = `${animation ? `${animation}, ` : ``}${name} ${duration}ms linear ${delay}ms 1 both`; active += 1; return name; } function delete_rule(node, name) { const previous = (node.style.animation || '').split(', '); const next = previous.filter(name ? anim => anim.indexOf(name) < 0 // remove specific animation : anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations ); const deleted = previous.length - next.length; if (deleted) { node.style.animation = next.join(', '); active -= deleted; if (!active) clear_rules(); } } function clear_rules() { raf(() => { if (active) return; active_docs.forEach(doc => { const stylesheet = doc.__svelte_stylesheet; let i = stylesheet.cssRules.length; while (i--) stylesheet.deleteRule(i); doc.__svelte_rules = {}; }); active_docs.clear(); }); } let current_component; function set_current_component(component) { current_component = component; } function get_current_component() { if (!current_component) throw new Error(`Function called outside component initialization`); return current_component; } function afterUpdate(fn) { get_current_component().$$.after_update.push(fn); } function onDestroy(fn) { get_current_component().$$.on_destroy.push(fn); } function createEventDispatcher() { const component = get_current_component(); return (type, detail) => { const callbacks = component.$$.callbacks[type]; if (callbacks) { // TODO are there situations where events could be dispatched // in a server (non-DOM) environment? const event = custom_event(type, detail); callbacks.slice().forEach(fn => { fn.call(component, event); }); } }; } function setContext(key, context) { get_current_component().$$.context.set(key, context); } function getContext(key) { return get_current_component().$$.context.get(key); } // TODO figure out if we still want to support // shorthand events, or if we want to implement // a real bubbling mechanism function bubble(component, event) { const callbacks = component.$$.callbacks[event.type]; if (callbacks) { callbacks.slice().forEach(fn => fn(event)); } } const dirty_components = []; const binding_callbacks = []; const render_callbacks = []; const flush_callbacks = []; const resolved_promise = Promise.resolve(); let update_scheduled = false; function schedule_update() { if (!update_scheduled) { update_scheduled = true; resolved_promise.then(flush); } } function add_render_callback(fn) { render_callbacks.push(fn); } let flushing = false; const seen_callbacks = new Set(); function flush() { if (flushing) return; flushing = true; do { // first, call beforeUpdate functions // and update components for (let i = 0; i < dirty_components.length; i += 1) { const component = dirty_components[i]; set_current_component(component); update(component.$$); } dirty_components.length = 0; while (binding_callbacks.length) binding_callbacks.pop()(); // then, once components are updated, call // afterUpdate functions. This may cause // subsequent updates... for (let i = 0; i < render_callbacks.length; i += 1) { const callback = render_callbacks[i]; if (!seen_callbacks.has(callback)) { // ...so guard against infinite loops seen_callbacks.add(callback); callback(); } } render_callbacks.length = 0; } while (dirty_components.length); while (flush_callbacks.length) { flush_callbacks.pop()(); } update_scheduled = false; flushing = false; seen_callbacks.clear(); } function update($$) { if ($$.fragment !== null) { $$.update(); run_all($$.before_update); const dirty = $$.dirty; $$.dirty = [-1]; $$.fragment && $$.fragment.p($$.ctx, dirty); $$.after_update.forEach(add_render_callback); } } let promise; function wait() { if (!promise) { promise = Promise.resolve(); promise.then(() => { promise = null; }); } return promise; } function dispatch(node, direction, kind) { node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`)); } const outroing = new Set(); let outros; function group_outros() { outros = { r: 0, c: [], p: outros // parent group }; } function check_outros() { if (!outros.r) { run_all(outros.c); } outros = outros.p; } function transition_in(block, local) { if (block && block.i) { outroing.delete(block); block.i(local); } } function transition_out(block, local, detach, callback) { if (block && block.o) { if (outroing.has(block)) return; outroing.add(block); outros.c.push(() => { outroing.delete(block); if (callback) { if (detach) block.d(1); callback(); } }); block.o(local); } } const null_transition = { duration: 0 }; function create_bidirectional_transition(node, fn, params, intro) { let config = fn(node, params); let t = intro ? 0 : 1; let running_program = null; let pending_program = null; let animation_name = null; function clear_animation() { if (animation_name) delete_rule(node, animation_name); } function init(program, duration) { const d = program.b - t; duration *= Math.abs(d); return { a: t, b: program.b, d, duration, start: program.start, end: program.start + duration, group: program.group }; } function go(b) { const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition; const program = { start: now() + delay, b }; if (!b) { // @ts-ignore todo: improve typings program.group = outros; outros.r += 1; } if (running_program) { pending_program = program; } else { // if this is an intro, and there's a delay, we need to do // an initial tick and/or apply CSS animation immediately if (css) { clear_animation(); animation_name = create_rule(node, t, b, duration, delay, easing, css); } if (b) tick(0, 1); running_program = init(program, duration); add_render_callback(() => dispatch(node, b, 'start')); loop(now => { if (pending_program && now > pending_program.start) { running_program = init(pending_program, duration); pending_program = null; dispatch(node, running_program.b, 'start'); if (css) { clear_animation(); animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css); } } if (running_program) { if (now >= running_program.end) { tick(t = running_program.b, 1 - t); dispatch(node, running_program.b, 'end'); if (!pending_program) { // we're done if (running_program.b) { // intro — we can tidy up immediately clear_animation(); } else { // outro — needs to be coordinated if (!--running_program.group.r) run_all(running_program.group.c); } } running_program = null; } else if (now >= running_program.start) { const p = now - running_program.start; t = running_program.a + running_program.d * easing(p / running_program.duration); tick(t, 1 - t); } } return !!(running_program || pending_program); }); } } return { run(b) { if (is_function(config)) { wait().then(() => { // @ts-ignore config = config(); go(b); }); } else { go(b); } }, end() { clear_animation(); running_program = pending_program = null; } }; } const globals = (typeof window !== 'undefined' ? window : typeof globalThis !== 'undefined' ? globalThis : global); function get_spread_update(levels, updates) { const update = {}; const to_null_out = {}; const accounted_for = { $$scope: 1 }; let i = levels.length; while (i--) { const o = levels[i]; const n = updates[i]; if (n) { for (const key in o) { if (!(key in n)) to_null_out[key] = 1; } for (const key in n) { if (!accounted_for[key]) { update[key] = n[key]; accounted_for[key] = 1; } } levels[i] = n; } else { for (const key in o) { accounted_for[key] = 1; } } } for (const key in to_null_out) { if (!(key in update)) update[key] = undefined; } return update; } function get_spread_object(spread_props) { return typeof spread_props === 'object' && spread_props !== null ? spread_props : {}; } function create_component(block) { block && block.c(); } function mount_component(component, target, anchor) { const { fragment, on_mount, on_destroy, after_update } = component.$$; fragment && fragment.m(target, anchor); // onMount happens before the initial afterUpdate add_render_callback(() => { const new_on_destroy = on_mount.map(run).filter(is_function); if (on_destroy) { on_destroy.push(...new_on_destroy); } else { // Edge case - component was destroyed immediately, // most likely as a result of a binding initialising run_all(new_on_destroy); } component.$$.on_mount = []; }); after_update.forEach(add_render_callback); } function destroy_component(component, detaching) { const $$ = component.$$; if ($$.fragment !== null) { run_all($$.on_destroy); $$.fragment && $$.fragment.d(detaching); // TODO null out other refs, including component.$$ (but need to // preserve final state?) $$.on_destroy = $$.fragment = null; $$.ctx = []; } } function make_dirty(component, i) { if (component.$$.dirty[0] === -1) { dirty_components.push(component); schedule_update(); component.$$.dirty.fill(0); } component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31)); } function init(component, options, instance, create_fragment, not_equal, props, dirty = [-1]) { const parent_component = current_component; set_current_component(component); const prop_values = options.props || {}; const $$ = component.$$ = { fragment: null, ctx: null, // state props, update: noop, not_equal, bound: blank_object(), // lifecycle on_mount: [], on_destroy: [], before_update: [], after_update: [], context: new Map(parent_component ? parent_component.$$.context : []), // everything else callbacks: blank_object(), dirty }; let ready = false; $$.ctx = instance ? instance(component, prop_values, (i, ret, ...rest) => { const value = rest.length ? rest[0] : ret; if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { if ($$.bound[i]) $$.bound[i](value); if (ready) make_dirty(component, i); } return ret; }) : []; $$.update(); ready = true; run_all($$.before_update); // `false` as a special case of no DOM component $$.fragment = create_fragment ? create_fragment($$.ctx) : false; if (options.target) { if (options.hydrate) { const nodes = children(options.target); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment && $$.fragment.l(nodes); nodes.forEach(detach); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment && $$.fragment.c(); } if (options.intro) transition_in(component.$$.fragment); mount_component(component, options.target, options.anchor); flush(); } set_current_component(parent_component); } class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set() { // overridden by instance, if it has props } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const MAKE_MOVE = 'MAKE_MOVE'; const GAME_EVENT = 'GAME_EVENT'; const REDO = 'REDO'; const RESET = 'RESET'; const SYNC = 'SYNC'; const UNDO = 'UNDO'; const UPDATE = 'UPDATE'; const PLUGIN = 'PLUGIN'; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Generate a move to be dispatched to the game move reducer. * * @param {string} type - The move type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const makeMove = (type, args, playerID, credentials) => ({ type: MAKE_MOVE, payload: { type, args, playerID, credentials }, }); /** * Generate a game event to be dispatched to the flow reducer. * * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const gameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, }); /** * Generate an automatic game event that is a side-effect of a move. * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const automaticGameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, automatic: true, }); const sync = (info) => ({ type: SYNC, state: info.state, log: info.log, initialState: info.initialState, clientOnly: true, }); /** * Used to update the Redux store's state in response to * an action coming from another player. * @param {object} state - The state to restore. * @param {Array} deltalog - A log delta. */ const update$1 = (state, deltalog) => ({ type: UPDATE, state, deltalog, clientOnly: true, }); /** * Used to reset the game state. * @param {object} state - The initial state. */ const reset = (state) => ({ type: RESET, state, clientOnly: true, }); /** * Used to undo the last move. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const undo = (playerID, credentials) => ({ type: UNDO, payload: { type: null, args: null, playerID, credentials }, }); /** * Used to redo the last undone move. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const redo = (playerID, credentials) => ({ type: REDO, payload: { type: null, args: null, playerID, credentials }, }); /** * Allows plugins to define their own actions and intercept them. */ const plugin = (type, args, playerID, credentials) => ({ type: PLUGIN, payload: { type, args, playerID, credentials }, }); var ActionCreators = /*#__PURE__*/Object.freeze({ makeMove: makeMove, gameEvent: gameEvent, automaticGameEvent: automaticGameEvent, sync: sync, update: update$1, reset: reset, undo: undo, redo: redo, plugin: plugin }); /** * Moves can return this when they want to indicate * that the combination of arguments is illegal and * the move ought to be discarded. */ const INVALID_MOVE = 'INVALID_MOVE'; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Plugin that allows using Immer to make immutable changes * to G by just mutating it. */ const ImmerPlugin = { name: 'plugin-immer', fnWrap: (move) => (G, ctx, ...args) => { let isInvalid = false; const newG = produce(G, (G) => { const result = move(G, ctx, ...args); if (result === INVALID_MOVE) { isInvalid = true; return; } return result; }); if (isInvalid) return INVALID_MOVE; return newG; }, }; // Inlined version of Alea from https://github.com/davidbau/seedrandom. // Converted to Typescript October 2020. class Alea { constructor(seed) { const mash = Mash(); // Apply the seeding algorithm from Baagoe. this.c = 1; this.s0 = mash(' '); this.s1 = mash(' '); this.s2 = mash(' '); this.s0 -= mash(seed); if (this.s0 < 0) { this.s0 += 1; } this.s1 -= mash(seed); if (this.s1 < 0) { this.s1 += 1; } this.s2 -= mash(seed); if (this.s2 < 0) { this.s2 += 1; } } next() { const t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 this.s0 = this.s1; this.s1 = this.s2; return (this.s2 = t - (this.c = Math.trunc(t))); } } function Mash() { let n = 0xefc8249d; const mash = function (data) { const str = data.toString(); for (let i = 0; i < str.length; i++) { n += str.charCodeAt(i); let h = 0.02519603282416938 * n; n = h >>> 0; h -= n; h *= n; n = h >>> 0; h -= n; n += h * 0x100000000; // 2^32 } return (n >>> 0) * 2.3283064365386963e-10; // 2^-32 }; return mash; } function copy(f, t) { t.c = f.c; t.s0 = f.s0; t.s1 = f.s1; t.s2 = f.s2; return t; } function alea(seed, state) { const xg = new Alea(seed); const prng = xg.next.bind(xg); if (state) copy(state, xg); prng.state = () => copy(xg, {}); return prng; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Random * * Calls that require a pseudorandom number generator. * Uses a seed from ctx, and also persists the PRNG * state in ctx so that moves can stay pure. */ class Random { /** * constructor * @param {object} ctx - The ctx object to initialize from. */ constructor(state) { // If we are on the client, the seed is not present. // Just use a temporary seed to execute the move without // crashing it. The move state itself is discarded, // so the actual value doesn't matter. this.state = state || { seed: '0' }; this.used = false; } /** * Generates a new seed from the current date / time. */ static seed() { return Date.now().toString(36).slice(-10); } isUsed() { return this.used; } getState() { return this.state; } /** * Generate a random number. */ _random() { this.used = true; const R = this.state; const seed = R.prngstate ? '' : R.seed; const rand = alea(seed, R.prngstate); const number = rand(); this.state = { ...R, prngstate: rand.state(), }; return number; } api() { const random = this._random.bind(this); const SpotValue = { D4: 4, D6: 6, D8: 8, D10: 10, D12: 12, D20: 20, }; // Generate functions for predefined dice values D4 - D20. const predefined = {}; for (const key in SpotValue) { const spotvalue = SpotValue[key]; predefined[key] = (diceCount) => { return diceCount === undefined ? Math.floor(random() * spotvalue) + 1 : [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1); }; } function Die(spotvalue = 6, diceCount) { return diceCount === undefined ? Math.floor(random() * spotvalue) + 1 : [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1); } return { /** * Similar to Die below, but with fixed spot values. * Supports passing a diceCount * if not defined, defaults to 1 and returns the value directly. * if defined, returns an array containing the random dice values. * * D4: (diceCount) => value * D6: (diceCount) => value * D8: (diceCount) => value * D10: (diceCount) => value * D12: (diceCount) => value * D20: (diceCount) => value */ ...predefined, /** * Roll a die of specified spot value. * * @param {number} spotvalue - The die dimension (default: 6). * @param {number} diceCount - number of dice to throw. * if not defined, defaults to 1 and returns the value directly. * if defined, returns an array containing the random dice values. */ Die, /** * Generate a random number between 0 and 1. */ Number: () => { return random(); }, /** * Shuffle an array. * * @param {Array} deck - The array to shuffle. Does not mutate * the input, but returns the shuffled array. */ Shuffle: (deck) => { const clone = deck.slice(0); let srcIndex = deck.length; let dstIndex = 0; const shuffled = new Array(srcIndex); while (srcIndex) { const randIndex = Math.trunc(srcIndex * random()); shuffled[dstIndex++] = clone[randIndex]; clone[randIndex] = clone[--srcIndex]; } return shuffled; }, _obj: this, }; } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const RandomPlugin = { name: 'random', noClient: ({ api }) => { return api._obj.isUsed(); }, flush: ({ api }) => { return api._obj.getState(); }, api: ({ data }) => { const random = new Random(data); return random.api(); }, setup: ({ game }) => { let { seed } = game; if (seed === undefined) { seed = Random.seed(); } return { seed }; }, playerView: () => undefined, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Events */ class Events { constructor(flow, playerID) { this.flow = flow; this.playerID = playerID; this.dispatch = []; } /** * Attaches the Events API to ctx. * @param {object} ctx - The ctx object to attach to. */ api(ctx) { const events = { _obj: this, }; const { phase, turn } = ctx; for (const key of this.flow.eventNames) { events[key] = (...args) => { this.dispatch.push({ key, args, phase, turn }); }; } return events; } isUsed() { return this.dispatch.length > 0; } /** * Updates ctx with the triggered events. * @param {object} state - The state object { G, ctx }. */ update(state) { for (let i = 0; i < this.dispatch.length; i++) { const item = this.dispatch[i]; // If the turn already ended some other way, // don't try to end the turn again. if (item.key === 'endTurn' && item.turn !== state.ctx.turn) { continue; } // If the phase already ended some other way, // don't try to end the phase again. if ((item.key === 'endPhase' || item.key === 'setPhase') && item.phase !== state.ctx.phase) { continue; } const action = automaticGameEvent(item.key, item.args, this.playerID); state = { ...state, ...this.flow.processEvent(state, action), }; } return state; } } /* * Copyright 2020 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const EventsPlugin = { name: 'events', noClient: ({ api }) => { return api._obj.isUsed(); }, dangerouslyFlushRawState: ({ state, api }) => { return api._obj.update(state); }, api: ({ game, playerID, ctx }) => { return new Events(game.flow, playerID).api(ctx); }, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Plugin that makes it possible to add metadata to log entries. * During a move, you can set metadata using ctx.log.setMetadata and it will be * available on the log entry for that move. */ const LogPlugin = { name: 'log', flush: () => ({}), api: ({ data }) => { return { setMetadata: (metadata) => { data.metadata = metadata; }, }; }, setup: () => ({}), }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * List of plugins that are always added. */ const DEFAULT_PLUGINS = [ImmerPlugin, RandomPlugin, EventsPlugin, LogPlugin]; /** * Allow plugins to intercept actions and process them. */ const ProcessAction = (state, action, opts) => { opts.game.plugins .filter((plugin) => plugin.action !== undefined) .filter((plugin) => plugin.name === action.payload.type) .forEach((plugin) => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const data = plugin.action(pluginState.data, action.payload); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, data }, }, }; }); return state; }; /** * The API's created by various plugins are stored in the plugins * section of the state object: * * { * G: {}, * ctx: {}, * plugins: { * plugin-a: { * data: {}, // this is generated by the plugin at Setup / Flush. * api: {}, // this is ephemeral and generated by Enhance. * } * } * } * * This function takes these API's and stuffs them back into * ctx for consumption inside a move function or hook. */ const EnhanceCtx = (state) => { const ctx = { ...state.ctx }; const plugins = state.plugins || {}; Object.entries(plugins).forEach(([name, { api }]) => { ctx[name] = api; }); return ctx; }; /** * Applies the provided plugins to the given move / flow function. * * @param {function} fn - The move function or trigger to apply the plugins to. * @param {object} plugins - The list of plugins. */ const FnWrap = (fn, plugins) => { const reducer = (acc, { fnWrap }) => fnWrap(acc); return [...DEFAULT_PLUGINS, ...plugins] .filter((plugin) => plugin.fnWrap !== undefined) .reduce(reducer, fn); }; /** * Allows the plugin to generate its initial state. */ const Setup = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter((plugin) => plugin.setup !== undefined) .forEach((plugin) => { const name = plugin.name; const data = plugin.setup({ G: state.G, ctx: state.ctx, game: opts.game, }); state = { ...state, plugins: { ...state.plugins, [name]: { data }, }, }; }); return state; }; /** * Invokes the plugin before a move or event. * The API that the plugin generates is stored inside * the `plugins` section of the state (which is subsequently * merged into ctx). */ const Enhance = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter((plugin) => plugin.api !== undefined) .forEach((plugin) => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const api = plugin.api({ G: state.G, ctx: state.ctx, data: pluginState.data, game: opts.game, playerID: opts.playerID, }); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, api }, }, }; }); return state; }; /** * Allows plugins to update their state after a move / event. */ const Flush = (state, opts) => { // Note that we flush plugins in reverse order, to make sure that plugins // that come before in the chain are still available. [...DEFAULT_PLUGINS, ...opts.game.plugins].reverse().forEach((plugin) => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; if (plugin.flush) { const newData = plugin.flush({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data: newData }, }, }; } else if (plugin.dangerouslyFlushRawState) { state = plugin.dangerouslyFlushRawState({ state, game: opts.game, api: pluginState.api, data: pluginState.data, }); // Remove everything other than data. const data = state.plugins[name].data; state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data }, }, }; } }); return state; }; /** * Allows plugins to indicate if they should not be materialized on the client. * This will cause the client to discard the state update and wait for the * master instead. */ const NoClient = (state, opts) => { return [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter((plugin) => plugin.noClient !== undefined) .map((plugin) => { const name = plugin.name; const pluginState = state.plugins[name]; if (pluginState) { return plugin.noClient({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); } return false; }) .some((value) => value === true); }; /** * Allows plugins to customize their data for specific players. * For example, a plugin may want to share no data with the client, or * want to keep some player data secret from opponents. */ const PlayerView = ({ G, ctx, plugins = {} }, { game, playerID }) => { [...DEFAULT_PLUGINS, ...game.plugins].forEach(({ name, playerView }) => { if (!playerView) return; const { data } = plugins[name] || { data: {} }; const newData = playerView({ G, ctx, game, data, playerID }); plugins = { ...plugins, [name]: { data: newData }, }; }); return plugins; }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const production = process.env.NODE_ENV === 'production'; const logfn = production ? () => { } : console.log; const errorfn = console.error; function info(msg) { logfn(`INFO: ${msg}`); } function error(error) { errorfn('ERROR:', error); } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Event to change the active players (and their stages) in the current turn. */ function SetActivePlayersEvent(state, _playerID, arg) { return { ...state, ctx: SetActivePlayers(state.ctx, arg) }; } function SetActivePlayers(ctx, arg) { let { _prevActivePlayers } = ctx; let activePlayers = {}; let _nextActivePlayers = null; let _activePlayersMoveLimit = {}; if (Array.isArray(arg)) { // support a simple array of player IDs as active players const value = {}; arg.forEach((v) => (value[v] = Stage.NULL)); activePlayers = value; } else { // process active players argument object if (arg.next) { _nextActivePlayers = arg.next; } _prevActivePlayers = arg.revert ? _prevActivePlayers.concat({ activePlayers: ctx.activePlayers, _activePlayersMoveLimit: ctx._activePlayersMoveLimit, _activePlayersNumMoves: ctx._activePlayersNumMoves, }) : []; if (arg.currentPlayer !== undefined) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, ctx.currentPlayer, arg.currentPlayer); } if (arg.others !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; if (id !== ctx.currentPlayer) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.others); } } } if (arg.all !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.all); } } if (arg.value) { for (const id in arg.value) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.value[id]); } } if (arg.moveLimit) { for (const id in activePlayers) { if (_activePlayersMoveLimit[id] === undefined) { _activePlayersMoveLimit[id] = arg.moveLimit; } } } } if (Object.keys(activePlayers).length == 0) { activePlayers = null; } if (Object.keys(_activePlayersMoveLimit).length == 0) { _activePlayersMoveLimit = null; } const _activePlayersNumMoves = {}; for (const id in activePlayers) { _activePlayersNumMoves[id] = 0; } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, }; } /** * Update activePlayers, setting it to previous, next or null values * when it becomes empty. * @param ctx */ function UpdateActivePlayersOnceEmpty(ctx) { let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx; if (activePlayers && Object.keys(activePlayers).length == 0) { if (ctx._nextActivePlayers) { ctx = SetActivePlayers(ctx, ctx._nextActivePlayers); ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx); } else if (_prevActivePlayers.length > 0) { const lastIndex = _prevActivePlayers.length - 1; ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = _prevActivePlayers[lastIndex]); _prevActivePlayers = _prevActivePlayers.slice(0, lastIndex); } else { activePlayers = null; _activePlayersMoveLimit = null; } } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, }; } /** * Apply an active player argument to the given player ID * @param {Object} activePlayers * @param {Object} _activePlayersMoveLimit * @param {String} playerID The player to apply the parameter to * @param {(String|Object)} arg An active player argument */ function ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, playerID, arg) { if (typeof arg !== 'object' || arg === Stage.NULL) { arg = { stage: arg }; } if (arg.stage !== undefined) { activePlayers[playerID] = arg.stage; if (arg.moveLimit) _activePlayersMoveLimit[playerID] = arg.moveLimit; } } /** * Converts a playOrderPos index into its value in playOrder. * @param {Array} playOrder - An array of player ID's. * @param {number} playOrderPos - An index into the above. */ function getCurrentPlayer(playOrder, playOrderPos) { // convert to string in case playOrder is set to number[] return playOrder[playOrderPos] + ''; } /** * Called at the start of a turn to initialize turn order state. * * TODO: This is called inside StartTurn, which is called from * both UpdateTurn and StartPhase (so it's called at the beginning * of a new phase as well as between turns). We should probably * split it into two. */ function InitTurnOrderState(state, turn) { let { G, ctx } = state; const ctxWithAPI = EnhanceCtx(state); const order = turn.order; let playOrder = [...new Array(ctx.numPlayers)].map((_, i) => i + ''); if (order.playOrder !== undefined) { playOrder = order.playOrder(G, ctxWithAPI); } const playOrderPos = order.first(G, ctxWithAPI); const posType = typeof playOrderPos; if (posType !== 'number') { error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`); } const currentPlayer = getCurrentPlayer(playOrder, playOrderPos); ctx = { ...ctx, currentPlayer, playOrderPos, playOrder }; ctx = SetActivePlayers(ctx, turn.activePlayers || {}); return ctx; } /** * Called at the end of each turn to update the turn order state. * @param {object} G - The game object G. * @param {object} ctx - The game object ctx. * @param {object} turn - A turn object for this phase. * @param {string} endTurnArg - An optional argument to endTurn that may specify the next player. */ function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) { const order = turn.order; let { G, ctx } = state; let playOrderPos = ctx.playOrderPos; let endPhase = false; if (endTurnArg && endTurnArg !== true) { if (typeof endTurnArg !== 'object') { error(`invalid argument to endTurn: ${endTurnArg}`); } Object.keys(endTurnArg).forEach((arg) => { switch (arg) { case 'remove': currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); break; case 'next': playOrderPos = ctx.playOrder.indexOf(endTurnArg.next); currentPlayer = endTurnArg.next; break; default: error(`invalid argument to endTurn: ${arg}`); } }); } else { const ctxWithAPI = EnhanceCtx(state); const t = order.next(G, ctxWithAPI); const type = typeof t; if (t !== undefined && type !== 'number') { error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`); } if (t === undefined) { endPhase = true; } else { playOrderPos = t; currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); } } ctx = { ...ctx, playOrderPos, currentPlayer, }; return { endPhase, ctx }; } /** * Set of different turn orders possible in a phase. * These are meant to be passed to the `turn` setting * in the flow objects. * * Each object defines the first player when the phase / game * begins, and also a function `next` to determine who the * next player is when the turn ends. * * The phase ends if next() returns undefined. */ const TurnOrder = { /** * DEFAULT * * The default round-robin turn order. */ DEFAULT: { first: (G, ctx) => ctx.turn === 0 ? ctx.playOrderPos : (ctx.playOrderPos + 1) % ctx.playOrder.length, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * RESET * * Similar to DEFAULT, but starts from 0 each time. */ RESET: { first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * CONTINUE * * Similar to DEFAULT, but starts with the player who ended the last phase. */ CONTINUE: { first: (G, ctx) => ctx.playOrderPos, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * ONCE * * Another round-robin turn order, but goes around just once. * The phase ends after all players have played. */ ONCE: { first: () => 0, next: (G, ctx) => { if (ctx.playOrderPos < ctx.playOrder.length - 1) { return ctx.playOrderPos + 1; } }, }, /** * CUSTOM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase. * * @param {Array} playOrder - The play order. */ CUSTOM: (playOrder) => ({ playOrder: () => playOrder, first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), /** * CUSTOM_FROM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase to a value specified by a field * in G. * * @param {string} playOrderField - Field in G. */ CUSTOM_FROM: (playOrderField) => ({ playOrder: (G) => G[playOrderField], first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), }; const Stage = { NULL: null, }; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Flow * * Creates a reducer that updates ctx (analogous to how moves update G). */ function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) { // Attach defaults. if (moves === undefined) { moves = {}; } if (events === undefined) { events = {}; } if (plugins === undefined) { plugins = []; } if (phases === undefined) { phases = {}; } if (!endIf) endIf = () => undefined; if (!onEnd) onEnd = (G) => G; if (!turn) turn = {}; const phaseMap = { ...phases }; if ('' in phaseMap) { error('cannot specify phase with empty name'); } phaseMap[''] = {}; const moveMap = {}; const moveNames = new Set(); let startingPhase = null; Object.keys(moves).forEach((name) => moveNames.add(name)); const HookWrapper = (fn) => { const withPlugins = FnWrap(fn, plugins); return (state) => { const ctxWithAPI = EnhanceCtx(state); return withPlugins(state.G, ctxWithAPI); }; }; const TriggerWrapper = (endIf) => { return (state) => { const ctxWithAPI = EnhanceCtx(state); return endIf(state.G, ctxWithAPI); }; }; const wrapped = { onEnd: HookWrapper(onEnd), endIf: TriggerWrapper(endIf), }; for (const phase in phaseMap) { const conf = phaseMap[phase]; if (conf.start === true) { startingPhase = phase; } if (conf.moves !== undefined) { for (const move of Object.keys(conf.moves)) { moveMap[phase + '.' + move] = conf.moves[move]; moveNames.add(move); } } if (conf.endIf === undefined) { conf.endIf = () => undefined; } if (conf.onBegin === undefined) { conf.onBegin = (G) => G; } if (conf.onEnd === undefined) { conf.onEnd = (G) => G; } if (conf.turn === undefined) { conf.turn = turn; } if (conf.turn.order === undefined) { conf.turn.order = TurnOrder.DEFAULT; } if (conf.turn.onBegin === undefined) { conf.turn.onBegin = (G) => G; } if (conf.turn.onEnd === undefined) { conf.turn.onEnd = (G) => G; } if (conf.turn.endIf === undefined) { conf.turn.endIf = () => false; } if (conf.turn.onMove === undefined) { conf.turn.onMove = (G) => G; } if (conf.turn.stages === undefined) { conf.turn.stages = {}; } for (const stage in conf.turn.stages) { const stageConfig = conf.turn.stages[stage]; const moves = stageConfig.moves || {}; for (const move of Object.keys(moves)) { const key = phase + '.' + stage + '.' + move; moveMap[key] = moves[move]; moveNames.add(move); } } conf.wrapped = { onBegin: HookWrapper(conf.onBegin), onEnd: HookWrapper(conf.onEnd), endIf: TriggerWrapper(conf.endIf), }; conf.turn.wrapped = { onMove: HookWrapper(conf.turn.onMove), onBegin: HookWrapper(conf.turn.onBegin), onEnd: HookWrapper(conf.turn.onEnd), endIf: TriggerWrapper(conf.turn.endIf), }; } function GetPhase(ctx) { return ctx.phase ? phaseMap[ctx.phase] : phaseMap['']; } function OnMove(s) { return s; } function Process(state, events) { const phasesEnded = new Set(); const turnsEnded = new Set(); for (let i = 0; i < events.length; i++) { const { fn, arg, ...rest } = events[i]; // Detect a loop of EndPhase calls. // This could potentially even be an infinite loop // if the endIf condition of each phase blindly // returns true. The moment we detect a single // loop, we just bail out of all phases. if (fn === EndPhase) { turnsEnded.clear(); const phase = state.ctx.phase; if (phasesEnded.has(phase)) { const ctx = { ...state.ctx, phase: null }; return { ...state, ctx }; } phasesEnded.add(phase); } // Process event. const next = []; state = fn(state, { ...rest, arg, next, }); if (fn === EndGame) { break; } // Check if we should end the game. const shouldEndGame = ShouldEndGame(state); if (shouldEndGame) { events.push({ fn: EndGame, arg: shouldEndGame, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the phase. const shouldEndPhase = ShouldEndPhase(state); if (shouldEndPhase) { events.push({ fn: EndPhase, arg: shouldEndPhase, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the turn. if (fn === OnMove) { const shouldEndTurn = ShouldEndTurn(state); if (shouldEndTurn) { events.push({ fn: EndTurn, arg: shouldEndTurn, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } } events.push(...next); } return state; } /////////// // Start // /////////// function StartGame(state, { next }) { next.push({ fn: StartPhase }); return state; } function StartPhase(state, { next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Run any phase setup code provided by the user. G = conf.wrapped.onBegin(state); next.push({ fn: StartTurn }); return { ...state, G, ctx }; } function StartTurn(state, { currentPlayer }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Initialize the turn order state. if (currentPlayer) { ctx = { ...ctx, currentPlayer }; if (conf.turn.activePlayers) { ctx = SetActivePlayers(ctx, conf.turn.activePlayers); } } else { // This is only called at the beginning of the phase // when there is no currentPlayer yet. ctx = InitTurnOrderState(state, conf.turn); } const turn = ctx.turn + 1; ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] }; G = conf.turn.wrapped.onBegin({ ...state, G, ctx }); return { ...state, G, ctx, _undo: [], _redo: [] }; } //////////// // Update // //////////// function UpdatePhase(state, { arg, next, phase }) { const conf = GetPhase({ phase }); let { ctx } = state; if (arg && arg.next) { if (arg.next in phaseMap) { ctx = { ...ctx, phase: arg.next }; } else { error('invalid phase: ' + arg.next); return state; } } else if (conf.next !== undefined) { ctx = { ...ctx, phase: conf.next }; } else { ctx = { ...ctx, phase: null }; } state = { ...state, ctx }; // Start the new phase. next.push({ fn: StartPhase }); return state; } function UpdateTurn(state, { arg, currentPlayer, next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Update turn order state. const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, conf.turn, arg); ctx = newCtx; state = { ...state, G, ctx }; if (endPhase) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); } else { next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer }); } return state; } function UpdateStage(state, { arg, playerID }) { if (typeof arg === 'string' || arg === Stage.NULL) { arg = { stage: arg }; } let { ctx } = state; let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = ctx; // Checking if stage is valid, even Stage.NULL if (arg.stage !== undefined) { if (activePlayers === null) { activePlayers = {}; } activePlayers[playerID] = arg.stage; _activePlayersNumMoves[playerID] = 0; if (arg.moveLimit) { if (_activePlayersMoveLimit === null) { _activePlayersMoveLimit = {}; } _activePlayersMoveLimit[playerID] = arg.moveLimit; } } ctx = { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, }; return { ...state, ctx }; } /////////////// // ShouldEnd // /////////////// function ShouldEndGame(state) { return wrapped.endIf(state); } function ShouldEndPhase(state) { const conf = GetPhase(state.ctx); return conf.wrapped.endIf(state); } function ShouldEndTurn(state) { const conf = GetPhase(state.ctx); // End the turn if the required number of moves has been made. const currentPlayerMoves = state.ctx.numMoves || 0; if (conf.turn.moveLimit && currentPlayerMoves >= conf.turn.moveLimit) { return true; } return conf.turn.wrapped.endIf(state); } ///////// // End // ///////// function EndGame(state, { arg, phase }) { state = EndPhase(state, { phase }); if (arg === undefined) { arg = true; } state = { ...state, ctx: { ...state.ctx, gameover: arg } }; // Run game end hook. const G = wrapped.onEnd(state); return { ...state, G }; } function EndPhase(state, { arg, next, turn, automatic }) { // End the turn first. state = EndTurn(state, { turn, force: true, automatic: true }); let G = state.G; let ctx = state.ctx; if (next) { next.push({ fn: UpdatePhase, arg, phase: ctx.phase }); } // If we aren't in a phase, there is nothing else to do. if (ctx.phase === null) { return state; } // Run any cleanup code for the phase that is about to end. const conf = GetPhase(ctx); G = conf.wrapped.onEnd(state); // Reset the phase. ctx = { ...ctx, phase: null }; // Add log entry. const action = gameEvent('endPhase', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, G, ctx, deltalog }; } function EndTurn(state, { arg, next, turn, force, automatic, playerID }) { // This is not the turn that EndTurn was originally // called for. The turn was probably ended some other way. if (turn !== state.ctx.turn) { return state; } let { G, ctx } = state; const conf = GetPhase(ctx); // Prevent ending the turn if moveLimit hasn't been reached. const currentPlayerMoves = ctx.numMoves || 0; if (!force && conf.turn.moveLimit && currentPlayerMoves < conf.turn.moveLimit) { info(`cannot end turn before making ${conf.turn.moveLimit} moves`); return state; } // Run turn-end triggers. G = conf.turn.wrapped.onEnd(state); if (next) { next.push({ fn: UpdateTurn, arg, currentPlayer: ctx.currentPlayer }); } // Reset activePlayers. ctx = { ...ctx, activePlayers: null }; // Remove player from playerOrder if (arg && arg.remove) { playerID = playerID || ctx.currentPlayer; const playOrder = ctx.playOrder.filter((i) => i != playerID); const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos; ctx = { ...ctx, playOrder, playOrderPos }; if (playOrder.length === 0) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); return state; } } // Add log entry. const action = gameEvent('endTurn', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, G, ctx, deltalog, _undo: [], _redo: [] }; } function EndStage(state, { arg, next, automatic, playerID }) { playerID = playerID || state.ctx.currentPlayer; let { ctx } = state; let { activePlayers, _activePlayersMoveLimit } = ctx; const playerInStage = activePlayers !== null && playerID in activePlayers; if (!arg && playerInStage) { const conf = GetPhase(ctx); const stage = conf.turn.stages[activePlayers[playerID]]; if (stage && stage.next) arg = stage.next; } // Checking if arg is a valid stage, even Stage.NULL if (next && arg !== undefined) { next.push({ fn: UpdateStage, arg, playerID }); } // If player isn’t in a stage, there is nothing else to do. if (!playerInStage) return state; // Remove player from activePlayers. activePlayers = Object.keys(activePlayers) .filter((id) => id !== playerID) .reduce((obj, key) => { obj[key] = activePlayers[key]; return obj; }, {}); if (_activePlayersMoveLimit) { // Remove player from _activePlayersMoveLimit. _activePlayersMoveLimit = Object.keys(_activePlayersMoveLimit) .filter((id) => id !== playerID) .reduce((obj, key) => { obj[key] = _activePlayersMoveLimit[key]; return obj; }, {}); } ctx = UpdateActivePlayersOnceEmpty({ ...ctx, activePlayers, _activePlayersMoveLimit, }); // Add log entry. const action = gameEvent('endStage', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, ctx, deltalog }; } /** * Retrieves the relevant move that can be played by playerID. * * If ctx.activePlayers is set (i.e. one or more players are in some stage), * then it attempts to find the move inside the stages config for * that turn. If the stage for a player is '', then the player is * allowed to make a move (as determined by the phase config), but * isn't restricted to a particular set as defined in the stage config. * * If not, it then looks for the move inside the phase. * * If it doesn't find the move there, it looks at the global move definition. * * @param {object} ctx * @param {string} name * @param {string} playerID */ function GetMove(ctx, name, playerID) { const conf = GetPhase(ctx); const stages = conf.turn.stages; const { activePlayers } = ctx; if (activePlayers && activePlayers[playerID] !== undefined && activePlayers[playerID] !== Stage.NULL && stages[activePlayers[playerID]] !== undefined && stages[activePlayers[playerID]].moves !== undefined) { // Check if moves are defined for the player's stage. const stage = stages[activePlayers[playerID]]; const moves = stage.moves; if (name in moves) { return moves[name]; } } else if (conf.moves) { // Check if moves are defined for the current phase. if (name in conf.moves) { return conf.moves[name]; } } else if (name in moves) { // Check for the move globally. return moves[name]; } return null; } function ProcessMove(state, action) { const conf = GetPhase(state.ctx); const move = GetMove(state.ctx, action.type, action.playerID); const shouldCount = !move || typeof move === 'function' || move.noLimit !== true; const { ctx } = state; const { _activePlayersNumMoves } = ctx; const { playerID } = action; let numMoves = state.ctx.numMoves; if (shouldCount) { if (playerID == state.ctx.currentPlayer) { numMoves++; } if (ctx.activePlayers) _activePlayersNumMoves[playerID]++; } state = { ...state, ctx: { ...ctx, numMoves, _activePlayersNumMoves, }, }; if (ctx._activePlayersMoveLimit && _activePlayersNumMoves[playerID] >= ctx._activePlayersMoveLimit[playerID]) { state = EndStage(state, { playerID, automatic: true }); } const G = conf.turn.wrapped.onMove(state); state = { ...state, G }; const events = [{ fn: OnMove }]; return Process(state, events); } function SetStageEvent(state, playerID, arg) { return Process(state, [{ fn: EndStage, arg, playerID }]); } function EndStageEvent(state, playerID) { return Process(state, [{ fn: EndStage, playerID }]); } function SetPhaseEvent(state, _playerID, newPhase) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn, arg: { next: newPhase }, }, ]); } function EndPhaseEvent(state) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn }, ]); } function EndTurnEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } function PassEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, force: true, arg, }, ]); } function EndGameEvent(state, _playerID, arg) { return Process(state, [ { fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } const eventHandlers = { endStage: EndStageEvent, setStage: SetStageEvent, endTurn: EndTurnEvent, pass: PassEvent, endPhase: EndPhaseEvent, setPhase: SetPhaseEvent, endGame: EndGameEvent, setActivePlayers: SetActivePlayersEvent, }; const enabledEventNames = []; if (events.endTurn !== false) { enabledEventNames.push('endTurn'); } if (events.pass !== false) { enabledEventNames.push('pass'); } if (events.endPhase !== false) { enabledEventNames.push('endPhase'); } if (events.setPhase !== false) { enabledEventNames.push('setPhase'); } if (events.endGame !== false) { enabledEventNames.push('endGame'); } if (events.setActivePlayers !== false) { enabledEventNames.push('setActivePlayers'); } if (events.endStage !== false) { enabledEventNames.push('endStage'); } if (events.setStage !== false) { enabledEventNames.push('setStage'); } function ProcessEvent(state, action) { const { type, playerID, args } = action.payload; if (Object.prototype.hasOwnProperty.call(eventHandlers, type)) { const eventArgs = [state, playerID].concat(args); return eventHandlers[type].apply({}, eventArgs); } return state; } function IsPlayerActive(_G, ctx, playerID) { if (ctx.activePlayers) { return playerID in ctx.activePlayers; } return ctx.currentPlayer === playerID; } return { ctx: (numPlayers) => ({ numPlayers, turn: 0, currentPlayer: '0', playOrder: [...new Array(numPlayers)].map((_d, i) => i + ''), playOrderPos: 0, phase: startingPhase, activePlayers: null, }), init: (state) => { return Process(state, [{ fn: StartGame }]); }, isPlayerActive: IsPlayerActive, eventHandlers, eventNames: Object.keys(eventHandlers), enabledEventNames, moveMap, moveNames: [...moveNames.values()], processMove: ProcessMove, processEvent: ProcessEvent, getMove: GetMove, }; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ function IsProcessed(game) { return game.processMove !== undefined; } /** * Helper to generate the game move reducer. The returned * reducer has the following signature: * * (G, action, ctx) => {} * * You can roll your own if you like, or use any Redux * addon to generate such a reducer. * * The convention used in this framework is to * have action.type contain the name of the move, and * action.args contain any additional arguments as an * Array. */ function ProcessGameConfig(game) { // The Game() function has already been called on this // config object, so just pass it through. if (IsProcessed(game)) { return game; } if (game.name === undefined) game.name = 'default'; if (game.disableUndo === undefined) game.disableUndo = false; if (game.setup === undefined) game.setup = () => ({}); if (game.moves === undefined) game.moves = {}; if (game.playerView === undefined) game.playerView = (G) => G; if (game.plugins === undefined) game.plugins = []; game.plugins.forEach((plugin) => { if (plugin.name === undefined) { throw new Error('Plugin missing name attribute'); } if (plugin.name.includes(' ')) { throw new Error(plugin.name + ': Plugin name must not include spaces'); } }); if (game.name.includes(' ')) { throw new Error(game.name + ': Game name must not include spaces'); } const flow = Flow(game); return { ...game, flow, moveNames: flow.moveNames, pluginNames: game.plugins.map((p) => p.name), processMove: (state, action) => { let moveFn = flow.getMove(state.ctx, action.type, action.playerID); if (IsLongFormMove(moveFn)) { moveFn = moveFn.move; } if (moveFn instanceof Function) { const fn = FnWrap(moveFn, game.plugins); const ctxWithAPI = { ...EnhanceCtx(state), playerID: action.playerID, }; let args = []; if (action.args !== undefined) { args = args.concat(action.args); } return fn(state.G, ctxWithAPI, ...args); } error(`invalid move object: ${action.type}`); return state.G; }, }; } function IsLongFormMove(move) { return move instanceof Object && move.move !== undefined; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Check if the payload for the passed action contains a playerID. */ const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined; /** * Returns true if a move can be undone. */ const CanUndoMove = (G, ctx, move) => { function HasUndoable(move) { return move.undoable !== undefined; } function IsFunction(undoable) { return undoable instanceof Function; } if (!HasUndoable(move)) { return true; } if (IsFunction(move.undoable)) { return move.undoable(G, ctx); } return move.undoable; }; /** * Update the undo and redo stacks for a move or event. */ function updateUndoRedoState(state, opts) { if (opts.game.disableUndo) return state; const undoEntry = { G: state.G, ctx: state.ctx, plugins: state.plugins, playerID: opts.action.payload.playerID || state.ctx.currentPlayer, }; if (opts.action.type === 'MAKE_MOVE') { undoEntry.moveType = opts.action.payload.type; } return { ...state, _undo: [...state._undo, undoEntry], // Always reset redo stack when making a move or event _redo: [], }; } /** * Process state, adding the initial deltalog for this action. */ function initializeDeltalog(state, action, move) { // Create a log entry for this action. const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; const pluginLogMetadata = state.plugins.log.data.metadata; if (pluginLogMetadata !== undefined) { logEntry.metadata = pluginLogMetadata; } if (typeof move === 'object' && move.redact === true) { logEntry.redact = true; } return { ...state, deltalog: [logEntry], }; } /** * CreateGameReducer * * Creates the main game state reducer. */ function CreateGameReducer({ game, isClient, }) { game = ProcessGameConfig(game); /** * GameReducer * * Redux reducer that maintains the overall game state. * @param {object} state - The state before the action. * @param {object} action - A Redux action. */ return (state = null, action) => { switch (action.type) { case GAME_EVENT: { state = { ...state, deltalog: [] }; // Process game events only on the server. // These events like `endTurn` typically // contain code that may rely on secret state // and cannot be computed on the client. if (isClient) { return state; } // Disallow events once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot call event after game end`); return state; } // Ignore the event if the player isn't active. if (actionHasPlayerID(action) && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed event: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient: false, playerID: action.payload.playerID, }); // Process event. let newState = game.flow.processEvent(state, action); // Execute plugins. newState = Flush(newState, { game, isClient: false }); // Update undo / redo state. newState = updateUndoRedoState(newState, { game, action }); return { ...newState, _stateID: state._stateID + 1 }; } case MAKE_MOVE: { state = { ...state, deltalog: [] }; // Check whether the move is allowed at this time. const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer); if (move === null) { error(`disallowed move: ${action.payload.type}`); return state; } // Don't run move on client if move says so. if (isClient && move.client === false) { return state; } // Disallow moves once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot make move after game end`); return state; } // Ignore the move if the player isn't active. if (actionHasPlayerID(action) && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed move: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient, playerID: action.payload.playerID, }); // Process the move. const G = game.processMove(state, action.payload); // The game declared the move as invalid. if (G === INVALID_MOVE) { error(`invalid move: ${action.payload.type} args: ${action.payload.args}`); return state; } const newState = { ...state, G }; // Some plugin indicated that it is not suitable to be // materialized on the client (and must wait for the server // response instead). if (isClient && NoClient(newState, { game })) { return state; } state = newState; // If we're on the client, just process the move // and no triggers in multiplayer mode. // These will be processed on the server, which // will send back a state update. if (isClient) { state = Flush(state, { game, isClient: true, }); return { ...state, _stateID: state._stateID + 1, }; } // On the server, construct the deltalog. state = initializeDeltalog(state, action, move); // Allow the flow reducer to process any triggers that happen after moves. state = game.flow.processMove(state, action.payload); state = Flush(state, { game }); // Update undo / redo state. state = updateUndoRedoState(state, { game, action }); return { ...state, _stateID: state._stateID + 1, }; } case RESET: case UPDATE: case SYNC: { return action.state; } case UNDO: { state = { ...state, deltalog: [] }; if (game.disableUndo) { error('Undo is not enabled'); return state; } const { _undo, _redo } = state; if (_undo.length < 2) { return state; } const last = _undo[_undo.length - 1]; const restore = _undo[_undo.length - 2]; // Only allow players to undo their own moves. if (actionHasPlayerID(action) && action.payload.playerID !== last.playerID) { return state; } // Only allow undoable moves to be undone. const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID); if (!CanUndoMove(state.G, state.ctx, lastMove)) { return state; } state = initializeDeltalog(state, action); return { ...state, G: restore.G, ctx: restore.ctx, plugins: restore.plugins, _stateID: state._stateID + 1, _undo: _undo.slice(0, -1), _redo: [last, ..._redo], }; } case REDO: { state = { ...state, deltalog: [] }; if (game.disableUndo) { error('Redo is not enabled'); return state; } const { _undo, _redo } = state; if (_redo.length == 0) { return state; } const first = _redo[0]; // Only allow players to redo their own undos. if (actionHasPlayerID(action) && action.payload.playerID !== first.playerID) { return state; } state = initializeDeltalog(state, action); return { ...state, G: first.G, ctx: first.ctx, plugins: first.plugins, _stateID: state._stateID + 1, _undo: [..._undo, first], _redo: _redo.slice(1), }; } case PLUGIN: { return ProcessAction(state, action, { game }); } default: { return state; } } }; } /* * Copyright 2020 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Creates the initial game state. */ function InitializeGame({ game, numPlayers, setupData, }) { game = ProcessGameConfig(game); if (!numPlayers) { numPlayers = 2; } const ctx = game.flow.ctx(numPlayers); let state = { // User managed state. G: {}, // Framework managed state. ctx, // Plugin related state. plugins: {}, }; // Run plugins over initial state. state = Setup(state, { game }); state = Enhance(state, { game, playerID: undefined }); const enhancedCtx = EnhanceCtx(state); state.G = game.setup(enhancedCtx, setupData); let initial = { ...state, // List of {G, ctx} pairs that can be undone. _undo: [], // List of {G, ctx} pairs that can be redone. _redo: [], // A monotonically non-decreasing ID to ensure that // state updates are only allowed from clients that // are at the same version that the server. _stateID: 0, }; initial = game.flow.init(initial); initial = Flush(initial, { game }); // Initialize undo stack. if (!game.disableUndo) { initial._undo = [ { G: initial.G, ctx: initial.ctx, plugins: initial.plugins, }, ]; } return initial; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class Transport { constructor({ store, gameName, playerID, matchID, credentials, numPlayers, }) { this.store = store; this.gameName = gameName || 'default'; this.playerID = playerID || null; this.matchID = matchID || 'default'; this.credentials = credentials; this.numPlayers = numPlayers || 2; } } /** * This class doesn’t do anything, but simplifies the client class by providing * dummy functions to call, so we don’t need to mock them in the client. */ class DummyImpl extends Transport { connect() { } disconnect() { } onAction() { } onChatMessage() { } subscribe() { } subscribeChatMessage() { } subscribeMatchData() { } updateCredentials() { } updateMatchID() { } updatePlayerID() { } } const DummyTransport = (opts) => new DummyImpl(opts); const subscriber_queue = []; /** * Create a `Writable` store that allows both updating and reading by subscription. * @param {*=}value initial value * @param {StartStopNotifier=}start start and stop notifications for subscriptions */ function writable(value, start = noop) { let stop; const subscribers = []; function set(new_value) { if (safe_not_equal(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (let i = 0; i < subscribers.length; i += 1) { const s = subscribers[i]; s[1](); subscriber_queue.push(s, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } function update(fn) { set(fn(value)); } function subscribe(run, invalidate = noop) { const subscriber = [run, invalidate]; subscribers.push(subscriber); if (subscribers.length === 1) { stop = start(set) || noop; } run(value); return () => { const index = subscribers.indexOf(subscriber); if (index !== -1) { subscribers.splice(index, 1); } if (subscribers.length === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; } function cubicOut(t) { const f = t - 1.0; return f * f * f + 1.0; } function fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 }) { const style = getComputedStyle(node); const target_opacity = +style.opacity; const transform = style.transform === 'none' ? '' : style.transform; const od = target_opacity * (1 - opacity); return { delay, duration, easing, css: (t, u) => ` transform: ${transform} translate(${(1 - t) * x}px, ${(1 - t) * y}px); opacity: ${target_opacity - (od * u)}` }; } /* src/client/debug/Menu.svelte generated by Svelte v3.24.0 */ function add_css() { var style = element("style"); style.id = "svelte-14p9tpy-style"; style.textContent = ".menu.svelte-14p9tpy{display:flex;margin-top:-10px;flex-direction:row-reverse;border:1px solid #ccc;border-radius:5px 5px 0 0;height:25px;line-height:25px;margin-right:-500px;transform-origin:bottom right;transform:rotate(-90deg) translate(0, -500px)}.menu-item.svelte-14p9tpy{line-height:25px;cursor:pointer;border:0;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-14p9tpy:first-child{border-radius:0 5px 0 0}.menu-item.svelte-14p9tpy:last-child{border-radius:5px 0 0 0}.menu-item.active.svelte-14p9tpy{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-14p9tpy:hover,.menu-item.svelte-14p9tpy:focus{background:#eee;color:#555}"; append(document.head, style); } function get_each_context(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[4] = list[i][0]; child_ctx[5] = list[i][1].label; return child_ctx; } // (57:2) {#each Object.entries(panes) as [key, {label} function create_each_block(ctx) { let button; let t0_value = /*label*/ ctx[5] + ""; let t0; let t1; let mounted; let dispose; function click_handler(...args) { return /*click_handler*/ ctx[3](/*key*/ ctx[4], ...args); } return { c() { button = element("button"); t0 = text(t0_value); t1 = space(); attr(button, "class", "menu-item svelte-14p9tpy"); toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]); }, m(target, anchor) { insert(target, button, anchor); append(button, t0); append(button, t1); if (!mounted) { dispose = listen(button, "click", click_handler); mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if (dirty & /*panes*/ 2 && t0_value !== (t0_value = /*label*/ ctx[5] + "")) set_data(t0, t0_value); if (dirty & /*pane, Object, panes*/ 3) { toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]); } }, d(detaching) { if (detaching) detach(button); mounted = false; dispose(); } }; } function create_fragment(ctx) { let nav; let each_value = Object.entries(/*panes*/ ctx[1]); let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i)); } return { c() { nav = element("nav"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(nav, "class", "menu svelte-14p9tpy"); }, m(target, anchor) { insert(target, nav, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(nav, null); } }, p(ctx, [dirty]) { if (dirty & /*pane, Object, panes, dispatch*/ 7) { each_value = Object.entries(/*panes*/ ctx[1]); let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); } else { each_blocks[i] = create_each_block(child_ctx); each_blocks[i].c(); each_blocks[i].m(nav, null); } } for (; i < each_blocks.length; i += 1) { each_blocks[i].d(1); } each_blocks.length = each_value.length; } }, i: noop, o: noop, d(detaching) { if (detaching) detach(nav); destroy_each(each_blocks, detaching); } }; } function instance($$self, $$props, $$invalidate) { let { pane } = $$props; let { panes } = $$props; const dispatch = createEventDispatcher(); const click_handler = key => dispatch("change", key); $$self.$set = $$props => { if ("pane" in $$props) $$invalidate(0, pane = $$props.pane); if ("panes" in $$props) $$invalidate(1, panes = $$props.panes); }; return [pane, panes, dispatch, click_handler]; } class Menu extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-14p9tpy-style")) add_css(); init(this, options, instance, create_fragment, safe_not_equal, { pane: 0, panes: 1 }); } } var contextKey = {}; /* node_modules/svelte-json-tree-auto/src/JSONArrow.svelte generated by Svelte v3.24.0 */ function add_css$1() { var style = element("style"); style.id = "svelte-1vyml86-style"; style.textContent = ".container.svelte-1vyml86{display:inline-block;cursor:pointer;transform:translate(calc(0px - var(--li-identation)), -50%);position:absolute;top:50%;padding-right:100%}.arrow.svelte-1vyml86{transform-origin:25% 50%;position:relative;line-height:1.1em;font-size:0.75em;margin-left:0;transition:150ms;color:var(--arrow-sign);user-select:none;font-family:'Courier New', Courier, monospace}.expanded.svelte-1vyml86{transform:rotateZ(90deg) translateX(-3px)}"; append(document.head, style); } function create_fragment$1(ctx) { let div1; let div0; let mounted; let dispose; return { c() { div1 = element("div"); div0 = element("div"); div0.textContent = `${"▶"}`; attr(div0, "class", "arrow svelte-1vyml86"); toggle_class(div0, "expanded", /*expanded*/ ctx[0]); attr(div1, "class", "container svelte-1vyml86"); }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); if (!mounted) { dispose = listen(div1, "click", /*click_handler*/ ctx[1]); mounted = true; } }, p(ctx, [dirty]) { if (dirty & /*expanded*/ 1) { toggle_class(div0, "expanded", /*expanded*/ ctx[0]); } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div1); mounted = false; dispose(); } }; } function instance$1($$self, $$props, $$invalidate) { let { expanded } = $$props; function click_handler(event) { bubble($$self, event); } $$self.$set = $$props => { if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded); }; return [expanded, click_handler]; } class JSONArrow extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1vyml86-style")) add_css$1(); init(this, options, instance$1, create_fragment$1, safe_not_equal, { expanded: 0 }); } } /* node_modules/svelte-json-tree-auto/src/JSONKey.svelte generated by Svelte v3.24.0 */ function add_css$2() { var style = element("style"); style.id = "svelte-1vlbacg-style"; style.textContent = "label.svelte-1vlbacg{display:inline-block;color:var(--label-color);padding:0}.spaced.svelte-1vlbacg{padding-right:var(--li-colon-space)}"; append(document.head, style); } // (16:0) {#if showKey && key} function create_if_block(ctx) { let label; let span; let t0; let t1; let mounted; let dispose; return { c() { label = element("label"); span = element("span"); t0 = text(/*key*/ ctx[0]); t1 = text(/*colon*/ ctx[2]); attr(label, "class", "svelte-1vlbacg"); toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]); }, m(target, anchor) { insert(target, label, anchor); append(label, span); append(span, t0); append(span, t1); if (!mounted) { dispose = listen(label, "click", /*click_handler*/ ctx[5]); mounted = true; } }, p(ctx, dirty) { if (dirty & /*key*/ 1) set_data(t0, /*key*/ ctx[0]); if (dirty & /*colon*/ 4) set_data(t1, /*colon*/ ctx[2]); if (dirty & /*isParentExpanded*/ 2) { toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]); } }, d(detaching) { if (detaching) detach(label); mounted = false; dispose(); } }; } function create_fragment$2(ctx) { let if_block_anchor; let if_block = /*showKey*/ ctx[3] && /*key*/ ctx[0] && create_if_block(ctx); return { c() { if (if_block) if_block.c(); if_block_anchor = empty(); }, m(target, anchor) { if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); }, p(ctx, [dirty]) { if (/*showKey*/ ctx[3] && /*key*/ ctx[0]) { if (if_block) { if_block.p(ctx, dirty); } else { if_block = create_if_block(ctx); if_block.c(); if_block.m(if_block_anchor.parentNode, if_block_anchor); } } else if (if_block) { if_block.d(1); if_block = null; } }, i: noop, o: noop, d(detaching) { if (if_block) if_block.d(detaching); if (detaching) detach(if_block_anchor); } }; } function instance$2($$self, $$props, $$invalidate) { let { key } = $$props, { isParentExpanded } = $$props, { isParentArray = false } = $$props, { colon = ":" } = $$props; function click_handler(event) { bubble($$self, event); } $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray); if ("colon" in $$props) $$invalidate(2, colon = $$props.colon); }; let showKey; $$self.$$.update = () => { if ($$self.$$.dirty & /*isParentExpanded, isParentArray, key*/ 19) { $: $$invalidate(3, showKey = isParentExpanded || !isParentArray || key != +key); } }; return [key, isParentExpanded, colon, showKey, isParentArray, click_handler]; } class JSONKey extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1vlbacg-style")) add_css$2(); init(this, options, instance$2, create_fragment$2, safe_not_equal, { key: 0, isParentExpanded: 1, isParentArray: 4, colon: 2 }); } } /* node_modules/svelte-json-tree-auto/src/JSONNested.svelte generated by Svelte v3.24.0 */ function add_css$3() { var style = element("style"); style.id = "svelte-rwxv37-style"; style.textContent = "label.svelte-rwxv37{display:inline-block}.indent.svelte-rwxv37{padding-left:var(--li-identation)}.collapse.svelte-rwxv37{--li-display:inline;display:inline;font-style:italic}.comma.svelte-rwxv37{margin-left:-0.5em;margin-right:0.5em}label.svelte-rwxv37{position:relative}"; append(document.head, style); } function get_each_context$1(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[12] = list[i]; child_ctx[20] = i; return child_ctx; } // (57:4) {#if expandable && isParentExpanded} function create_if_block_3(ctx) { let jsonarrow; let current; jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } }); jsonarrow.$on("click", /*toggleExpand*/ ctx[15]); return { c() { create_component(jsonarrow.$$.fragment); }, m(target, anchor) { mount_component(jsonarrow, target, anchor); current = true; }, p(ctx, dirty) { const jsonarrow_changes = {}; if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0]; jsonarrow.$set(jsonarrow_changes); }, i(local) { if (current) return; transition_in(jsonarrow.$$.fragment, local); current = true; }, o(local) { transition_out(jsonarrow.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonarrow, detaching); } }; } // (75:4) {:else} function create_else_block(ctx) { let span; return { c() { span = element("span"); span.textContent = "…"; }, m(target, anchor) { insert(target, span, anchor); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) detach(span); } }; } // (63:4) {#if isParentExpanded} function create_if_block$1(ctx) { let ul; let t; let current; let mounted; let dispose; let each_value = /*slicedKeys*/ ctx[13]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); let if_block = /*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length && create_if_block_1(); return { c() { ul = element("ul"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } t = space(); if (if_block) if_block.c(); attr(ul, "class", "svelte-rwxv37"); toggle_class(ul, "collapse", !/*expanded*/ ctx[0]); }, m(target, anchor) { insert(target, ul, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(ul, null); } append(ul, t); if (if_block) if_block.m(ul, null); current = true; if (!mounted) { dispose = listen(ul, "click", /*expand*/ ctx[16]); mounted = true; } }, p(ctx, dirty) { if (dirty & /*expanded, previewKeys, getKey, slicedKeys, isArray, getValue, getPreviewValue*/ 10129) { each_value = /*slicedKeys*/ ctx[13]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$1(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$1(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(ul, t); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } if (/*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length) { if (if_block) ; else { if_block = create_if_block_1(); if_block.c(); if_block.m(ul, null); } } else if (if_block) { if_block.d(1); if_block = null; } if (dirty & /*expanded*/ 1) { toggle_class(ul, "collapse", !/*expanded*/ ctx[0]); } }, i(local) { if (current) return; for (let i = 0; i < each_value.length; i += 1) { transition_in(each_blocks[i]); } current = true; }, o(local) { each_blocks = each_blocks.filter(Boolean); for (let i = 0; i < each_blocks.length; i += 1) { transition_out(each_blocks[i]); } current = false; }, d(detaching) { if (detaching) detach(ul); destroy_each(each_blocks, detaching); if (if_block) if_block.d(); mounted = false; dispose(); } }; } // (67:10) {#if !expanded && index < previewKeys.length - 1} function create_if_block_2(ctx) { let span; return { c() { span = element("span"); span.textContent = ","; attr(span, "class", "comma svelte-rwxv37"); }, m(target, anchor) { insert(target, span, anchor); }, d(detaching) { if (detaching) detach(span); } }; } // (65:8) {#each slicedKeys as key, index} function create_each_block$1(ctx) { let jsonnode; let t; let if_block_anchor; let current; jsonnode = new JSONNode({ props: { key: /*getKey*/ ctx[8](/*key*/ ctx[12]), isParentExpanded: /*expanded*/ ctx[0], isParentArray: /*isArray*/ ctx[4], value: /*expanded*/ ctx[0] ? /*getValue*/ ctx[9](/*key*/ ctx[12]) : /*getPreviewValue*/ ctx[10](/*key*/ ctx[12]) } }); let if_block = !/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1 && create_if_block_2(); return { c() { create_component(jsonnode.$$.fragment); t = space(); if (if_block) if_block.c(); if_block_anchor = empty(); }, m(target, anchor) { mount_component(jsonnode, target, anchor); insert(target, t, anchor); if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); current = true; }, p(ctx, dirty) { const jsonnode_changes = {}; if (dirty & /*getKey, slicedKeys*/ 8448) jsonnode_changes.key = /*getKey*/ ctx[8](/*key*/ ctx[12]); if (dirty & /*expanded*/ 1) jsonnode_changes.isParentExpanded = /*expanded*/ ctx[0]; if (dirty & /*isArray*/ 16) jsonnode_changes.isParentArray = /*isArray*/ ctx[4]; if (dirty & /*expanded, getValue, slicedKeys, getPreviewValue*/ 9729) jsonnode_changes.value = /*expanded*/ ctx[0] ? /*getValue*/ ctx[9](/*key*/ ctx[12]) : /*getPreviewValue*/ ctx[10](/*key*/ ctx[12]); jsonnode.$set(jsonnode_changes); if (!/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1) { if (if_block) ; else { if_block = create_if_block_2(); if_block.c(); if_block.m(if_block_anchor.parentNode, if_block_anchor); } } else if (if_block) { if_block.d(1); if_block = null; } }, i(local) { if (current) return; transition_in(jsonnode.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnode.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonnode, detaching); if (detaching) detach(t); if (if_block) if_block.d(detaching); if (detaching) detach(if_block_anchor); } }; } // (71:8) {#if slicedKeys.length < previewKeys.length } function create_if_block_1(ctx) { let span; return { c() { span = element("span"); span.textContent = "…"; }, m(target, anchor) { insert(target, span, anchor); }, d(detaching) { if (detaching) detach(span); } }; } function create_fragment$3(ctx) { let li; let label_1; let t0; let jsonkey; let t1; let span1; let span0; let t2; let t3; let t4; let current_block_type_index; let if_block1; let t5; let span2; let t6; let current; let mounted; let dispose; let if_block0 = /*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2] && create_if_block_3(ctx); jsonkey = new JSONKey({ props: { key: /*key*/ ctx[12], colon: /*context*/ ctx[14].colon, isParentExpanded: /*isParentExpanded*/ ctx[2], isParentArray: /*isParentArray*/ ctx[3] } }); jsonkey.$on("click", /*toggleExpand*/ ctx[15]); const if_block_creators = [create_if_block$1, create_else_block]; const if_blocks = []; function select_block_type(ctx, dirty) { if (/*isParentExpanded*/ ctx[2]) return 0; return 1; } current_block_type_index = select_block_type(ctx); if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); return { c() { li = element("li"); label_1 = element("label"); if (if_block0) if_block0.c(); t0 = space(); create_component(jsonkey.$$.fragment); t1 = space(); span1 = element("span"); span0 = element("span"); t2 = text(/*label*/ ctx[1]); t3 = text(/*bracketOpen*/ ctx[5]); t4 = space(); if_block1.c(); t5 = space(); span2 = element("span"); t6 = text(/*bracketClose*/ ctx[6]); attr(label_1, "class", "svelte-rwxv37"); attr(li, "class", "svelte-rwxv37"); toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]); }, m(target, anchor) { insert(target, li, anchor); append(li, label_1); if (if_block0) if_block0.m(label_1, null); append(label_1, t0); mount_component(jsonkey, label_1, null); append(label_1, t1); append(label_1, span1); append(span1, span0); append(span0, t2); append(span1, t3); append(li, t4); if_blocks[current_block_type_index].m(li, null); append(li, t5); append(li, span2); append(span2, t6); current = true; if (!mounted) { dispose = listen(span1, "click", /*toggleExpand*/ ctx[15]); mounted = true; } }, p(ctx, [dirty]) { if (/*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2]) { if (if_block0) { if_block0.p(ctx, dirty); if (dirty & /*expandable, isParentExpanded*/ 2052) { transition_in(if_block0, 1); } } else { if_block0 = create_if_block_3(ctx); if_block0.c(); transition_in(if_block0, 1); if_block0.m(label_1, t0); } } else if (if_block0) { group_outros(); transition_out(if_block0, 1, 1, () => { if_block0 = null; }); check_outros(); } const jsonkey_changes = {}; if (dirty & /*key*/ 4096) jsonkey_changes.key = /*key*/ ctx[12]; if (dirty & /*isParentExpanded*/ 4) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[2]; if (dirty & /*isParentArray*/ 8) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[3]; jsonkey.$set(jsonkey_changes); if (!current || dirty & /*label*/ 2) set_data(t2, /*label*/ ctx[1]); if (!current || dirty & /*bracketOpen*/ 32) set_data(t3, /*bracketOpen*/ ctx[5]); let previous_block_index = current_block_type_index; current_block_type_index = select_block_type(ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(ctx, dirty); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block1 = if_blocks[current_block_type_index]; if (!if_block1) { if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block1.c(); } transition_in(if_block1, 1); if_block1.m(li, t5); } if (!current || dirty & /*bracketClose*/ 64) set_data(t6, /*bracketClose*/ ctx[6]); if (dirty & /*isParentExpanded*/ 4) { toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]); } }, i(local) { if (current) return; transition_in(if_block0); transition_in(jsonkey.$$.fragment, local); transition_in(if_block1); current = true; }, o(local) { transition_out(if_block0); transition_out(jsonkey.$$.fragment, local); transition_out(if_block1); current = false; }, d(detaching) { if (detaching) detach(li); if (if_block0) if_block0.d(); destroy_component(jsonkey); if_blocks[current_block_type_index].d(); mounted = false; dispose(); } }; } function instance$3($$self, $$props, $$invalidate) { let { key } = $$props, { keys } = $$props, { colon = ":" } = $$props, { label = "" } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props, { isArray = false } = $$props, { bracketOpen } = $$props, { bracketClose } = $$props; let { previewKeys = keys } = $$props; let { getKey = key => key } = $$props; let { getValue = key => key } = $$props; let { getPreviewValue = getValue } = $$props; let { expanded = false } = $$props, { expandable = true } = $$props; const context = getContext(contextKey); setContext(contextKey, { ...context, colon }); function toggleExpand() { $$invalidate(0, expanded = !expanded); } function expand() { $$invalidate(0, expanded = true); } $$self.$set = $$props => { if ("key" in $$props) $$invalidate(12, key = $$props.key); if ("keys" in $$props) $$invalidate(17, keys = $$props.keys); if ("colon" in $$props) $$invalidate(18, colon = $$props.colon); if ("label" in $$props) $$invalidate(1, label = $$props.label); if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray); if ("isArray" in $$props) $$invalidate(4, isArray = $$props.isArray); if ("bracketOpen" in $$props) $$invalidate(5, bracketOpen = $$props.bracketOpen); if ("bracketClose" in $$props) $$invalidate(6, bracketClose = $$props.bracketClose); if ("previewKeys" in $$props) $$invalidate(7, previewKeys = $$props.previewKeys); if ("getKey" in $$props) $$invalidate(8, getKey = $$props.getKey); if ("getValue" in $$props) $$invalidate(9, getValue = $$props.getValue); if ("getPreviewValue" in $$props) $$invalidate(10, getPreviewValue = $$props.getPreviewValue); if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded); if ("expandable" in $$props) $$invalidate(11, expandable = $$props.expandable); }; let slicedKeys; $$self.$$.update = () => { if ($$self.$$.dirty & /*isParentExpanded*/ 4) { $: if (!isParentExpanded) { $$invalidate(0, expanded = false); } } if ($$self.$$.dirty & /*expanded, keys, previewKeys*/ 131201) { $: $$invalidate(13, slicedKeys = expanded ? keys : previewKeys.slice(0, 5)); } }; return [ expanded, label, isParentExpanded, isParentArray, isArray, bracketOpen, bracketClose, previewKeys, getKey, getValue, getPreviewValue, expandable, key, slicedKeys, context, toggleExpand, expand, keys, colon ]; } class JSONNested extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-rwxv37-style")) add_css$3(); init(this, options, instance$3, create_fragment$3, safe_not_equal, { key: 12, keys: 17, colon: 18, label: 1, isParentExpanded: 2, isParentArray: 3, isArray: 4, bracketOpen: 5, bracketClose: 6, previewKeys: 7, getKey: 8, getValue: 9, getPreviewValue: 10, expanded: 0, expandable: 11 }); } } /* node_modules/svelte-json-tree-auto/src/JSONObjectNode.svelte generated by Svelte v3.24.0 */ function create_fragment$4(ctx) { let jsonnested; let current; jsonnested = new JSONNested({ props: { key: /*key*/ ctx[0], expanded: /*expanded*/ ctx[4], isParentExpanded: /*isParentExpanded*/ ctx[1], isParentArray: /*isParentArray*/ ctx[2], keys: /*keys*/ ctx[5], previewKeys: /*keys*/ ctx[5], getValue: /*getValue*/ ctx[6], label: "" + (/*nodeType*/ ctx[3] + " "), bracketOpen: "{", bracketClose: "}" } }); return { c() { create_component(jsonnested.$$.fragment); }, m(target, anchor) { mount_component(jsonnested, target, anchor); current = true; }, p(ctx, [dirty]) { const jsonnested_changes = {}; if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0]; if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4]; if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1]; if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2]; if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5]; if (dirty & /*keys*/ 32) jsonnested_changes.previewKeys = /*keys*/ ctx[5]; if (dirty & /*nodeType*/ 8) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + " "); jsonnested.$set(jsonnested_changes); }, i(local) { if (current) return; transition_in(jsonnested.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnested.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonnested, detaching); } }; } function instance$4($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props, { nodeType } = $$props; let { expanded = true } = $$props; function getValue(key) { return value[key]; } $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(7, value = $$props.value); if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray); if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType); if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded); }; let keys; $$self.$$.update = () => { if ($$self.$$.dirty & /*value*/ 128) { $: $$invalidate(5, keys = Object.getOwnPropertyNames(value)); } }; return [ key, isParentExpanded, isParentArray, nodeType, expanded, keys, getValue, value ]; } class JSONObjectNode extends SvelteComponent { constructor(options) { super(); init(this, options, instance$4, create_fragment$4, safe_not_equal, { key: 0, value: 7, isParentExpanded: 1, isParentArray: 2, nodeType: 3, expanded: 4 }); } } /* node_modules/svelte-json-tree-auto/src/JSONArrayNode.svelte generated by Svelte v3.24.0 */ function create_fragment$5(ctx) { let jsonnested; let current; jsonnested = new JSONNested({ props: { key: /*key*/ ctx[0], expanded: /*expanded*/ ctx[4], isParentExpanded: /*isParentExpanded*/ ctx[2], isParentArray: /*isParentArray*/ ctx[3], isArray: true, keys: /*keys*/ ctx[5], previewKeys: /*previewKeys*/ ctx[6], getValue: /*getValue*/ ctx[7], label: "Array(" + /*value*/ ctx[1].length + ")", bracketOpen: "[", bracketClose: "]" } }); return { c() { create_component(jsonnested.$$.fragment); }, m(target, anchor) { mount_component(jsonnested, target, anchor); current = true; }, p(ctx, [dirty]) { const jsonnested_changes = {}; if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0]; if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4]; if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2]; if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3]; if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5]; if (dirty & /*previewKeys*/ 64) jsonnested_changes.previewKeys = /*previewKeys*/ ctx[6]; if (dirty & /*value*/ 2) jsonnested_changes.label = "Array(" + /*value*/ ctx[1].length + ")"; jsonnested.$set(jsonnested_changes); }, i(local) { if (current) return; transition_in(jsonnested.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnested.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonnested, detaching); } }; } function instance$5($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props; let { expanded = JSON.stringify(value).length < 1024 } = $$props; const filteredKey = new Set(["length"]); function getValue(key) { return value[key]; } $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(1, value = $$props.value); if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray); if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded); }; let keys; let previewKeys; $$self.$$.update = () => { if ($$self.$$.dirty & /*value*/ 2) { $: $$invalidate(5, keys = Object.getOwnPropertyNames(value)); } if ($$self.$$.dirty & /*keys*/ 32) { $: $$invalidate(6, previewKeys = keys.filter(key => !filteredKey.has(key))); } }; return [ key, value, isParentExpanded, isParentArray, expanded, keys, previewKeys, getValue ]; } class JSONArrayNode extends SvelteComponent { constructor(options) { super(); init(this, options, instance$5, create_fragment$5, safe_not_equal, { key: 0, value: 1, isParentExpanded: 2, isParentArray: 3, expanded: 4 }); } } /* node_modules/svelte-json-tree-auto/src/JSONIterableArrayNode.svelte generated by Svelte v3.24.0 */ function create_fragment$6(ctx) { let jsonnested; let current; jsonnested = new JSONNested({ props: { key: /*key*/ ctx[0], isParentExpanded: /*isParentExpanded*/ ctx[1], isParentArray: /*isParentArray*/ ctx[2], keys: /*keys*/ ctx[4], getKey, getValue, isArray: true, label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"), bracketOpen: "{", bracketClose: "}" } }); return { c() { create_component(jsonnested.$$.fragment); }, m(target, anchor) { mount_component(jsonnested, target, anchor); current = true; }, p(ctx, [dirty]) { const jsonnested_changes = {}; if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0]; if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1]; if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2]; if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4]; if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"); jsonnested.$set(jsonnested_changes); }, i(local) { if (current) return; transition_in(jsonnested.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnested.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonnested, detaching); } }; } function getKey(key) { return String(key[0]); } function getValue(key) { return key[1]; } function instance$6($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props, { nodeType } = $$props; let keys = []; $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(5, value = $$props.value); if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray); if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*value*/ 32) { $: { let result = []; let i = 0; for (const entry of value) { result.push([i++, entry]); } $$invalidate(4, keys = result); } } }; return [key, isParentExpanded, isParentArray, nodeType, keys, value]; } class JSONIterableArrayNode extends SvelteComponent { constructor(options) { super(); init(this, options, instance$6, create_fragment$6, safe_not_equal, { key: 0, value: 5, isParentExpanded: 1, isParentArray: 2, nodeType: 3 }); } } class MapEntry { constructor(key, value) { this.key = key; this.value = value; } } /* node_modules/svelte-json-tree-auto/src/JSONIterableMapNode.svelte generated by Svelte v3.24.0 */ function create_fragment$7(ctx) { let jsonnested; let current; jsonnested = new JSONNested({ props: { key: /*key*/ ctx[0], isParentExpanded: /*isParentExpanded*/ ctx[1], isParentArray: /*isParentArray*/ ctx[2], keys: /*keys*/ ctx[4], getKey: getKey$1, getValue: getValue$1, label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"), colon: "", bracketOpen: "{", bracketClose: "}" } }); return { c() { create_component(jsonnested.$$.fragment); }, m(target, anchor) { mount_component(jsonnested, target, anchor); current = true; }, p(ctx, [dirty]) { const jsonnested_changes = {}; if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0]; if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1]; if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2]; if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4]; if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"); jsonnested.$set(jsonnested_changes); }, i(local) { if (current) return; transition_in(jsonnested.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnested.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonnested, detaching); } }; } function getKey$1(entry) { return entry[0]; } function getValue$1(entry) { return entry[1]; } function instance$7($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props, { nodeType } = $$props; let keys = []; $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(5, value = $$props.value); if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray); if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*value*/ 32) { $: { let result = []; let i = 0; for (const entry of value) { result.push([i++, new MapEntry(entry[0], entry[1])]); } $$invalidate(4, keys = result); } } }; return [key, isParentExpanded, isParentArray, nodeType, keys, value]; } class JSONIterableMapNode extends SvelteComponent { constructor(options) { super(); init(this, options, instance$7, create_fragment$7, safe_not_equal, { key: 0, value: 5, isParentExpanded: 1, isParentArray: 2, nodeType: 3 }); } } /* node_modules/svelte-json-tree-auto/src/JSONMapEntryNode.svelte generated by Svelte v3.24.0 */ function create_fragment$8(ctx) { let jsonnested; let current; jsonnested = new JSONNested({ props: { expanded: /*expanded*/ ctx[4], isParentExpanded: /*isParentExpanded*/ ctx[2], isParentArray: /*isParentArray*/ ctx[3], key: /*isParentExpanded*/ ctx[2] ? String(/*key*/ ctx[0]) : /*value*/ ctx[1].key, keys: /*keys*/ ctx[5], getValue: /*getValue*/ ctx[6], label: /*isParentExpanded*/ ctx[2] ? "Entry " : "=> ", bracketOpen: "{", bracketClose: "}" } }); return { c() { create_component(jsonnested.$$.fragment); }, m(target, anchor) { mount_component(jsonnested, target, anchor); current = true; }, p(ctx, [dirty]) { const jsonnested_changes = {}; if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4]; if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2]; if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3]; if (dirty & /*isParentExpanded, key, value*/ 7) jsonnested_changes.key = /*isParentExpanded*/ ctx[2] ? String(/*key*/ ctx[0]) : /*value*/ ctx[1].key; if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.label = /*isParentExpanded*/ ctx[2] ? "Entry " : "=> "; jsonnested.$set(jsonnested_changes); }, i(local) { if (current) return; transition_in(jsonnested.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnested.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonnested, detaching); } }; } function instance$8($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props; let { expanded = false } = $$props; const keys = ["key", "value"]; function getValue(key) { return value[key]; } $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(1, value = $$props.value); if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray); if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded); }; return [key, value, isParentExpanded, isParentArray, expanded, keys, getValue]; } class JSONMapEntryNode extends SvelteComponent { constructor(options) { super(); init(this, options, instance$8, create_fragment$8, safe_not_equal, { key: 0, value: 1, isParentExpanded: 2, isParentArray: 3, expanded: 4 }); } } /* node_modules/svelte-json-tree-auto/src/JSONValueNode.svelte generated by Svelte v3.24.0 */ function add_css$4() { var style = element("style"); style.id = "svelte-3bjyvl-style"; style.textContent = "li.svelte-3bjyvl{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-3bjyvl{padding-left:var(--li-identation)}.String.svelte-3bjyvl{color:var(--string-color)}.Date.svelte-3bjyvl{color:var(--date-color)}.Number.svelte-3bjyvl{color:var(--number-color)}.Boolean.svelte-3bjyvl{color:var(--boolean-color)}.Null.svelte-3bjyvl{color:var(--null-color)}.Undefined.svelte-3bjyvl{color:var(--undefined-color)}.Function.svelte-3bjyvl{color:var(--function-color);font-style:italic}.Symbol.svelte-3bjyvl{color:var(--symbol-color)}"; append(document.head, style); } function create_fragment$9(ctx) { let li; let jsonkey; let t0; let span; let t1_value = (/*valueGetter*/ ctx[2] ? /*valueGetter*/ ctx[2](/*value*/ ctx[1]) : /*value*/ ctx[1]) + ""; let t1; let span_class_value; let current; jsonkey = new JSONKey({ props: { key: /*key*/ ctx[0], colon: /*colon*/ ctx[6], isParentExpanded: /*isParentExpanded*/ ctx[3], isParentArray: /*isParentArray*/ ctx[4] } }); return { c() { li = element("li"); create_component(jsonkey.$$.fragment); t0 = space(); span = element("span"); t1 = text(t1_value); attr(span, "class", span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl")); attr(li, "class", "svelte-3bjyvl"); toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]); }, m(target, anchor) { insert(target, li, anchor); mount_component(jsonkey, li, null); append(li, t0); append(li, span); append(span, t1); current = true; }, p(ctx, [dirty]) { const jsonkey_changes = {}; if (dirty & /*key*/ 1) jsonkey_changes.key = /*key*/ ctx[0]; if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3]; if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4]; jsonkey.$set(jsonkey_changes); if ((!current || dirty & /*valueGetter, value*/ 6) && t1_value !== (t1_value = (/*valueGetter*/ ctx[2] ? /*valueGetter*/ ctx[2](/*value*/ ctx[1]) : /*value*/ ctx[1]) + "")) set_data(t1, t1_value); if (!current || dirty & /*nodeType*/ 32 && span_class_value !== (span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"))) { attr(span, "class", span_class_value); } if (dirty & /*isParentExpanded*/ 8) { toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]); } }, i(local) { if (current) return; transition_in(jsonkey.$$.fragment, local); current = true; }, o(local) { transition_out(jsonkey.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(li); destroy_component(jsonkey); } }; } function instance$9($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { valueGetter = null } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props, { nodeType } = $$props; const { colon } = getContext(contextKey); $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(1, value = $$props.value); if ("valueGetter" in $$props) $$invalidate(2, valueGetter = $$props.valueGetter); if ("isParentExpanded" in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray); if ("nodeType" in $$props) $$invalidate(5, nodeType = $$props.nodeType); }; return [key, value, valueGetter, isParentExpanded, isParentArray, nodeType, colon]; } class JSONValueNode extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-3bjyvl-style")) add_css$4(); init(this, options, instance$9, create_fragment$9, safe_not_equal, { key: 0, value: 1, valueGetter: 2, isParentExpanded: 3, isParentArray: 4, nodeType: 5 }); } } /* node_modules/svelte-json-tree-auto/src/ErrorNode.svelte generated by Svelte v3.24.0 */ function add_css$5() { var style = element("style"); style.id = "svelte-1ca3gb2-style"; style.textContent = "li.svelte-1ca3gb2{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-1ca3gb2{padding-left:var(--li-identation)}.collapse.svelte-1ca3gb2{--li-display:inline;display:inline;font-style:italic}"; append(document.head, style); } function get_each_context$2(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[8] = list[i]; child_ctx[10] = i; return child_ctx; } // (40:2) {#if isParentExpanded} function create_if_block_2$1(ctx) { let jsonarrow; let current; jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } }); jsonarrow.$on("click", /*toggleExpand*/ ctx[7]); return { c() { create_component(jsonarrow.$$.fragment); }, m(target, anchor) { mount_component(jsonarrow, target, anchor); current = true; }, p(ctx, dirty) { const jsonarrow_changes = {}; if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0]; jsonarrow.$set(jsonarrow_changes); }, i(local) { if (current) return; transition_in(jsonarrow.$$.fragment, local); current = true; }, o(local) { transition_out(jsonarrow.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonarrow, detaching); } }; } // (45:2) {#if isParentExpanded} function create_if_block$2(ctx) { let ul; let current; let if_block = /*expanded*/ ctx[0] && create_if_block_1$1(ctx); return { c() { ul = element("ul"); if (if_block) if_block.c(); attr(ul, "class", "svelte-1ca3gb2"); toggle_class(ul, "collapse", !/*expanded*/ ctx[0]); }, m(target, anchor) { insert(target, ul, anchor); if (if_block) if_block.m(ul, null); current = true; }, p(ctx, dirty) { if (/*expanded*/ ctx[0]) { if (if_block) { if_block.p(ctx, dirty); if (dirty & /*expanded*/ 1) { transition_in(if_block, 1); } } else { if_block = create_if_block_1$1(ctx); if_block.c(); transition_in(if_block, 1); if_block.m(ul, null); } } else if (if_block) { group_outros(); transition_out(if_block, 1, 1, () => { if_block = null; }); check_outros(); } if (dirty & /*expanded*/ 1) { toggle_class(ul, "collapse", !/*expanded*/ ctx[0]); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (detaching) detach(ul); if (if_block) if_block.d(); } }; } // (47:6) {#if expanded} function create_if_block_1$1(ctx) { let jsonnode; let t0; let li; let jsonkey; let t1; let span; let current; jsonnode = new JSONNode({ props: { key: "message", value: /*value*/ ctx[2].message } }); jsonkey = new JSONKey({ props: { key: "stack", colon: ":", isParentExpanded: /*isParentExpanded*/ ctx[3] } }); let each_value = /*stack*/ ctx[5]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i)); } return { c() { create_component(jsonnode.$$.fragment); t0 = space(); li = element("li"); create_component(jsonkey.$$.fragment); t1 = space(); span = element("span"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(li, "class", "svelte-1ca3gb2"); }, m(target, anchor) { mount_component(jsonnode, target, anchor); insert(target, t0, anchor); insert(target, li, anchor); mount_component(jsonkey, li, null); append(li, t1); append(li, span); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(span, null); } current = true; }, p(ctx, dirty) { const jsonnode_changes = {}; if (dirty & /*value*/ 4) jsonnode_changes.value = /*value*/ ctx[2].message; jsonnode.$set(jsonnode_changes); const jsonkey_changes = {}; if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3]; jsonkey.$set(jsonkey_changes); if (dirty & /*stack*/ 32) { each_value = /*stack*/ ctx[5]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$2(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); } else { each_blocks[i] = create_each_block$2(child_ctx); each_blocks[i].c(); each_blocks[i].m(span, null); } } for (; i < each_blocks.length; i += 1) { each_blocks[i].d(1); } each_blocks.length = each_value.length; } }, i(local) { if (current) return; transition_in(jsonnode.$$.fragment, local); transition_in(jsonkey.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnode.$$.fragment, local); transition_out(jsonkey.$$.fragment, local); current = false; }, d(detaching) { destroy_component(jsonnode, detaching); if (detaching) detach(t0); if (detaching) detach(li); destroy_component(jsonkey); destroy_each(each_blocks, detaching); } }; } // (52:12) {#each stack as line, index} function create_each_block$2(ctx) { let span; let t_value = /*line*/ ctx[8] + ""; let t; let br; return { c() { span = element("span"); t = text(t_value); br = element("br"); attr(span, "class", "svelte-1ca3gb2"); toggle_class(span, "indent", /*index*/ ctx[10] > 0); }, m(target, anchor) { insert(target, span, anchor); append(span, t); insert(target, br, anchor); }, p(ctx, dirty) { if (dirty & /*stack*/ 32 && t_value !== (t_value = /*line*/ ctx[8] + "")) set_data(t, t_value); }, d(detaching) { if (detaching) detach(span); if (detaching) detach(br); } }; } function create_fragment$a(ctx) { let li; let t0; let jsonkey; let t1; let span; let t2; let t3_value = (/*expanded*/ ctx[0] ? "" : /*value*/ ctx[2].message) + ""; let t3; let t4; let current; let mounted; let dispose; let if_block0 = /*isParentExpanded*/ ctx[3] && create_if_block_2$1(ctx); jsonkey = new JSONKey({ props: { key: /*key*/ ctx[1], colon: /*context*/ ctx[6].colon, isParentExpanded: /*isParentExpanded*/ ctx[3], isParentArray: /*isParentArray*/ ctx[4] } }); let if_block1 = /*isParentExpanded*/ ctx[3] && create_if_block$2(ctx); return { c() { li = element("li"); if (if_block0) if_block0.c(); t0 = space(); create_component(jsonkey.$$.fragment); t1 = space(); span = element("span"); t2 = text("Error: "); t3 = text(t3_value); t4 = space(); if (if_block1) if_block1.c(); attr(li, "class", "svelte-1ca3gb2"); toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]); }, m(target, anchor) { insert(target, li, anchor); if (if_block0) if_block0.m(li, null); append(li, t0); mount_component(jsonkey, li, null); append(li, t1); append(li, span); append(span, t2); append(span, t3); append(li, t4); if (if_block1) if_block1.m(li, null); current = true; if (!mounted) { dispose = listen(span, "click", /*toggleExpand*/ ctx[7]); mounted = true; } }, p(ctx, [dirty]) { if (/*isParentExpanded*/ ctx[3]) { if (if_block0) { if_block0.p(ctx, dirty); if (dirty & /*isParentExpanded*/ 8) { transition_in(if_block0, 1); } } else { if_block0 = create_if_block_2$1(ctx); if_block0.c(); transition_in(if_block0, 1); if_block0.m(li, t0); } } else if (if_block0) { group_outros(); transition_out(if_block0, 1, 1, () => { if_block0 = null; }); check_outros(); } const jsonkey_changes = {}; if (dirty & /*key*/ 2) jsonkey_changes.key = /*key*/ ctx[1]; if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3]; if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4]; jsonkey.$set(jsonkey_changes); if ((!current || dirty & /*expanded, value*/ 5) && t3_value !== (t3_value = (/*expanded*/ ctx[0] ? "" : /*value*/ ctx[2].message) + "")) set_data(t3, t3_value); if (/*isParentExpanded*/ ctx[3]) { if (if_block1) { if_block1.p(ctx, dirty); if (dirty & /*isParentExpanded*/ 8) { transition_in(if_block1, 1); } } else { if_block1 = create_if_block$2(ctx); if_block1.c(); transition_in(if_block1, 1); if_block1.m(li, null); } } else if (if_block1) { group_outros(); transition_out(if_block1, 1, 1, () => { if_block1 = null; }); check_outros(); } if (dirty & /*isParentExpanded*/ 8) { toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]); } }, i(local) { if (current) return; transition_in(if_block0); transition_in(jsonkey.$$.fragment, local); transition_in(if_block1); current = true; }, o(local) { transition_out(if_block0); transition_out(jsonkey.$$.fragment, local); transition_out(if_block1); current = false; }, d(detaching) { if (detaching) detach(li); if (if_block0) if_block0.d(); destroy_component(jsonkey); if (if_block1) if_block1.d(); mounted = false; dispose(); } }; } function instance$a($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props; let { expanded = false } = $$props; const context = getContext(contextKey); setContext(contextKey, { ...context, colon: ":" }); function toggleExpand() { $$invalidate(0, expanded = !expanded); } $$self.$set = $$props => { if ("key" in $$props) $$invalidate(1, key = $$props.key); if ("value" in $$props) $$invalidate(2, value = $$props.value); if ("isParentExpanded" in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray); if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded); }; let stack; $$self.$$.update = () => { if ($$self.$$.dirty & /*value*/ 4) { $: $$invalidate(5, stack = value.stack.split("\n")); } if ($$self.$$.dirty & /*isParentExpanded*/ 8) { $: if (!isParentExpanded) { $$invalidate(0, expanded = false); } } }; return [ expanded, key, value, isParentExpanded, isParentArray, stack, context, toggleExpand ]; } class ErrorNode extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1ca3gb2-style")) add_css$5(); init(this, options, instance$a, create_fragment$a, safe_not_equal, { key: 1, value: 2, isParentExpanded: 3, isParentArray: 4, expanded: 0 }); } } function objType(obj) { const type = Object.prototype.toString.call(obj).slice(8, -1); if (type === 'Object') { if (typeof obj[Symbol.iterator] === 'function') { return 'Iterable'; } return obj.constructor.name; } return type; } /* node_modules/svelte-json-tree-auto/src/JSONNode.svelte generated by Svelte v3.24.0 */ function create_fragment$b(ctx) { let switch_instance; let switch_instance_anchor; let current; var switch_value = /*componentType*/ ctx[5]; function switch_props(ctx) { return { props: { key: /*key*/ ctx[0], value: /*value*/ ctx[1], isParentExpanded: /*isParentExpanded*/ ctx[2], isParentArray: /*isParentArray*/ ctx[3], nodeType: /*nodeType*/ ctx[4], valueGetter: /*valueGetter*/ ctx[6] } }; } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); } return { c() { if (switch_instance) create_component(switch_instance.$$.fragment); switch_instance_anchor = empty(); }, m(target, anchor) { if (switch_instance) { mount_component(switch_instance, target, anchor); } insert(target, switch_instance_anchor, anchor); current = true; }, p(ctx, [dirty]) { const switch_instance_changes = {}; if (dirty & /*key*/ 1) switch_instance_changes.key = /*key*/ ctx[0]; if (dirty & /*value*/ 2) switch_instance_changes.value = /*value*/ ctx[1]; if (dirty & /*isParentExpanded*/ 4) switch_instance_changes.isParentExpanded = /*isParentExpanded*/ ctx[2]; if (dirty & /*isParentArray*/ 8) switch_instance_changes.isParentArray = /*isParentArray*/ ctx[3]; if (dirty & /*nodeType*/ 16) switch_instance_changes.nodeType = /*nodeType*/ ctx[4]; if (dirty & /*valueGetter*/ 64) switch_instance_changes.valueGetter = /*valueGetter*/ ctx[6]; if (switch_value !== (switch_value = /*componentType*/ ctx[5])) { if (switch_instance) { group_outros(); const old_component = switch_instance; transition_out(old_component.$$.fragment, 1, 0, () => { destroy_component(old_component, 1); }); check_outros(); } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); create_component(switch_instance.$$.fragment); transition_in(switch_instance.$$.fragment, 1); mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor); } else { switch_instance = null; } } else if (switch_value) { switch_instance.$set(switch_instance_changes); } }, i(local) { if (current) return; if (switch_instance) transition_in(switch_instance.$$.fragment, local); current = true; }, o(local) { if (switch_instance) transition_out(switch_instance.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(switch_instance_anchor); if (switch_instance) destroy_component(switch_instance, detaching); } }; } function instance$b($$self, $$props, $$invalidate) { let { key } = $$props, { value } = $$props, { isParentExpanded } = $$props, { isParentArray } = $$props; function getComponent(nodeType) { switch (nodeType) { case "Object": return JSONObjectNode; case "Error": return ErrorNode; case "Array": return JSONArrayNode; case "Iterable": case "Map": case "Set": return typeof value.set === "function" ? JSONIterableMapNode : JSONIterableArrayNode; case "MapEntry": return JSONMapEntryNode; default: return JSONValueNode; } } function getValueGetter(nodeType) { switch (nodeType) { case "Object": case "Error": case "Array": case "Iterable": case "Map": case "Set": case "MapEntry": case "Number": return undefined; case "String": return raw => `"${raw}"`; case "Boolean": return raw => raw ? "true" : "false"; case "Date": return raw => raw.toISOString(); case "Null": return () => "null"; case "Undefined": return () => "undefined"; case "Function": case "Symbol": return raw => raw.toString(); default: return () => `<${nodeType}>`; } } $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(1, value = $$props.value); if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded); if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray); }; let nodeType; let componentType; let valueGetter; $$self.$$.update = () => { if ($$self.$$.dirty & /*value*/ 2) { $: $$invalidate(4, nodeType = objType(value)); } if ($$self.$$.dirty & /*nodeType*/ 16) { $: $$invalidate(5, componentType = getComponent(nodeType)); } if ($$self.$$.dirty & /*nodeType*/ 16) { $: $$invalidate(6, valueGetter = getValueGetter(nodeType)); } }; return [ key, value, isParentExpanded, isParentArray, nodeType, componentType, valueGetter ]; } class JSONNode extends SvelteComponent { constructor(options) { super(); init(this, options, instance$b, create_fragment$b, safe_not_equal, { key: 0, value: 1, isParentExpanded: 2, isParentArray: 3 }); } } /* node_modules/svelte-json-tree-auto/src/Root.svelte generated by Svelte v3.24.0 */ function add_css$6() { var style = element("style"); style.id = "svelte-773n60-style"; style.textContent = "ul.svelte-773n60{--string-color:var(--json-tree-string-color, #cb3f41);--symbol-color:var(--json-tree-symbol-color, #cb3f41);--boolean-color:var(--json-tree-boolean-color, #112aa7);--function-color:var(--json-tree-function-color, #112aa7);--number-color:var(--json-tree-number-color, #3029cf);--label-color:var(--json-tree-label-color, #871d8f);--arrow-color:var(--json-tree-arrow-color, #727272);--null-color:var(--json-tree-null-color, #8d8d8d);--undefined-color:var(--json-tree-undefined-color, #8d8d8d);--date-color:var(--json-tree-date-color, #8d8d8d);--li-identation:var(--json-tree-li-indentation, 1em);--li-line-height:var(--json-tree-li-line-height, 1.3);--li-colon-space:0.3em;font-size:var(--json-tree-font-size, 12px);font-family:var(--json-tree-font-family, 'Courier New', Courier, monospace)}ul.svelte-773n60 li{line-height:var(--li-line-height);display:var(--li-display, list-item);list-style:none}ul.svelte-773n60,ul.svelte-773n60 ul{padding:0;margin:0}"; append(document.head, style); } function create_fragment$c(ctx) { let ul; let jsonnode; let current; jsonnode = new JSONNode({ props: { key: /*key*/ ctx[0], value: /*value*/ ctx[1], isParentExpanded: true, isParentArray: false } }); return { c() { ul = element("ul"); create_component(jsonnode.$$.fragment); attr(ul, "class", "svelte-773n60"); }, m(target, anchor) { insert(target, ul, anchor); mount_component(jsonnode, ul, null); current = true; }, p(ctx, [dirty]) { const jsonnode_changes = {}; if (dirty & /*key*/ 1) jsonnode_changes.key = /*key*/ ctx[0]; if (dirty & /*value*/ 2) jsonnode_changes.value = /*value*/ ctx[1]; jsonnode.$set(jsonnode_changes); }, i(local) { if (current) return; transition_in(jsonnode.$$.fragment, local); current = true; }, o(local) { transition_out(jsonnode.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(ul); destroy_component(jsonnode); } }; } function instance$c($$self, $$props, $$invalidate) { setContext(contextKey, {}); let { key = "" } = $$props, { value } = $$props; $$self.$set = $$props => { if ("key" in $$props) $$invalidate(0, key = $$props.key); if ("value" in $$props) $$invalidate(1, value = $$props.value); }; return [key, value]; } class Root extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-773n60-style")) add_css$6(); init(this, options, instance$c, create_fragment$c, safe_not_equal, { key: 0, value: 1 }); } } /* src/client/debug/main/ClientSwitcher.svelte generated by Svelte v3.24.0 */ const { document: document_1 } = globals; function add_css$7() { var style = element("style"); style.id = "svelte-jvfq3i-style"; style.textContent = ".svelte-jvfq3i{box-sizing:border-box}section.switcher.svelte-jvfq3i{position:sticky;bottom:0;transform:translateY(20px);margin:40px -20px 0;border-top:1px solid #999;padding:20px;background:#fff}label.svelte-jvfq3i{display:flex;align-items:baseline;gap:5px;font-weight:bold}select.svelte-jvfq3i{min-width:140px}"; append(document_1.head, style); } function get_each_context$3(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[7] = list[i]; child_ctx[9] = i; return child_ctx; } // (42:0) {#if debuggableClients.length > 1} function create_if_block$3(ctx) { let section; let label; let t; let select; let mounted; let dispose; let each_value = /*debuggableClients*/ ctx[1]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i)); } return { c() { section = element("section"); label = element("label"); t = text("Client\n \n "); select = element("select"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(select, "id", selectId); attr(select, "class", "svelte-jvfq3i"); if (/*selected*/ ctx[2] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[4].call(select)); attr(label, "class", "svelte-jvfq3i"); attr(section, "class", "switcher svelte-jvfq3i"); }, m(target, anchor) { insert(target, section, anchor); append(section, label); append(label, t); append(label, select); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(select, null); } select_option(select, /*selected*/ ctx[2]); if (!mounted) { dispose = [ listen(select, "change", /*handleSelection*/ ctx[3]), listen(select, "change", /*select_change_handler*/ ctx[4]) ]; mounted = true; } }, p(ctx, dirty) { if (dirty & /*debuggableClients, JSON*/ 2) { each_value = /*debuggableClients*/ ctx[1]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$3(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); } else { each_blocks[i] = create_each_block$3(child_ctx); each_blocks[i].c(); each_blocks[i].m(select, null); } } for (; i < each_blocks.length; i += 1) { each_blocks[i].d(1); } each_blocks.length = each_value.length; } if (dirty & /*selected*/ 4) { select_option(select, /*selected*/ ctx[2]); } }, d(detaching) { if (detaching) detach(section); destroy_each(each_blocks, detaching); mounted = false; run_all(dispose); } }; } // (48:8) {#each debuggableClients as clientOption, index} function create_each_block$3(ctx) { let option; let t0; let t1; let t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + ""; let t2; let t3; let t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + ""; let t4; let t5; let t6_value = /*clientOption*/ ctx[7].game.name + ""; let t6; let t7; let option_value_value; return { c() { option = element("option"); t0 = text(/*index*/ ctx[9]); t1 = text(" —\n playerID: "); t2 = text(t2_value); t3 = text(",\n matchID: "); t4 = text(t4_value); t5 = text("\n ("); t6 = text(t6_value); t7 = text(")\n "); option.__value = option_value_value = /*index*/ ctx[9]; option.value = option.__value; attr(option, "class", "svelte-jvfq3i"); }, m(target, anchor) { insert(target, option, anchor); append(option, t0); append(option, t1); append(option, t2); append(option, t3); append(option, t4); append(option, t5); append(option, t6); append(option, t7); }, p(ctx, dirty) { if (dirty & /*debuggableClients*/ 2 && t2_value !== (t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "")) set_data(t2, t2_value); if (dirty & /*debuggableClients*/ 2 && t4_value !== (t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "")) set_data(t4, t4_value); if (dirty & /*debuggableClients*/ 2 && t6_value !== (t6_value = /*clientOption*/ ctx[7].game.name + "")) set_data(t6, t6_value); }, d(detaching) { if (detaching) detach(option); } }; } function create_fragment$d(ctx) { let if_block_anchor; let if_block = /*debuggableClients*/ ctx[1].length > 1 && create_if_block$3(ctx); return { c() { if (if_block) if_block.c(); if_block_anchor = empty(); }, m(target, anchor) { if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); }, p(ctx, [dirty]) { if (/*debuggableClients*/ ctx[1].length > 1) { if (if_block) { if_block.p(ctx, dirty); } else { if_block = create_if_block$3(ctx); if_block.c(); if_block.m(if_block_anchor.parentNode, if_block_anchor); } } else if (if_block) { if_block.d(1); if_block = null; } }, i: noop, o: noop, d(detaching) { if (if_block) if_block.d(detaching); if (detaching) detach(if_block_anchor); } }; } const selectId = "bgio-debug-select-client"; function instance$d($$self, $$props, $$invalidate) { let $clientManager, $$unsubscribe_clientManager = noop, $$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(6, $clientManager = $$value)), clientManager); $$self.$$.on_destroy.push(() => $$unsubscribe_clientManager()); let { clientManager } = $$props; $$subscribe_clientManager(); const handleSelection = e => { // Request to switch to the selected client. const selectedClient = debuggableClients[e.target.value]; clientManager.switchToClient(selectedClient); // Maintain focus on the client select menu after switching clients. // Necessary because switching clients will usually trigger a mount/unmount. const select = document.getElementById(selectId); if (select) select.focus(); }; function select_change_handler() { selected = select_value(this); ((($$invalidate(2, selected), $$invalidate(1, debuggableClients)), $$invalidate(5, client)), $$invalidate(6, $clientManager)); } $$self.$set = $$props => { if ("clientManager" in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager)); }; let client; let debuggableClients; let selected; $$self.$$.update = () => { if ($$self.$$.dirty & /*$clientManager*/ 64) { $: $$invalidate(5, { client, debuggableClients } = $clientManager, client, ($$invalidate(1, debuggableClients), $$invalidate(6, $clientManager))); } if ($$self.$$.dirty & /*debuggableClients, client*/ 34) { $: $$invalidate(2, selected = debuggableClients.indexOf(client)); } }; return [ clientManager, debuggableClients, selected, handleSelection, select_change_handler ]; } class ClientSwitcher extends SvelteComponent { constructor(options) { super(); if (!document_1.getElementById("svelte-jvfq3i-style")) add_css$7(); init(this, options, instance$d, create_fragment$d, safe_not_equal, { clientManager: 0 }); } } /* src/client/debug/main/Hotkey.svelte generated by Svelte v3.24.0 */ function add_css$8() { var style = element("style"); style.id = "svelte-1vfj1mn-style"; style.textContent = ".key.svelte-1vfj1mn.svelte-1vfj1mn{display:flex;flex-direction:row;align-items:center}button.svelte-1vfj1mn.svelte-1vfj1mn{cursor:pointer;min-width:10px;padding-left:5px;padding-right:5px;height:20px;line-height:20px;text-align:center;border:1px solid #ccc;box-shadow:1px 1px 1px #888;background:#eee;color:#444}button.svelte-1vfj1mn.svelte-1vfj1mn:hover{background:#ddd}.key.active.svelte-1vfj1mn button.svelte-1vfj1mn{background:#ddd;border:1px solid #999;box-shadow:none}label.svelte-1vfj1mn.svelte-1vfj1mn{margin-left:10px}"; append(document.head, style); } // (78:2) {#if label} function create_if_block$4(ctx) { let label_1; let t0; let t1; let span; let t2_value = `(shortcut: ${/*value*/ ctx[0]})` + ""; let t2; return { c() { label_1 = element("label"); t0 = text(/*label*/ ctx[1]); t1 = space(); span = element("span"); t2 = text(t2_value); attr(span, "class", "screen-reader-only"); attr(label_1, "for", /*id*/ ctx[5]); attr(label_1, "class", "svelte-1vfj1mn"); }, m(target, anchor) { insert(target, label_1, anchor); append(label_1, t0); append(label_1, t1); append(label_1, span); append(span, t2); }, p(ctx, dirty) { if (dirty & /*label*/ 2) set_data(t0, /*label*/ ctx[1]); if (dirty & /*value*/ 1 && t2_value !== (t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "")) set_data(t2, t2_value); }, d(detaching) { if (detaching) detach(label_1); } }; } function create_fragment$e(ctx) { let div; let button; let t0; let t1; let mounted; let dispose; let if_block = /*label*/ ctx[1] && create_if_block$4(ctx); return { c() { div = element("div"); button = element("button"); t0 = text(/*value*/ ctx[0]); t1 = space(); if (if_block) if_block.c(); attr(button, "id", /*id*/ ctx[5]); button.disabled = /*disable*/ ctx[2]; attr(button, "class", "svelte-1vfj1mn"); attr(div, "class", "key svelte-1vfj1mn"); toggle_class(div, "active", /*active*/ ctx[3]); }, m(target, anchor) { insert(target, div, anchor); append(div, button); append(button, t0); append(div, t1); if (if_block) if_block.m(div, null); if (!mounted) { dispose = [ listen(window, "keydown", /*Keypress*/ ctx[7]), listen(button, "click", /*Activate*/ ctx[6]) ]; mounted = true; } }, p(ctx, [dirty]) { if (dirty & /*value*/ 1) set_data(t0, /*value*/ ctx[0]); if (dirty & /*disable*/ 4) { button.disabled = /*disable*/ ctx[2]; } if (/*label*/ ctx[1]) { if (if_block) { if_block.p(ctx, dirty); } else { if_block = create_if_block$4(ctx); if_block.c(); if_block.m(div, null); } } else if (if_block) { if_block.d(1); if_block = null; } if (dirty & /*active*/ 8) { toggle_class(div, "active", /*active*/ ctx[3]); } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); if (if_block) if_block.d(); mounted = false; run_all(dispose); } }; } function instance$e($$self, $$props, $$invalidate) { let $disableHotkeys; let { value } = $$props; let { onPress = null } = $$props; let { label = null } = $$props; let { disable = false } = $$props; const { disableHotkeys } = getContext("hotkeys"); component_subscribe($$self, disableHotkeys, value => $$invalidate(9, $disableHotkeys = value)); let active = false; let id = `key-${value}`; function Deactivate() { $$invalidate(3, active = false); } function Activate() { $$invalidate(3, active = true); setTimeout(Deactivate, 200); if (onPress) { setTimeout(onPress, 1); } } function Keypress(e) { if (!$disableHotkeys && !disable && !e.ctrlKey && !e.metaKey && e.key == value) { e.preventDefault(); Activate(); } } $$self.$set = $$props => { if ("value" in $$props) $$invalidate(0, value = $$props.value); if ("onPress" in $$props) $$invalidate(8, onPress = $$props.onPress); if ("label" in $$props) $$invalidate(1, label = $$props.label); if ("disable" in $$props) $$invalidate(2, disable = $$props.disable); }; return [value, label, disable, active, disableHotkeys, id, Activate, Keypress, onPress]; } class Hotkey extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1vfj1mn-style")) add_css$8(); init(this, options, instance$e, create_fragment$e, safe_not_equal, { value: 0, onPress: 8, label: 1, disable: 2 }); } } /* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.24.0 */ function add_css$9() { var style = element("style"); style.id = "svelte-1mppqmp-style"; style.textContent = ".move.svelte-1mppqmp{display:flex;flex-direction:row;cursor:pointer;margin-left:10px;color:#666}.move.svelte-1mppqmp:hover{color:#333}.move.active.svelte-1mppqmp{color:#111;font-weight:bold}.arg-field.svelte-1mppqmp{outline:none;font-family:monospace}"; append(document.head, style); } function create_fragment$f(ctx) { let div; let span0; let t0; let t1; let span1; let t3; let span2; let t4; let span3; let mounted; let dispose; return { c() { div = element("div"); span0 = element("span"); t0 = text(/*name*/ ctx[2]); t1 = space(); span1 = element("span"); span1.textContent = "("; t3 = space(); span2 = element("span"); t4 = space(); span3 = element("span"); span3.textContent = ")"; attr(span2, "class", "arg-field svelte-1mppqmp"); attr(span2, "contenteditable", ""); attr(div, "class", "move svelte-1mppqmp"); toggle_class(div, "active", /*active*/ ctx[3]); }, m(target, anchor) { insert(target, div, anchor); append(div, span0); append(span0, t0); append(div, t1); append(div, span1); append(div, t3); append(div, span2); /*span2_binding*/ ctx[6](span2); append(div, t4); append(div, span3); if (!mounted) { dispose = [ listen(span2, "focus", function () { if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments); }), listen(span2, "blur", function () { if (is_function(/*Deactivate*/ ctx[1])) /*Deactivate*/ ctx[1].apply(this, arguments); }), listen(span2, "keypress", stop_propagation(keypress_handler)), listen(span2, "keydown", /*OnKeyDown*/ ctx[5]), listen(div, "click", function () { if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments); }) ]; mounted = true; } }, p(new_ctx, [dirty]) { ctx = new_ctx; if (dirty & /*name*/ 4) set_data(t0, /*name*/ ctx[2]); if (dirty & /*active*/ 8) { toggle_class(div, "active", /*active*/ ctx[3]); } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); /*span2_binding*/ ctx[6](null); mounted = false; run_all(dispose); } }; } const keypress_handler = () => { }; function instance$f($$self, $$props, $$invalidate) { let { Activate } = $$props; let { Deactivate } = $$props; let { name } = $$props; let { active } = $$props; let span; const dispatch = createEventDispatcher(); function Submit() { try { const value = span.innerText; let argArray = new Function(`return [${value}]`)(); dispatch("submit", argArray); } catch(error) { dispatch("error", error); } $$invalidate(4, span.innerText = "", span); } function OnKeyDown(e) { if (e.key == "Enter") { e.preventDefault(); Submit(); } if (e.key == "Escape") { e.preventDefault(); Deactivate(); } } afterUpdate(() => { if (active) { span.focus(); } else { span.blur(); } }); function span2_binding($$value) { binding_callbacks[$$value ? "unshift" : "push"](() => { span = $$value; $$invalidate(4, span); }); } $$self.$set = $$props => { if ("Activate" in $$props) $$invalidate(0, Activate = $$props.Activate); if ("Deactivate" in $$props) $$invalidate(1, Deactivate = $$props.Deactivate); if ("name" in $$props) $$invalidate(2, name = $$props.name); if ("active" in $$props) $$invalidate(3, active = $$props.active); }; return [Activate, Deactivate, name, active, span, OnKeyDown, span2_binding]; } class InteractiveFunction extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1mppqmp-style")) add_css$9(); init(this, options, instance$f, create_fragment$f, safe_not_equal, { Activate: 0, Deactivate: 1, name: 2, active: 3 }); } } /* src/client/debug/main/Move.svelte generated by Svelte v3.24.0 */ function add_css$a() { var style = element("style"); style.id = "svelte-smqssc-style"; style.textContent = ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}"; append(document.head, style); } // (65:2) {#if error} function create_if_block$5(ctx) { let span; let t; return { c() { span = element("span"); t = text(/*error*/ ctx[2]); attr(span, "class", "move-error svelte-smqssc"); }, m(target, anchor) { insert(target, span, anchor); append(span, t); }, p(ctx, dirty) { if (dirty & /*error*/ 4) set_data(t, /*error*/ ctx[2]); }, d(detaching) { if (detaching) detach(span); } }; } function create_fragment$g(ctx) { let div1; let div0; let hotkey; let t0; let interactivefunction; let t1; let current; hotkey = new Hotkey({ props: { value: /*shortcut*/ ctx[0], onPress: /*Activate*/ ctx[4] } }); interactivefunction = new InteractiveFunction({ props: { Activate: /*Activate*/ ctx[4], Deactivate: /*Deactivate*/ ctx[5], name: /*name*/ ctx[1], active: /*active*/ ctx[3] } }); interactivefunction.$on("submit", /*Submit*/ ctx[6]); interactivefunction.$on("error", /*Error*/ ctx[7]); let if_block = /*error*/ ctx[2] && create_if_block$5(ctx); return { c() { div1 = element("div"); div0 = element("div"); create_component(hotkey.$$.fragment); t0 = space(); create_component(interactivefunction.$$.fragment); t1 = space(); if (if_block) if_block.c(); attr(div0, "class", "wrapper svelte-smqssc"); }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); mount_component(hotkey, div0, null); append(div0, t0); mount_component(interactivefunction, div0, null); append(div1, t1); if (if_block) if_block.m(div1, null); current = true; }, p(ctx, [dirty]) { const hotkey_changes = {}; if (dirty & /*shortcut*/ 1) hotkey_changes.value = /*shortcut*/ ctx[0]; hotkey.$set(hotkey_changes); const interactivefunction_changes = {}; if (dirty & /*name*/ 2) interactivefunction_changes.name = /*name*/ ctx[1]; if (dirty & /*active*/ 8) interactivefunction_changes.active = /*active*/ ctx[3]; interactivefunction.$set(interactivefunction_changes); if (/*error*/ ctx[2]) { if (if_block) { if_block.p(ctx, dirty); } else { if_block = create_if_block$5(ctx); if_block.c(); if_block.m(div1, null); } } else if (if_block) { if_block.d(1); if_block = null; } }, i(local) { if (current) return; transition_in(hotkey.$$.fragment, local); transition_in(interactivefunction.$$.fragment, local); current = true; }, o(local) { transition_out(hotkey.$$.fragment, local); transition_out(interactivefunction.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(div1); destroy_component(hotkey); destroy_component(interactivefunction); if (if_block) if_block.d(); } }; } function instance$g($$self, $$props, $$invalidate) { let { shortcut } = $$props; let { name } = $$props; let { fn } = $$props; const { disableHotkeys } = getContext("hotkeys"); let error$1 = ""; let active = false; function Activate() { disableHotkeys.set(true); $$invalidate(3, active = true); } function Deactivate() { disableHotkeys.set(false); $$invalidate(2, error$1 = ""); $$invalidate(3, active = false); } function Submit(e) { $$invalidate(2, error$1 = ""); Deactivate(); fn.apply(this, e.detail); } function Error(e) { $$invalidate(2, error$1 = e.detail); error(e.detail); } $$self.$set = $$props => { if ("shortcut" in $$props) $$invalidate(0, shortcut = $$props.shortcut); if ("name" in $$props) $$invalidate(1, name = $$props.name); if ("fn" in $$props) $$invalidate(8, fn = $$props.fn); }; return [shortcut, name, error$1, active, Activate, Deactivate, Submit, Error, fn]; } class Move extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-smqssc-style")) add_css$a(); init(this, options, instance$g, create_fragment$g, safe_not_equal, { shortcut: 0, name: 1, fn: 8 }); } } /* src/client/debug/main/Controls.svelte generated by Svelte v3.24.0 */ function add_css$b() { var style = element("style"); style.id = "svelte-c3lavh-style"; style.textContent = "ul.svelte-c3lavh{padding-left:0}li.svelte-c3lavh{list-style:none;margin:none;margin-bottom:5px}"; append(document.head, style); } function create_fragment$h(ctx) { let ul; let li0; let hotkey0; let t0; let li1; let hotkey1; let t1; let li2; let hotkey2; let t2; let li3; let hotkey3; let current; hotkey0 = new Hotkey({ props: { value: "1", onPress: /*client*/ ctx[0].reset, label: "reset" } }); hotkey1 = new Hotkey({ props: { value: "2", onPress: /*Save*/ ctx[1], label: "save" } }); hotkey2 = new Hotkey({ props: { value: "3", onPress: /*Restore*/ ctx[2], label: "restore" } }); hotkey3 = new Hotkey({ props: { value: ".", disable: true, label: "hide" } }); return { c() { ul = element("ul"); li0 = element("li"); create_component(hotkey0.$$.fragment); t0 = space(); li1 = element("li"); create_component(hotkey1.$$.fragment); t1 = space(); li2 = element("li"); create_component(hotkey2.$$.fragment); t2 = space(); li3 = element("li"); create_component(hotkey3.$$.fragment); attr(li0, "class", "svelte-c3lavh"); attr(li1, "class", "svelte-c3lavh"); attr(li2, "class", "svelte-c3lavh"); attr(li3, "class", "svelte-c3lavh"); attr(ul, "id", "debug-controls"); attr(ul, "class", "controls svelte-c3lavh"); }, m(target, anchor) { insert(target, ul, anchor); append(ul, li0); mount_component(hotkey0, li0, null); append(ul, t0); append(ul, li1); mount_component(hotkey1, li1, null); append(ul, t1); append(ul, li2); mount_component(hotkey2, li2, null); append(ul, t2); append(ul, li3); mount_component(hotkey3, li3, null); current = true; }, p(ctx, [dirty]) { const hotkey0_changes = {}; if (dirty & /*client*/ 1) hotkey0_changes.onPress = /*client*/ ctx[0].reset; hotkey0.$set(hotkey0_changes); }, i(local) { if (current) return; transition_in(hotkey0.$$.fragment, local); transition_in(hotkey1.$$.fragment, local); transition_in(hotkey2.$$.fragment, local); transition_in(hotkey3.$$.fragment, local); current = true; }, o(local) { transition_out(hotkey0.$$.fragment, local); transition_out(hotkey1.$$.fragment, local); transition_out(hotkey2.$$.fragment, local); transition_out(hotkey3.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(ul); destroy_component(hotkey0); destroy_component(hotkey1); destroy_component(hotkey2); destroy_component(hotkey3); } }; } function instance$h($$self, $$props, $$invalidate) { let { client } = $$props; function Save() { // get state to persist and overwrite deltalog, _undo, and _redo const state = client.getState(); const json = stringify({ ...state, _undo: [], _redo: [], deltalog: [] }); window.localStorage.setItem("gamestate", json); window.localStorage.setItem("initialState", stringify(client.initialState)); } function Restore() { const gamestateJSON = window.localStorage.getItem("gamestate"); const initialStateJSON = window.localStorage.getItem("initialState"); if (gamestateJSON !== null && initialStateJSON !== null) { const gamestate = parse(gamestateJSON); const initialState = parse(initialStateJSON); client.store.dispatch(sync({ state: gamestate, initialState })); } } $$self.$set = $$props => { if ("client" in $$props) $$invalidate(0, client = $$props.client); }; return [client, Save, Restore]; } class Controls extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-c3lavh-style")) add_css$b(); init(this, options, instance$h, create_fragment$h, safe_not_equal, { client: 0 }); } } /* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.24.0 */ function add_css$c() { var style = element("style"); style.id = "svelte-19aan9p-style"; style.textContent = ".player-box.svelte-19aan9p{display:flex;flex-direction:row}.player.svelte-19aan9p{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box;padding:0}.player.current.svelte-19aan9p{background:#555;color:#eee;font-weight:bold}.player.active.svelte-19aan9p{border:3px solid #ff7f50}"; append(document.head, style); } function get_each_context$4(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[7] = list[i]; return child_ctx; } // (59:2) {#each players as player} function create_each_block$4(ctx) { let button; let t0_value = /*player*/ ctx[7] + ""; let t0; let t1; let button_aria_label_value; let mounted; let dispose; function click_handler(...args) { return /*click_handler*/ ctx[5](/*player*/ ctx[7], ...args); } return { c() { button = element("button"); t0 = text(t0_value); t1 = space(); attr(button, "class", "player svelte-19aan9p"); attr(button, "aria-label", button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7])); toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer); toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]); }, m(target, anchor) { insert(target, button, anchor); append(button, t0); append(button, t1); if (!mounted) { dispose = listen(button, "click", click_handler); mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if (dirty & /*players*/ 4 && t0_value !== (t0_value = /*player*/ ctx[7] + "")) set_data(t0, t0_value); if (dirty & /*players*/ 4 && button_aria_label_value !== (button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]))) { attr(button, "aria-label", button_aria_label_value); } if (dirty & /*players, ctx*/ 5) { toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer); } if (dirty & /*players, playerID*/ 6) { toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]); } }, d(detaching) { if (detaching) detach(button); mounted = false; dispose(); } }; } function create_fragment$i(ctx) { let div; let each_value = /*players*/ ctx[2]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i)); } return { c() { div = element("div"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(div, "class", "player-box svelte-19aan9p"); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(div, null); } }, p(ctx, [dirty]) { if (dirty & /*playerLabel, players, ctx, playerID, OnClick*/ 31) { each_value = /*players*/ ctx[2]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$4(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); } else { each_blocks[i] = create_each_block$4(child_ctx); each_blocks[i].c(); each_blocks[i].m(div, null); } } for (; i < each_blocks.length; i += 1) { each_blocks[i].d(1); } each_blocks.length = each_value.length; } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); destroy_each(each_blocks, detaching); } }; } function instance$i($$self, $$props, $$invalidate) { let { ctx } = $$props; let { playerID } = $$props; const dispatch = createEventDispatcher(); function OnClick(player) { if (player == playerID) { dispatch("change", { playerID: null }); } else { dispatch("change", { playerID: player }); } } function playerLabel(player) { const properties = []; if (player == ctx.currentPlayer) properties.push("current"); if (player == playerID) properties.push("active"); let label = `Player ${player}`; if (properties.length) label += ` (${properties.join(", ")})`; return label; } let players; const click_handler = player => OnClick(player); $$self.$set = $$props => { if ("ctx" in $$props) $$invalidate(0, ctx = $$props.ctx); if ("playerID" in $$props) $$invalidate(1, playerID = $$props.playerID); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*ctx*/ 1) { $: $$invalidate(2, players = ctx ? [...Array(ctx.numPlayers).keys()].map(i => i.toString()) : []); } }; return [ctx, playerID, players, OnClick, playerLabel, click_handler]; } class PlayerInfo extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-19aan9p-style")) add_css$c(); init(this, options, instance$i, create_fragment$i, safe_not_equal, { ctx: 0, playerID: 1 }); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = o[Symbol.iterator](); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ function AssignShortcuts(moveNames, blacklist) { var shortcuts = {}; var taken = {}; var _iterator = _createForOfIteratorHelper(blacklist), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var c = _step.value; taken[c] = true; } // Try assigning the first char of each move as the shortcut. } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var t = taken; var canUseFirstChar = true; for (var name in moveNames) { var shortcut = name[0]; if (t[shortcut]) { canUseFirstChar = false; break; } t[shortcut] = true; shortcuts[name] = shortcut; } if (canUseFirstChar) { return shortcuts; } // If those aren't unique, use a-z. t = taken; var next = 97; shortcuts = {}; for (var _name in moveNames) { var _shortcut = String.fromCharCode(next); while (t[_shortcut]) { next++; _shortcut = String.fromCharCode(next); } t[_shortcut] = true; shortcuts[_name] = _shortcut; } return shortcuts; } /* src/client/debug/main/Main.svelte generated by Svelte v3.24.0 */ function add_css$d() { var style = element("style"); style.id = "svelte-146sq5f-style"; style.textContent = ".tree.svelte-146sq5f{--json-tree-font-family:monospace;--json-tree-font-size:14px;--json-tree-null-color:#757575}.label.svelte-146sq5f{margin-bottom:0;text-transform:none}h3.svelte-146sq5f{text-transform:uppercase}ul.svelte-146sq5f{padding-left:0}li.svelte-146sq5f{list-style:none;margin:0;margin-bottom:5px}"; append(document.head, style); } function get_each_context$5(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[9] = list[i][0]; child_ctx[10] = list[i][1]; return child_ctx; } // (77:4) {#each Object.entries(moves) as [name, fn]} function create_each_block$5(ctx) { let li; let move; let t; let current; move = new Move({ props: { shortcut: /*shortcuts*/ ctx[7][/*name*/ ctx[9]], fn: /*fn*/ ctx[10], name: /*name*/ ctx[9] } }); return { c() { li = element("li"); create_component(move.$$.fragment); t = space(); attr(li, "class", "svelte-146sq5f"); }, m(target, anchor) { insert(target, li, anchor); mount_component(move, li, null); append(li, t); current = true; }, p(ctx, dirty) { const move_changes = {}; if (dirty & /*moves*/ 8) move_changes.shortcut = /*shortcuts*/ ctx[7][/*name*/ ctx[9]]; if (dirty & /*moves*/ 8) move_changes.fn = /*fn*/ ctx[10]; if (dirty & /*moves*/ 8) move_changes.name = /*name*/ ctx[9]; move.$set(move_changes); }, i(local) { if (current) return; transition_in(move.$$.fragment, local); current = true; }, o(local) { transition_out(move.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(li); destroy_component(move); } }; } // (89:2) {#if ctx.activePlayers && events.endStage} function create_if_block_2$2(ctx) { let li; let move; let current; move = new Move({ props: { name: "endStage", shortcut: 7, fn: /*events*/ ctx[4].endStage } }); return { c() { li = element("li"); create_component(move.$$.fragment); attr(li, "class", "svelte-146sq5f"); }, m(target, anchor) { insert(target, li, anchor); mount_component(move, li, null); current = true; }, p(ctx, dirty) { const move_changes = {}; if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endStage; move.$set(move_changes); }, i(local) { if (current) return; transition_in(move.$$.fragment, local); current = true; }, o(local) { transition_out(move.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(li); destroy_component(move); } }; } // (94:2) {#if events.endTurn} function create_if_block_1$2(ctx) { let li; let move; let current; move = new Move({ props: { name: "endTurn", shortcut: 8, fn: /*events*/ ctx[4].endTurn } }); return { c() { li = element("li"); create_component(move.$$.fragment); attr(li, "class", "svelte-146sq5f"); }, m(target, anchor) { insert(target, li, anchor); mount_component(move, li, null); current = true; }, p(ctx, dirty) { const move_changes = {}; if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endTurn; move.$set(move_changes); }, i(local) { if (current) return; transition_in(move.$$.fragment, local); current = true; }, o(local) { transition_out(move.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(li); destroy_component(move); } }; } // (99:2) {#if ctx.phase && events.endPhase} function create_if_block$6(ctx) { let li; let move; let current; move = new Move({ props: { name: "endPhase", shortcut: 9, fn: /*events*/ ctx[4].endPhase } }); return { c() { li = element("li"); create_component(move.$$.fragment); attr(li, "class", "svelte-146sq5f"); }, m(target, anchor) { insert(target, li, anchor); mount_component(move, li, null); current = true; }, p(ctx, dirty) { const move_changes = {}; if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endPhase; move.$set(move_changes); }, i(local) { if (current) return; transition_in(move.$$.fragment, local); current = true; }, o(local) { transition_out(move.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(li); destroy_component(move); } }; } function create_fragment$j(ctx) { let section0; let h30; let t1; let controls; let t2; let section1; let h31; let t4; let playerinfo; let t5; let section2; let h32; let t7; let ul0; let t8; let section3; let h33; let t10; let ul1; let t11; let t12; let t13; let section4; let h34; let t15; let jsontree0; let t16; let section5; let h35; let t18; let jsontree1; let t19; let clientswitcher; let current; controls = new Controls({ props: { client: /*client*/ ctx[0] } }); playerinfo = new PlayerInfo({ props: { ctx: /*ctx*/ ctx[5], playerID: /*playerID*/ ctx[2] } }); playerinfo.$on("change", /*change_handler*/ ctx[8]); let each_value = Object.entries(/*moves*/ ctx[3]); let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$5(get_each_context$5(ctx, each_value, i)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); let if_block0 = /*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage && create_if_block_2$2(ctx); let if_block1 = /*events*/ ctx[4].endTurn && create_if_block_1$2(ctx); let if_block2 = /*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase && create_if_block$6(ctx); jsontree0 = new Root({ props: { value: /*G*/ ctx[6] } }); jsontree1 = new Root({ props: { value: SanitizeCtx(/*ctx*/ ctx[5]) } }); clientswitcher = new ClientSwitcher({ props: { clientManager: /*clientManager*/ ctx[1] } }); return { c() { section0 = element("section"); h30 = element("h3"); h30.textContent = "Controls"; t1 = space(); create_component(controls.$$.fragment); t2 = space(); section1 = element("section"); h31 = element("h3"); h31.textContent = "Players"; t4 = space(); create_component(playerinfo.$$.fragment); t5 = space(); section2 = element("section"); h32 = element("h3"); h32.textContent = "Moves"; t7 = space(); ul0 = element("ul"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } t8 = space(); section3 = element("section"); h33 = element("h3"); h33.textContent = "Events"; t10 = space(); ul1 = element("ul"); if (if_block0) if_block0.c(); t11 = space(); if (if_block1) if_block1.c(); t12 = space(); if (if_block2) if_block2.c(); t13 = space(); section4 = element("section"); h34 = element("h3"); h34.textContent = "G"; t15 = space(); create_component(jsontree0.$$.fragment); t16 = space(); section5 = element("section"); h35 = element("h3"); h35.textContent = "ctx"; t18 = space(); create_component(jsontree1.$$.fragment); t19 = space(); create_component(clientswitcher.$$.fragment); attr(h30, "class", "svelte-146sq5f"); attr(h31, "class", "svelte-146sq5f"); attr(h32, "class", "svelte-146sq5f"); attr(ul0, "class", "svelte-146sq5f"); attr(h33, "class", "svelte-146sq5f"); attr(ul1, "class", "svelte-146sq5f"); attr(h34, "class", "label svelte-146sq5f"); attr(section4, "class", "tree svelte-146sq5f"); attr(h35, "class", "label svelte-146sq5f"); attr(section5, "class", "tree svelte-146sq5f"); }, m(target, anchor) { insert(target, section0, anchor); append(section0, h30); append(section0, t1); mount_component(controls, section0, null); insert(target, t2, anchor); insert(target, section1, anchor); append(section1, h31); append(section1, t4); mount_component(playerinfo, section1, null); insert(target, t5, anchor); insert(target, section2, anchor); append(section2, h32); append(section2, t7); append(section2, ul0); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(ul0, null); } insert(target, t8, anchor); insert(target, section3, anchor); append(section3, h33); append(section3, t10); append(section3, ul1); if (if_block0) if_block0.m(ul1, null); append(ul1, t11); if (if_block1) if_block1.m(ul1, null); append(ul1, t12); if (if_block2) if_block2.m(ul1, null); insert(target, t13, anchor); insert(target, section4, anchor); append(section4, h34); append(section4, t15); mount_component(jsontree0, section4, null); insert(target, t16, anchor); insert(target, section5, anchor); append(section5, h35); append(section5, t18); mount_component(jsontree1, section5, null); insert(target, t19, anchor); mount_component(clientswitcher, target, anchor); current = true; }, p(ctx, [dirty]) { const controls_changes = {}; if (dirty & /*client*/ 1) controls_changes.client = /*client*/ ctx[0]; controls.$set(controls_changes); const playerinfo_changes = {}; if (dirty & /*ctx*/ 32) playerinfo_changes.ctx = /*ctx*/ ctx[5]; if (dirty & /*playerID*/ 4) playerinfo_changes.playerID = /*playerID*/ ctx[2]; playerinfo.$set(playerinfo_changes); if (dirty & /*shortcuts, Object, moves*/ 136) { each_value = Object.entries(/*moves*/ ctx[3]); let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$5(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$5(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(ul0, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } if (/*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage) { if (if_block0) { if_block0.p(ctx, dirty); if (dirty & /*ctx, events*/ 48) { transition_in(if_block0, 1); } } else { if_block0 = create_if_block_2$2(ctx); if_block0.c(); transition_in(if_block0, 1); if_block0.m(ul1, t11); } } else if (if_block0) { group_outros(); transition_out(if_block0, 1, 1, () => { if_block0 = null; }); check_outros(); } if (/*events*/ ctx[4].endTurn) { if (if_block1) { if_block1.p(ctx, dirty); if (dirty & /*events*/ 16) { transition_in(if_block1, 1); } } else { if_block1 = create_if_block_1$2(ctx); if_block1.c(); transition_in(if_block1, 1); if_block1.m(ul1, t12); } } else if (if_block1) { group_outros(); transition_out(if_block1, 1, 1, () => { if_block1 = null; }); check_outros(); } if (/*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase) { if (if_block2) { if_block2.p(ctx, dirty); if (dirty & /*ctx, events*/ 48) { transition_in(if_block2, 1); } } else { if_block2 = create_if_block$6(ctx); if_block2.c(); transition_in(if_block2, 1); if_block2.m(ul1, null); } } else if (if_block2) { group_outros(); transition_out(if_block2, 1, 1, () => { if_block2 = null; }); check_outros(); } const jsontree0_changes = {}; if (dirty & /*G*/ 64) jsontree0_changes.value = /*G*/ ctx[6]; jsontree0.$set(jsontree0_changes); const jsontree1_changes = {}; if (dirty & /*ctx*/ 32) jsontree1_changes.value = SanitizeCtx(/*ctx*/ ctx[5]); jsontree1.$set(jsontree1_changes); const clientswitcher_changes = {}; if (dirty & /*clientManager*/ 2) clientswitcher_changes.clientManager = /*clientManager*/ ctx[1]; clientswitcher.$set(clientswitcher_changes); }, i(local) { if (current) return; transition_in(controls.$$.fragment, local); transition_in(playerinfo.$$.fragment, local); for (let i = 0; i < each_value.length; i += 1) { transition_in(each_blocks[i]); } transition_in(if_block0); transition_in(if_block1); transition_in(if_block2); transition_in(jsontree0.$$.fragment, local); transition_in(jsontree1.$$.fragment, local); transition_in(clientswitcher.$$.fragment, local); current = true; }, o(local) { transition_out(controls.$$.fragment, local); transition_out(playerinfo.$$.fragment, local); each_blocks = each_blocks.filter(Boolean); for (let i = 0; i < each_blocks.length; i += 1) { transition_out(each_blocks[i]); } transition_out(if_block0); transition_out(if_block1); transition_out(if_block2); transition_out(jsontree0.$$.fragment, local); transition_out(jsontree1.$$.fragment, local); transition_out(clientswitcher.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(section0); destroy_component(controls); if (detaching) detach(t2); if (detaching) detach(section1); destroy_component(playerinfo); if (detaching) detach(t5); if (detaching) detach(section2); destroy_each(each_blocks, detaching); if (detaching) detach(t8); if (detaching) detach(section3); if (if_block0) if_block0.d(); if (if_block1) if_block1.d(); if (if_block2) if_block2.d(); if (detaching) detach(t13); if (detaching) detach(section4); destroy_component(jsontree0); if (detaching) detach(t16); if (detaching) detach(section5); destroy_component(jsontree1); if (detaching) detach(t19); destroy_component(clientswitcher, detaching); } }; } function SanitizeCtx(ctx) { let r = {}; for (const key in ctx) { if (!key.startsWith("_")) { r[key] = ctx[key]; } } return r; } function instance$j($$self, $$props, $$invalidate) { let { client } = $$props; let { clientManager } = $$props; const shortcuts = AssignShortcuts(client.moves, "mlia"); let { playerID, moves, events } = client; let ctx = {}; let G = {}; client.subscribe(state => { if (state) $$invalidate(6, { G, ctx } = state, G, $$invalidate(5, ctx)); $$invalidate(2, { playerID, moves, events } = client, playerID, $$invalidate(3, moves), $$invalidate(4, events)); }); const change_handler = e => clientManager.switchPlayerID(e.detail.playerID); $$self.$set = $$props => { if ("client" in $$props) $$invalidate(0, client = $$props.client); if ("clientManager" in $$props) $$invalidate(1, clientManager = $$props.clientManager); }; return [ client, clientManager, playerID, moves, events, ctx, G, shortcuts, change_handler ]; } class Main extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-146sq5f-style")) add_css$d(); init(this, options, instance$j, create_fragment$j, safe_not_equal, { client: 0, clientManager: 1 }); } } /* src/client/debug/info/Item.svelte generated by Svelte v3.24.0 */ function add_css$e() { var style = element("style"); style.id = "svelte-13qih23-style"; style.textContent = ".item.svelte-13qih23.svelte-13qih23{padding:10px}.item.svelte-13qih23.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}"; append(document.head, style); } function create_fragment$k(ctx) { let div1; let strong; let t0; let t1; let div0; let t2_value = JSON.stringify(/*value*/ ctx[1]) + ""; let t2; return { c() { div1 = element("div"); strong = element("strong"); t0 = text(/*name*/ ctx[0]); t1 = space(); div0 = element("div"); t2 = text(t2_value); attr(div0, "class", "svelte-13qih23"); attr(div1, "class", "item svelte-13qih23"); }, m(target, anchor) { insert(target, div1, anchor); append(div1, strong); append(strong, t0); append(div1, t1); append(div1, div0); append(div0, t2); }, p(ctx, [dirty]) { if (dirty & /*name*/ 1) set_data(t0, /*name*/ ctx[0]); if (dirty & /*value*/ 2 && t2_value !== (t2_value = JSON.stringify(/*value*/ ctx[1]) + "")) set_data(t2, t2_value); }, i: noop, o: noop, d(detaching) { if (detaching) detach(div1); } }; } function instance$k($$self, $$props, $$invalidate) { let { name } = $$props; let { value } = $$props; $$self.$set = $$props => { if ("name" in $$props) $$invalidate(0, name = $$props.name); if ("value" in $$props) $$invalidate(1, value = $$props.value); }; return [name, value]; } class Item extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-13qih23-style")) add_css$e(); init(this, options, instance$k, create_fragment$k, safe_not_equal, { name: 0, value: 1 }); } } /* src/client/debug/info/Info.svelte generated by Svelte v3.24.0 */ function add_css$f() { var style = element("style"); style.id = "svelte-1yzq5o8-style"; style.textContent = ".gameinfo.svelte-1yzq5o8{padding:10px}"; append(document.head, style); } // (18:2) {#if client.multiplayer} function create_if_block$7(ctx) { let item; let current; item = new Item({ props: { name: "isConnected", value: /*$client*/ ctx[1].isConnected } }); return { c() { create_component(item.$$.fragment); }, m(target, anchor) { mount_component(item, target, anchor); current = true; }, p(ctx, dirty) { const item_changes = {}; if (dirty & /*$client*/ 2) item_changes.value = /*$client*/ ctx[1].isConnected; item.$set(item_changes); }, i(local) { if (current) return; transition_in(item.$$.fragment, local); current = true; }, o(local) { transition_out(item.$$.fragment, local); current = false; }, d(detaching) { destroy_component(item, detaching); } }; } function create_fragment$l(ctx) { let section; let item0; let t0; let item1; let t1; let item2; let t2; let current; item0 = new Item({ props: { name: "matchID", value: /*client*/ ctx[0].matchID } }); item1 = new Item({ props: { name: "playerID", value: /*client*/ ctx[0].playerID } }); item2 = new Item({ props: { name: "isActive", value: /*$client*/ ctx[1].isActive } }); let if_block = /*client*/ ctx[0].multiplayer && create_if_block$7(ctx); return { c() { section = element("section"); create_component(item0.$$.fragment); t0 = space(); create_component(item1.$$.fragment); t1 = space(); create_component(item2.$$.fragment); t2 = space(); if (if_block) if_block.c(); attr(section, "class", "gameinfo svelte-1yzq5o8"); }, m(target, anchor) { insert(target, section, anchor); mount_component(item0, section, null); append(section, t0); mount_component(item1, section, null); append(section, t1); mount_component(item2, section, null); append(section, t2); if (if_block) if_block.m(section, null); current = true; }, p(ctx, [dirty]) { const item0_changes = {}; if (dirty & /*client*/ 1) item0_changes.value = /*client*/ ctx[0].matchID; item0.$set(item0_changes); const item1_changes = {}; if (dirty & /*client*/ 1) item1_changes.value = /*client*/ ctx[0].playerID; item1.$set(item1_changes); const item2_changes = {}; if (dirty & /*$client*/ 2) item2_changes.value = /*$client*/ ctx[1].isActive; item2.$set(item2_changes); if (/*client*/ ctx[0].multiplayer) { if (if_block) { if_block.p(ctx, dirty); if (dirty & /*client*/ 1) { transition_in(if_block, 1); } } else { if_block = create_if_block$7(ctx); if_block.c(); transition_in(if_block, 1); if_block.m(section, null); } } else if (if_block) { group_outros(); transition_out(if_block, 1, 1, () => { if_block = null; }); check_outros(); } }, i(local) { if (current) return; transition_in(item0.$$.fragment, local); transition_in(item1.$$.fragment, local); transition_in(item2.$$.fragment, local); transition_in(if_block); current = true; }, o(local) { transition_out(item0.$$.fragment, local); transition_out(item1.$$.fragment, local); transition_out(item2.$$.fragment, local); transition_out(if_block); current = false; }, d(detaching) { if (detaching) detach(section); destroy_component(item0); destroy_component(item1); destroy_component(item2); if (if_block) if_block.d(); } }; } function instance$l($$self, $$props, $$invalidate) { let $client, $$unsubscribe_client = noop, $$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(1, $client = $$value)), client); $$self.$$.on_destroy.push(() => $$unsubscribe_client()); let { client } = $$props; $$subscribe_client(); let { clientManager } = $$props; $$self.$set = $$props => { if ("client" in $$props) $$subscribe_client($$invalidate(0, client = $$props.client)); if ("clientManager" in $$props) $$invalidate(2, clientManager = $$props.clientManager); }; return [client, $client, clientManager]; } class Info extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1yzq5o8-style")) add_css$f(); init(this, options, instance$l, create_fragment$l, safe_not_equal, { client: 0, clientManager: 2 }); } } /* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.24.0 */ function add_css$g() { var style = element("style"); style.id = "svelte-6eza86-style"; style.textContent = ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}"; append(document.head, style); } function create_fragment$m(ctx) { let div; let t; return { c() { div = element("div"); t = text(/*turn*/ ctx[0]); attr(div, "class", "turn-marker svelte-6eza86"); attr(div, "style", /*style*/ ctx[1]); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(ctx, [dirty]) { if (dirty & /*turn*/ 1) set_data(t, /*turn*/ ctx[0]); }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); } }; } function instance$m($$self, $$props, $$invalidate) { let { turn } = $$props; let { numEvents } = $$props; const style = `grid-row: span ${numEvents}`; $$self.$set = $$props => { if ("turn" in $$props) $$invalidate(0, turn = $$props.turn); if ("numEvents" in $$props) $$invalidate(2, numEvents = $$props.numEvents); }; return [turn, style, numEvents]; } class TurnMarker extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-6eza86-style")) add_css$g(); init(this, options, instance$m, create_fragment$m, safe_not_equal, { turn: 0, numEvents: 2 }); } } /* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.24.0 */ function add_css$h() { var style = element("style"); style.id = "svelte-1t4xap-style"; style.textContent = ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}"; append(document.head, style); } function create_fragment$n(ctx) { let div; let t_value = (/*phase*/ ctx[0] || "") + ""; let t; return { c() { div = element("div"); t = text(t_value); attr(div, "class", "phase-marker svelte-1t4xap"); attr(div, "style", /*style*/ ctx[1]); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(ctx, [dirty]) { if (dirty & /*phase*/ 1 && t_value !== (t_value = (/*phase*/ ctx[0] || "") + "")) set_data(t, t_value); }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); } }; } function instance$n($$self, $$props, $$invalidate) { let { phase } = $$props; let { numEvents } = $$props; const style = `grid-row: span ${numEvents}`; $$self.$set = $$props => { if ("phase" in $$props) $$invalidate(0, phase = $$props.phase); if ("numEvents" in $$props) $$invalidate(2, numEvents = $$props.numEvents); }; return [phase, style, numEvents]; } class PhaseMarker extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1t4xap-style")) add_css$h(); init(this, options, instance$n, create_fragment$n, safe_not_equal, { phase: 0, numEvents: 2 }); } } /* src/client/debug/log/LogMetadata.svelte generated by Svelte v3.24.0 */ function create_fragment$o(ctx) { let div; return { c() { div = element("div"); div.textContent = `${/*renderedMetadata*/ ctx[0]}`; }, m(target, anchor) { insert(target, div, anchor); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) detach(div); } }; } function instance$o($$self, $$props, $$invalidate) { let { metadata } = $$props; const renderedMetadata = metadata !== undefined ? JSON.stringify(metadata, null, 4) : ""; $$self.$set = $$props => { if ("metadata" in $$props) $$invalidate(1, metadata = $$props.metadata); }; return [renderedMetadata, metadata]; } class LogMetadata extends SvelteComponent { constructor(options) { super(); init(this, options, instance$o, create_fragment$o, safe_not_equal, { metadata: 1 }); } } /* src/client/debug/log/LogEvent.svelte generated by Svelte v3.24.0 */ function add_css$i() { var style = element("style"); style.id = "svelte-11hs70q-style"; style.textContent = ".log-event.svelte-11hs70q{grid-column:2;cursor:pointer;overflow:hidden;display:flex;flex-direction:column;justify-content:center;background:#fff;border:1px dotted #ccc;border-left:5px solid #ccc;padding:5px;text-align:center;color:#666;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-11hs70q:hover,.log-event.svelte-11hs70q:focus{border-style:solid;background:#eee}.log-event.pinned.svelte-11hs70q{border-style:solid;background:#eee;opacity:1}.player0.svelte-11hs70q{border-left-color:#ff851b}.player1.svelte-11hs70q{border-left-color:#7fdbff}.player2.svelte-11hs70q{border-left-color:#0074d9}.player3.svelte-11hs70q{border-left-color:#39cccc}.player4.svelte-11hs70q{border-left-color:#3d9970}.player5.svelte-11hs70q{border-left-color:#2ecc40}.player6.svelte-11hs70q{border-left-color:#01ff70}.player7.svelte-11hs70q{border-left-color:#ffdc00}.player8.svelte-11hs70q{border-left-color:#001f3f}.player9.svelte-11hs70q{border-left-color:#ff4136}.player10.svelte-11hs70q{border-left-color:#85144b}.player11.svelte-11hs70q{border-left-color:#f012be}.player12.svelte-11hs70q{border-left-color:#b10dc9}.player13.svelte-11hs70q{border-left-color:#111111}.player14.svelte-11hs70q{border-left-color:#aaaaaa}.player15.svelte-11hs70q{border-left-color:#dddddd}"; append(document.head, style); } // (139:2) {:else} function create_else_block$1(ctx) { let logmetadata; let current; logmetadata = new LogMetadata({ props: { metadata: /*metadata*/ ctx[2] } }); return { c() { create_component(logmetadata.$$.fragment); }, m(target, anchor) { mount_component(logmetadata, target, anchor); current = true; }, p(ctx, dirty) { const logmetadata_changes = {}; if (dirty & /*metadata*/ 4) logmetadata_changes.metadata = /*metadata*/ ctx[2]; logmetadata.$set(logmetadata_changes); }, i(local) { if (current) return; transition_in(logmetadata.$$.fragment, local); current = true; }, o(local) { transition_out(logmetadata.$$.fragment, local); current = false; }, d(detaching) { destroy_component(logmetadata, detaching); } }; } // (137:2) {#if metadataComponent} function create_if_block$8(ctx) { let switch_instance; let switch_instance_anchor; let current; var switch_value = /*metadataComponent*/ ctx[3]; function switch_props(ctx) { return { props: { metadata: /*metadata*/ ctx[2] } }; } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); } return { c() { if (switch_instance) create_component(switch_instance.$$.fragment); switch_instance_anchor = empty(); }, m(target, anchor) { if (switch_instance) { mount_component(switch_instance, target, anchor); } insert(target, switch_instance_anchor, anchor); current = true; }, p(ctx, dirty) { const switch_instance_changes = {}; if (dirty & /*metadata*/ 4) switch_instance_changes.metadata = /*metadata*/ ctx[2]; if (switch_value !== (switch_value = /*metadataComponent*/ ctx[3])) { if (switch_instance) { group_outros(); const old_component = switch_instance; transition_out(old_component.$$.fragment, 1, 0, () => { destroy_component(old_component, 1); }); check_outros(); } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); create_component(switch_instance.$$.fragment); transition_in(switch_instance.$$.fragment, 1); mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor); } else { switch_instance = null; } } else if (switch_value) { switch_instance.$set(switch_instance_changes); } }, i(local) { if (current) return; if (switch_instance) transition_in(switch_instance.$$.fragment, local); current = true; }, o(local) { if (switch_instance) transition_out(switch_instance.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(switch_instance_anchor); if (switch_instance) destroy_component(switch_instance, detaching); } }; } function create_fragment$p(ctx) { let button; let div; let t0; let t1; let t2; let t3; let t4; let current_block_type_index; let if_block; let button_class_value; let current; let mounted; let dispose; const if_block_creators = [create_if_block$8, create_else_block$1]; const if_blocks = []; function select_block_type(ctx, dirty) { if (/*metadataComponent*/ ctx[3]) return 0; return 1; } current_block_type_index = select_block_type(ctx); if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); return { c() { button = element("button"); div = element("div"); t0 = text(/*actionType*/ ctx[4]); t1 = text("("); t2 = text(/*renderedArgs*/ ctx[6]); t3 = text(")"); t4 = space(); if_block.c(); attr(button, "class", button_class_value = "log-event player" + /*playerID*/ ctx[7] + " svelte-11hs70q"); toggle_class(button, "pinned", /*pinned*/ ctx[1]); }, m(target, anchor) { insert(target, button, anchor); append(button, div); append(div, t0); append(div, t1); append(div, t2); append(div, t3); append(button, t4); if_blocks[current_block_type_index].m(button, null); current = true; if (!mounted) { dispose = [ listen(button, "click", /*click_handler*/ ctx[9]), listen(button, "mouseenter", /*mouseenter_handler*/ ctx[10]), listen(button, "focus", /*focus_handler*/ ctx[11]), listen(button, "mouseleave", /*mouseleave_handler*/ ctx[12]), listen(button, "blur", /*blur_handler*/ ctx[13]) ]; mounted = true; } }, p(ctx, [dirty]) { if (!current || dirty & /*actionType*/ 16) set_data(t0, /*actionType*/ ctx[4]); let previous_block_index = current_block_type_index; current_block_type_index = select_block_type(ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(ctx, dirty); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block = if_blocks[current_block_type_index]; if (!if_block) { if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block.c(); } transition_in(if_block, 1); if_block.m(button, null); } if (dirty & /*pinned*/ 2) { toggle_class(button, "pinned", /*pinned*/ ctx[1]); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (detaching) detach(button); if_blocks[current_block_type_index].d(); mounted = false; run_all(dispose); } }; } function instance$p($$self, $$props, $$invalidate) { let { logIndex } = $$props; let { action } = $$props; let { pinned } = $$props; let { metadata } = $$props; let { metadataComponent } = $$props; const dispatch = createEventDispatcher(); const args = action.payload.args; const renderedArgs = typeof args === "string" ? args : (args || []).join(","); const playerID = action.payload.playerID; let actionType; switch (action.type) { case "UNDO": actionType = "undo"; break; case "REDO": actionType = "redo"; case "GAME_EVENT": case "MAKE_MOVE": default: actionType = action.payload.type; break; } const click_handler = () => dispatch("click", { logIndex }); const mouseenter_handler = () => dispatch("mouseenter", { logIndex }); const focus_handler = () => dispatch("mouseenter", { logIndex }); const mouseleave_handler = () => dispatch("mouseleave"); const blur_handler = () => dispatch("mouseleave"); $$self.$set = $$props => { if ("logIndex" in $$props) $$invalidate(0, logIndex = $$props.logIndex); if ("action" in $$props) $$invalidate(8, action = $$props.action); if ("pinned" in $$props) $$invalidate(1, pinned = $$props.pinned); if ("metadata" in $$props) $$invalidate(2, metadata = $$props.metadata); if ("metadataComponent" in $$props) $$invalidate(3, metadataComponent = $$props.metadataComponent); }; return [ logIndex, pinned, metadata, metadataComponent, actionType, dispatch, renderedArgs, playerID, action, click_handler, mouseenter_handler, focus_handler, mouseleave_handler, blur_handler ]; } class LogEvent extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-11hs70q-style")) add_css$i(); init(this, options, instance$p, create_fragment$p, safe_not_equal, { logIndex: 0, action: 8, pinned: 1, metadata: 2, metadataComponent: 3 }); } } /* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.24.0 */ function add_css$j() { var style = element("style"); style.id = "svelte-c8tyih-style"; style.textContent = "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}"; append(document.head, style); } // (18:2) {#if title} function create_if_block$9(ctx) { let title_1; let t; return { c() { title_1 = svg_element("title"); t = text(/*title*/ ctx[0]); }, m(target, anchor) { insert(target, title_1, anchor); append(title_1, t); }, p(ctx, dirty) { if (dirty & /*title*/ 1) set_data(t, /*title*/ ctx[0]); }, d(detaching) { if (detaching) detach(title_1); } }; } function create_fragment$q(ctx) { let svg; let if_block_anchor; let current; let if_block = /*title*/ ctx[0] && create_if_block$9(ctx); const default_slot_template = /*$$slots*/ ctx[3].default; const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[2], null); return { c() { svg = svg_element("svg"); if (if_block) if_block.c(); if_block_anchor = empty(); if (default_slot) default_slot.c(); attr(svg, "xmlns", "http://www.w3.org/2000/svg"); attr(svg, "viewBox", /*viewBox*/ ctx[1]); attr(svg, "class", "svelte-c8tyih"); }, m(target, anchor) { insert(target, svg, anchor); if (if_block) if_block.m(svg, null); append(svg, if_block_anchor); if (default_slot) { default_slot.m(svg, null); } current = true; }, p(ctx, [dirty]) { if (/*title*/ ctx[0]) { if (if_block) { if_block.p(ctx, dirty); } else { if_block = create_if_block$9(ctx); if_block.c(); if_block.m(svg, if_block_anchor); } } else if (if_block) { if_block.d(1); if_block = null; } if (default_slot) { if (default_slot.p && dirty & /*$$scope*/ 4) { update_slot(default_slot, default_slot_template, ctx, /*$$scope*/ ctx[2], dirty, null, null); } } if (!current || dirty & /*viewBox*/ 2) { attr(svg, "viewBox", /*viewBox*/ ctx[1]); } }, i(local) { if (current) return; transition_in(default_slot, local); current = true; }, o(local) { transition_out(default_slot, local); current = false; }, d(detaching) { if (detaching) detach(svg); if (if_block) if_block.d(); if (default_slot) default_slot.d(detaching); } }; } function instance$q($$self, $$props, $$invalidate) { let { title = null } = $$props; let { viewBox } = $$props; let { $$slots = {}, $$scope } = $$props; $$self.$set = $$props => { if ("title" in $$props) $$invalidate(0, title = $$props.title); if ("viewBox" in $$props) $$invalidate(1, viewBox = $$props.viewBox); if ("$$scope" in $$props) $$invalidate(2, $$scope = $$props.$$scope); }; return [title, viewBox, $$scope, $$slots]; } class IconBase extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-c8tyih-style")) add_css$j(); init(this, options, instance$q, create_fragment$q, safe_not_equal, { title: 0, viewBox: 1 }); } } /* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.24.0 */ function create_default_slot(ctx) { let path; return { c() { path = svg_element("path"); attr(path, "d", "M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z"); }, m(target, anchor) { insert(target, path, anchor); }, d(detaching) { if (detaching) detach(path); } }; } function create_fragment$r(ctx) { let iconbase; let current; const iconbase_spread_levels = [{ viewBox: "0 0 512 512" }, /*$$props*/ ctx[0]]; let iconbase_props = { $$slots: { default: [create_default_slot] }, $$scope: { ctx } }; for (let i = 0; i < iconbase_spread_levels.length; i += 1) { iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]); } iconbase = new IconBase({ props: iconbase_props }); return { c() { create_component(iconbase.$$.fragment); }, m(target, anchor) { mount_component(iconbase, target, anchor); current = true; }, p(ctx, [dirty]) { const iconbase_changes = (dirty & /*$$props*/ 1) ? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])]) : {}; if (dirty & /*$$scope*/ 2) { iconbase_changes.$$scope = { dirty, ctx }; } iconbase.$set(iconbase_changes); }, i(local) { if (current) return; transition_in(iconbase.$$.fragment, local); current = true; }, o(local) { transition_out(iconbase.$$.fragment, local); current = false; }, d(detaching) { destroy_component(iconbase, detaching); } }; } function instance$r($$self, $$props, $$invalidate) { $$self.$set = $$new_props => { $$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); }; $$props = exclude_internal_props($$props); return [$$props]; } class FaArrowAltCircleDown extends SvelteComponent { constructor(options) { super(); init(this, options, instance$r, create_fragment$r, safe_not_equal, {}); } } /* src/client/debug/mcts/Action.svelte generated by Svelte v3.24.0 */ function add_css$k() { var style = element("style"); style.id = "svelte-1a7time-style"; style.textContent = "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}"; append(document.head, style); } function create_fragment$s(ctx) { let div; let t; return { c() { div = element("div"); t = text(/*text*/ ctx[0]); attr(div, "alt", /*text*/ ctx[0]); attr(div, "class", "svelte-1a7time"); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(ctx, [dirty]) { if (dirty & /*text*/ 1) set_data(t, /*text*/ ctx[0]); if (dirty & /*text*/ 1) { attr(div, "alt", /*text*/ ctx[0]); } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); } }; } function instance$s($$self, $$props, $$invalidate) { let { action } = $$props; let text; $$self.$set = $$props => { if ("action" in $$props) $$invalidate(1, action = $$props.action); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*action*/ 2) { $: { const { type, args } = action.payload; const argsFormatted = (args || []).join(","); $$invalidate(0, text = `${type}(${argsFormatted})`); } } }; return [text, action]; } class Action extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1a7time-style")) add_css$k(); init(this, options, instance$s, create_fragment$s, safe_not_equal, { action: 1 }); } } /* src/client/debug/mcts/Table.svelte generated by Svelte v3.24.0 */ function add_css$l() { var style = element("style"); style.id = "svelte-ztcwsu-style"; style.textContent = "table.svelte-ztcwsu.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.svelte-ztcwsu.svelte-ztcwsu{cursor:pointer}tr.svelte-ztcwsu:hover td.svelte-ztcwsu{background:#eee}tr.selected.svelte-ztcwsu td.svelte-ztcwsu{background:#eee}td.svelte-ztcwsu.svelte-ztcwsu{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}"; append(document.head, style); } function get_each_context$6(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[10] = list[i]; child_ctx[12] = i; return child_ctx; } // (86:2) {#each children as child, i} function create_each_block$6(ctx) { let tr; let td0; let t0_value = /*child*/ ctx[10].value + ""; let t0; let t1; let td1; let t2_value = /*child*/ ctx[10].visits + ""; let t2; let t3; let td2; let action; let t4; let current; let mounted; let dispose; action = new Action({ props: { action: /*child*/ ctx[10].parentAction } }); function click_handler(...args) { return /*click_handler*/ ctx[5](/*child*/ ctx[10], /*i*/ ctx[12], ...args); } function mouseout_handler(...args) { return /*mouseout_handler*/ ctx[6](/*i*/ ctx[12], ...args); } function mouseover_handler(...args) { return /*mouseover_handler*/ ctx[7](/*child*/ ctx[10], /*i*/ ctx[12], ...args); } return { c() { tr = element("tr"); td0 = element("td"); t0 = text(t0_value); t1 = space(); td1 = element("td"); t2 = text(t2_value); t3 = space(); td2 = element("td"); create_component(action.$$.fragment); t4 = space(); attr(td0, "class", "svelte-ztcwsu"); attr(td1, "class", "svelte-ztcwsu"); attr(td2, "class", "svelte-ztcwsu"); attr(tr, "class", "svelte-ztcwsu"); toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0); toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]); }, m(target, anchor) { insert(target, tr, anchor); append(tr, td0); append(td0, t0); append(tr, t1); append(tr, td1); append(td1, t2); append(tr, t3); append(tr, td2); mount_component(action, td2, null); append(tr, t4); current = true; if (!mounted) { dispose = [ listen(tr, "click", click_handler), listen(tr, "mouseout", mouseout_handler), listen(tr, "mouseover", mouseover_handler) ]; mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if ((!current || dirty & /*children*/ 2) && t0_value !== (t0_value = /*child*/ ctx[10].value + "")) set_data(t0, t0_value); if ((!current || dirty & /*children*/ 2) && t2_value !== (t2_value = /*child*/ ctx[10].visits + "")) set_data(t2, t2_value); const action_changes = {}; if (dirty & /*children*/ 2) action_changes.action = /*child*/ ctx[10].parentAction; action.$set(action_changes); if (dirty & /*children*/ 2) { toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0); } if (dirty & /*selectedIndex*/ 1) { toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]); } }, i(local) { if (current) return; transition_in(action.$$.fragment, local); current = true; }, o(local) { transition_out(action.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(tr); destroy_component(action); mounted = false; run_all(dispose); } }; } function create_fragment$t(ctx) { let table; let thead; let t5; let tbody; let current; let each_value = /*children*/ ctx[1]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$6(get_each_context$6(ctx, each_value, i)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); return { c() { table = element("table"); thead = element("thead"); thead.innerHTML = `<th class="svelte-ztcwsu">Value</th> <th class="svelte-ztcwsu">Visits</th> <th class="svelte-ztcwsu">Action</th>`; t5 = space(); tbody = element("tbody"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(table, "class", "svelte-ztcwsu"); }, m(target, anchor) { insert(target, table, anchor); append(table, thead); append(table, t5); append(table, tbody); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(tbody, null); } current = true; }, p(ctx, [dirty]) { if (dirty & /*children, selectedIndex, Select, Preview*/ 15) { each_value = /*children*/ ctx[1]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$6(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$6(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(tbody, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } }, i(local) { if (current) return; for (let i = 0; i < each_value.length; i += 1) { transition_in(each_blocks[i]); } current = true; }, o(local) { each_blocks = each_blocks.filter(Boolean); for (let i = 0; i < each_blocks.length; i += 1) { transition_out(each_blocks[i]); } current = false; }, d(detaching) { if (detaching) detach(table); destroy_each(each_blocks, detaching); } }; } function instance$t($$self, $$props, $$invalidate) { let { root } = $$props; let { selectedIndex = null } = $$props; const dispatch = createEventDispatcher(); let parents = []; let children = []; function Select(node, i) { dispatch("select", { node, selectedIndex: i }); } function Preview(node, i) { if (selectedIndex === null) { dispatch("preview", { node }); } } const click_handler = (child, i) => Select(child, i); const mouseout_handler = i => Preview(null); const mouseover_handler = (child, i) => Preview(child); $$self.$set = $$props => { if ("root" in $$props) $$invalidate(4, root = $$props.root); if ("selectedIndex" in $$props) $$invalidate(0, selectedIndex = $$props.selectedIndex); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*root, parents*/ 272) { $: { let t = root; $$invalidate(8, parents = []); while (t.parent) { const parent = t.parent; const { type, args } = t.parentAction.payload; const argsFormatted = (args || []).join(","); const arrowText = `${type}(${argsFormatted})`; parents.push({ parent, arrowText }); t = parent; } parents.reverse(); $$invalidate(1, children = [...root.children].sort((a, b) => a.visits < b.visits ? 1 : -1).slice(0, 50)); } } }; return [ selectedIndex, children, Select, Preview, root, click_handler, mouseout_handler, mouseover_handler ]; } class Table extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-ztcwsu-style")) add_css$l(); init(this, options, instance$t, create_fragment$t, safe_not_equal, { root: 4, selectedIndex: 0 }); } } /* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.24.0 */ function add_css$m() { var style = element("style"); style.id = "svelte-1f0amz4-style"; style.textContent = ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}"; append(document.head, style); } function get_each_context$7(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[9] = list[i].node; child_ctx[10] = list[i].selectedIndex; child_ctx[12] = i; return child_ctx; } // (50:4) {#if i !== 0} function create_if_block_2$3(ctx) { let div; let arrow; let current; arrow = new FaArrowAltCircleDown({}); return { c() { div = element("div"); create_component(arrow.$$.fragment); attr(div, "class", "icon svelte-1f0amz4"); }, m(target, anchor) { insert(target, div, anchor); mount_component(arrow, div, null); current = true; }, i(local) { if (current) return; transition_in(arrow.$$.fragment, local); current = true; }, o(local) { transition_out(arrow.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(div); destroy_component(arrow); } }; } // (61:6) {:else} function create_else_block$2(ctx) { let table; let current; function select_handler_1(...args) { return /*select_handler_1*/ ctx[7](/*i*/ ctx[12], ...args); } table = new Table({ props: { root: /*node*/ ctx[9], selectedIndex: /*selectedIndex*/ ctx[10] } }); table.$on("select", select_handler_1); return { c() { create_component(table.$$.fragment); }, m(target, anchor) { mount_component(table, target, anchor); current = true; }, p(new_ctx, dirty) { ctx = new_ctx; const table_changes = {}; if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9]; if (dirty & /*nodes*/ 1) table_changes.selectedIndex = /*selectedIndex*/ ctx[10]; table.$set(table_changes); }, i(local) { if (current) return; transition_in(table.$$.fragment, local); current = true; }, o(local) { transition_out(table.$$.fragment, local); current = false; }, d(detaching) { destroy_component(table, detaching); } }; } // (57:6) {#if i === nodes.length - 1} function create_if_block_1$3(ctx) { let table; let current; function select_handler(...args) { return /*select_handler*/ ctx[5](/*i*/ ctx[12], ...args); } function preview_handler(...args) { return /*preview_handler*/ ctx[6](/*i*/ ctx[12], ...args); } table = new Table({ props: { root: /*node*/ ctx[9] } }); table.$on("select", select_handler); table.$on("preview", preview_handler); return { c() { create_component(table.$$.fragment); }, m(target, anchor) { mount_component(table, target, anchor); current = true; }, p(new_ctx, dirty) { ctx = new_ctx; const table_changes = {}; if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9]; table.$set(table_changes); }, i(local) { if (current) return; transition_in(table.$$.fragment, local); current = true; }, o(local) { transition_out(table.$$.fragment, local); current = false; }, d(detaching) { destroy_component(table, detaching); } }; } // (49:2) {#each nodes as { node, selectedIndex } function create_each_block$7(ctx) { let t; let section; let current_block_type_index; let if_block1; let current; let if_block0 = /*i*/ ctx[12] !== 0 && create_if_block_2$3(); const if_block_creators = [create_if_block_1$3, create_else_block$2]; const if_blocks = []; function select_block_type(ctx, dirty) { if (/*i*/ ctx[12] === /*nodes*/ ctx[0].length - 1) return 0; return 1; } current_block_type_index = select_block_type(ctx); if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); return { c() { if (if_block0) if_block0.c(); t = space(); section = element("section"); if_block1.c(); }, m(target, anchor) { if (if_block0) if_block0.m(target, anchor); insert(target, t, anchor); insert(target, section, anchor); if_blocks[current_block_type_index].m(section, null); current = true; }, p(ctx, dirty) { let previous_block_index = current_block_type_index; current_block_type_index = select_block_type(ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(ctx, dirty); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block1 = if_blocks[current_block_type_index]; if (!if_block1) { if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block1.c(); } transition_in(if_block1, 1); if_block1.m(section, null); } }, i(local) { if (current) return; transition_in(if_block0); transition_in(if_block1); current = true; }, o(local) { transition_out(if_block0); transition_out(if_block1); current = false; }, d(detaching) { if (if_block0) if_block0.d(detaching); if (detaching) detach(t); if (detaching) detach(section); if_blocks[current_block_type_index].d(); } }; } // (69:2) {#if preview} function create_if_block$a(ctx) { let div; let arrow; let t; let section; let table; let current; arrow = new FaArrowAltCircleDown({}); table = new Table({ props: { root: /*preview*/ ctx[1] } }); return { c() { div = element("div"); create_component(arrow.$$.fragment); t = space(); section = element("section"); create_component(table.$$.fragment); attr(div, "class", "icon svelte-1f0amz4"); attr(section, "class", "preview svelte-1f0amz4"); }, m(target, anchor) { insert(target, div, anchor); mount_component(arrow, div, null); insert(target, t, anchor); insert(target, section, anchor); mount_component(table, section, null); current = true; }, p(ctx, dirty) { const table_changes = {}; if (dirty & /*preview*/ 2) table_changes.root = /*preview*/ ctx[1]; table.$set(table_changes); }, i(local) { if (current) return; transition_in(arrow.$$.fragment, local); transition_in(table.$$.fragment, local); current = true; }, o(local) { transition_out(arrow.$$.fragment, local); transition_out(table.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(div); destroy_component(arrow); if (detaching) detach(t); if (detaching) detach(section); destroy_component(table); } }; } function create_fragment$u(ctx) { let div; let t; let current; let each_value = /*nodes*/ ctx[0]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$7(get_each_context$7(ctx, each_value, i)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); let if_block = /*preview*/ ctx[1] && create_if_block$a(ctx); return { c() { div = element("div"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } t = space(); if (if_block) if_block.c(); attr(div, "class", "visualizer svelte-1f0amz4"); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(div, null); } append(div, t); if (if_block) if_block.m(div, null); current = true; }, p(ctx, [dirty]) { if (dirty & /*nodes, SelectNode, PreviewNode*/ 13) { each_value = /*nodes*/ ctx[0]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$7(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$7(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(div, t); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } if (/*preview*/ ctx[1]) { if (if_block) { if_block.p(ctx, dirty); if (dirty & /*preview*/ 2) { transition_in(if_block, 1); } } else { if_block = create_if_block$a(ctx); if_block.c(); transition_in(if_block, 1); if_block.m(div, null); } } else if (if_block) { group_outros(); transition_out(if_block, 1, 1, () => { if_block = null; }); check_outros(); } }, i(local) { if (current) return; for (let i = 0; i < each_value.length; i += 1) { transition_in(each_blocks[i]); } transition_in(if_block); current = true; }, o(local) { each_blocks = each_blocks.filter(Boolean); for (let i = 0; i < each_blocks.length; i += 1) { transition_out(each_blocks[i]); } transition_out(if_block); current = false; }, d(detaching) { if (detaching) detach(div); destroy_each(each_blocks, detaching); if (if_block) if_block.d(); } }; } function instance$u($$self, $$props, $$invalidate) { let { metadata } = $$props; let nodes = []; let preview = null; function SelectNode({ node, selectedIndex }, i) { $$invalidate(1, preview = null); $$invalidate(0, nodes[i].selectedIndex = selectedIndex, nodes); $$invalidate(0, nodes = [...nodes.slice(0, i + 1), { node }]); } function PreviewNode({ node }, i) { $$invalidate(1, preview = node); } const select_handler = (i, e) => SelectNode(e.detail, i); const preview_handler = (i, e) => PreviewNode(e.detail); const select_handler_1 = (i, e) => SelectNode(e.detail, i); $$self.$set = $$props => { if ("metadata" in $$props) $$invalidate(4, metadata = $$props.metadata); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*metadata*/ 16) { $: { $$invalidate(0, nodes = [{ node: metadata }]); } } }; return [ nodes, preview, SelectNode, PreviewNode, metadata, select_handler, preview_handler, select_handler_1 ]; } class MCTS extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1f0amz4-style")) add_css$m(); init(this, options, instance$u, create_fragment$u, safe_not_equal, { metadata: 4 }); } } /* src/client/debug/log/Log.svelte generated by Svelte v3.24.0 */ function add_css$n() { var style = element("style"); style.id = "svelte-1pq5e4b-style"; style.textContent = ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}"; append(document.head, style); } function get_each_context$8(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[16] = list[i].phase; child_ctx[18] = i; return child_ctx; } function get_each_context_1(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[19] = list[i].action; child_ctx[20] = list[i].metadata; child_ctx[18] = i; return child_ctx; } function get_each_context_2(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[22] = list[i].turn; child_ctx[18] = i; return child_ctx; } // (136:4) {#if i in turnBoundaries} function create_if_block_1$4(ctx) { let turnmarker; let current; turnmarker = new TurnMarker({ props: { turn: /*turn*/ ctx[22], numEvents: /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]] } }); return { c() { create_component(turnmarker.$$.fragment); }, m(target, anchor) { mount_component(turnmarker, target, anchor); current = true; }, p(ctx, dirty) { const turnmarker_changes = {}; if (dirty & /*renderedLogEntries*/ 4) turnmarker_changes.turn = /*turn*/ ctx[22]; if (dirty & /*turnBoundaries*/ 8) turnmarker_changes.numEvents = /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]]; turnmarker.$set(turnmarker_changes); }, i(local) { if (current) return; transition_in(turnmarker.$$.fragment, local); current = true; }, o(local) { transition_out(turnmarker.$$.fragment, local); current = false; }, d(detaching) { destroy_component(turnmarker, detaching); } }; } // (135:2) {#each renderedLogEntries as { turn } function create_each_block_2(ctx) { let if_block_anchor; let current; let if_block = /*i*/ ctx[18] in /*turnBoundaries*/ ctx[3] && create_if_block_1$4(ctx); return { c() { if (if_block) if_block.c(); if_block_anchor = empty(); }, m(target, anchor) { if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); current = true; }, p(ctx, dirty) { if (/*i*/ ctx[18] in /*turnBoundaries*/ ctx[3]) { if (if_block) { if_block.p(ctx, dirty); if (dirty & /*turnBoundaries*/ 8) { transition_in(if_block, 1); } } else { if_block = create_if_block_1$4(ctx); if_block.c(); transition_in(if_block, 1); if_block.m(if_block_anchor.parentNode, if_block_anchor); } } else if (if_block) { group_outros(); transition_out(if_block, 1, 1, () => { if_block = null; }); check_outros(); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (if_block) if_block.d(detaching); if (detaching) detach(if_block_anchor); } }; } // (141:2) {#each renderedLogEntries as { action, metadata } function create_each_block_1(ctx) { let logevent; let current; logevent = new LogEvent({ props: { pinned: /*i*/ ctx[18] === /*pinned*/ ctx[1], logIndex: /*i*/ ctx[18], action: /*action*/ ctx[19], metadata: /*metadata*/ ctx[20] } }); logevent.$on("click", /*OnLogClick*/ ctx[5]); logevent.$on("mouseenter", /*OnMouseEnter*/ ctx[6]); logevent.$on("mouseleave", /*OnMouseLeave*/ ctx[7]); return { c() { create_component(logevent.$$.fragment); }, m(target, anchor) { mount_component(logevent, target, anchor); current = true; }, p(ctx, dirty) { const logevent_changes = {}; if (dirty & /*pinned*/ 2) logevent_changes.pinned = /*i*/ ctx[18] === /*pinned*/ ctx[1]; if (dirty & /*renderedLogEntries*/ 4) logevent_changes.action = /*action*/ ctx[19]; if (dirty & /*renderedLogEntries*/ 4) logevent_changes.metadata = /*metadata*/ ctx[20]; logevent.$set(logevent_changes); }, i(local) { if (current) return; transition_in(logevent.$$.fragment, local); current = true; }, o(local) { transition_out(logevent.$$.fragment, local); current = false; }, d(detaching) { destroy_component(logevent, detaching); } }; } // (153:4) {#if i in phaseBoundaries} function create_if_block$b(ctx) { let phasemarker; let current; phasemarker = new PhaseMarker({ props: { phase: /*phase*/ ctx[16], numEvents: /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]] } }); return { c() { create_component(phasemarker.$$.fragment); }, m(target, anchor) { mount_component(phasemarker, target, anchor); current = true; }, p(ctx, dirty) { const phasemarker_changes = {}; if (dirty & /*renderedLogEntries*/ 4) phasemarker_changes.phase = /*phase*/ ctx[16]; if (dirty & /*phaseBoundaries*/ 16) phasemarker_changes.numEvents = /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]]; phasemarker.$set(phasemarker_changes); }, i(local) { if (current) return; transition_in(phasemarker.$$.fragment, local); current = true; }, o(local) { transition_out(phasemarker.$$.fragment, local); current = false; }, d(detaching) { destroy_component(phasemarker, detaching); } }; } // (152:2) {#each renderedLogEntries as { phase } function create_each_block$8(ctx) { let if_block_anchor; let current; let if_block = /*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4] && create_if_block$b(ctx); return { c() { if (if_block) if_block.c(); if_block_anchor = empty(); }, m(target, anchor) { if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); current = true; }, p(ctx, dirty) { if (/*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4]) { if (if_block) { if_block.p(ctx, dirty); if (dirty & /*phaseBoundaries*/ 16) { transition_in(if_block, 1); } } else { if_block = create_if_block$b(ctx); if_block.c(); transition_in(if_block, 1); if_block.m(if_block_anchor.parentNode, if_block_anchor); } } else if (if_block) { group_outros(); transition_out(if_block, 1, 1, () => { if_block = null; }); check_outros(); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (if_block) if_block.d(detaching); if (detaching) detach(if_block_anchor); } }; } function create_fragment$v(ctx) { let div; let t0; let t1; let current; let mounted; let dispose; let each_value_2 = /*renderedLogEntries*/ ctx[2]; let each_blocks_2 = []; for (let i = 0; i < each_value_2.length; i += 1) { each_blocks_2[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i)); } const out = i => transition_out(each_blocks_2[i], 1, 1, () => { each_blocks_2[i] = null; }); let each_value_1 = /*renderedLogEntries*/ ctx[2]; let each_blocks_1 = []; for (let i = 0; i < each_value_1.length; i += 1) { each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i)); } const out_1 = i => transition_out(each_blocks_1[i], 1, 1, () => { each_blocks_1[i] = null; }); let each_value = /*renderedLogEntries*/ ctx[2]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$8(get_each_context$8(ctx, each_value, i)); } const out_2 = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); return { c() { div = element("div"); for (let i = 0; i < each_blocks_2.length; i += 1) { each_blocks_2[i].c(); } t0 = space(); for (let i = 0; i < each_blocks_1.length; i += 1) { each_blocks_1[i].c(); } t1 = space(); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(div, "class", "gamelog svelte-1pq5e4b"); toggle_class(div, "pinned", /*pinned*/ ctx[1]); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks_2.length; i += 1) { each_blocks_2[i].m(div, null); } append(div, t0); for (let i = 0; i < each_blocks_1.length; i += 1) { each_blocks_1[i].m(div, null); } append(div, t1); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(div, null); } current = true; if (!mounted) { dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[8]); mounted = true; } }, p(ctx, [dirty]) { if (dirty & /*renderedLogEntries, turnBoundaries*/ 12) { each_value_2 = /*renderedLogEntries*/ ctx[2]; let i; for (i = 0; i < each_value_2.length; i += 1) { const child_ctx = get_each_context_2(ctx, each_value_2, i); if (each_blocks_2[i]) { each_blocks_2[i].p(child_ctx, dirty); transition_in(each_blocks_2[i], 1); } else { each_blocks_2[i] = create_each_block_2(child_ctx); each_blocks_2[i].c(); transition_in(each_blocks_2[i], 1); each_blocks_2[i].m(div, t0); } } group_outros(); for (i = each_value_2.length; i < each_blocks_2.length; i += 1) { out(i); } check_outros(); } if (dirty & /*pinned, renderedLogEntries, OnLogClick, OnMouseEnter, OnMouseLeave*/ 230) { each_value_1 = /*renderedLogEntries*/ ctx[2]; let i; for (i = 0; i < each_value_1.length; i += 1) { const child_ctx = get_each_context_1(ctx, each_value_1, i); if (each_blocks_1[i]) { each_blocks_1[i].p(child_ctx, dirty); transition_in(each_blocks_1[i], 1); } else { each_blocks_1[i] = create_each_block_1(child_ctx); each_blocks_1[i].c(); transition_in(each_blocks_1[i], 1); each_blocks_1[i].m(div, t1); } } group_outros(); for (i = each_value_1.length; i < each_blocks_1.length; i += 1) { out_1(i); } check_outros(); } if (dirty & /*renderedLogEntries, phaseBoundaries*/ 20) { each_value = /*renderedLogEntries*/ ctx[2]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$8(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$8(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(div, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out_2(i); } check_outros(); } if (dirty & /*pinned*/ 2) { toggle_class(div, "pinned", /*pinned*/ ctx[1]); } }, i(local) { if (current) return; for (let i = 0; i < each_value_2.length; i += 1) { transition_in(each_blocks_2[i]); } for (let i = 0; i < each_value_1.length; i += 1) { transition_in(each_blocks_1[i]); } for (let i = 0; i < each_value.length; i += 1) { transition_in(each_blocks[i]); } current = true; }, o(local) { each_blocks_2 = each_blocks_2.filter(Boolean); for (let i = 0; i < each_blocks_2.length; i += 1) { transition_out(each_blocks_2[i]); } each_blocks_1 = each_blocks_1.filter(Boolean); for (let i = 0; i < each_blocks_1.length; i += 1) { transition_out(each_blocks_1[i]); } each_blocks = each_blocks.filter(Boolean); for (let i = 0; i < each_blocks.length; i += 1) { transition_out(each_blocks[i]); } current = false; }, d(detaching) { if (detaching) detach(div); destroy_each(each_blocks_2, detaching); destroy_each(each_blocks_1, detaching); destroy_each(each_blocks, detaching); mounted = false; dispose(); } }; } function instance$v($$self, $$props, $$invalidate) { let $client, $$unsubscribe_client = noop, $$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(10, $client = $$value)), client); $$self.$$.on_destroy.push(() => $$unsubscribe_client()); let { client } = $$props; $$subscribe_client(); const { secondaryPane } = getContext("secondaryPane"); const reducer = CreateGameReducer({ game: client.game }); const initialState = client.getInitialState(); let { log } = $client; let pinned = null; function rewind(logIndex) { let state = initialState; for (let i = 0; i < log.length; i++) { const { action, automatic } = log[i]; if (!automatic) { state = reducer(state, action); if (logIndex == 0) { break; } logIndex--; } } return { G: state.G, ctx: state.ctx, plugins: state.plugins }; } function OnLogClick(e) { const { logIndex } = e.detail; const state = rewind(logIndex); const renderedLogEntries = log.filter(e => !e.automatic); client.overrideGameState(state); if (pinned == logIndex) { $$invalidate(1, pinned = null); secondaryPane.set(null); } else { $$invalidate(1, pinned = logIndex); const { metadata } = renderedLogEntries[logIndex].action.payload; if (metadata) { secondaryPane.set({ component: MCTS, metadata }); } } } function OnMouseEnter(e) { const { logIndex } = e.detail; if (pinned === null) { const state = rewind(logIndex); client.overrideGameState(state); } } function OnMouseLeave() { if (pinned === null) { client.overrideGameState(null); } } function Reset() { $$invalidate(1, pinned = null); client.overrideGameState(null); secondaryPane.set(null); } onDestroy(Reset); function OnKeyDown(e) { // ESC. if (e.keyCode == 27) { Reset(); } } let renderedLogEntries; let turnBoundaries = {}; let phaseBoundaries = {}; $$self.$set = $$props => { if ("client" in $$props) $$subscribe_client($$invalidate(0, client = $$props.client)); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*$client, log, renderedLogEntries*/ 1540) { $: { $$invalidate(9, log = $client.log); $$invalidate(2, renderedLogEntries = log.filter(e => !e.automatic)); let eventsInCurrentPhase = 0; let eventsInCurrentTurn = 0; $$invalidate(3, turnBoundaries = {}); $$invalidate(4, phaseBoundaries = {}); for (let i = 0; i < renderedLogEntries.length; i++) { const { action, payload, turn, phase } = renderedLogEntries[i]; eventsInCurrentTurn++; eventsInCurrentPhase++; if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].turn != turn) { $$invalidate(3, turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries); eventsInCurrentTurn = 0; } if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase) { $$invalidate(4, phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries); eventsInCurrentPhase = 0; } } } } }; return [ client, pinned, renderedLogEntries, turnBoundaries, phaseBoundaries, OnLogClick, OnMouseEnter, OnMouseLeave, OnKeyDown ]; } class Log extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1pq5e4b-style")) add_css$n(); init(this, options, instance$v, create_fragment$v, safe_not_equal, { client: 0 }); } } /* src/client/debug/ai/Options.svelte generated by Svelte v3.24.0 */ function add_css$o() { var style = element("style"); style.id = "svelte-1fu900w-style"; style.textContent = "label.svelte-1fu900w{color:#666}.option.svelte-1fu900w{margin-bottom:20px}.value.svelte-1fu900w{font-weight:bold;color:#000}input[type='checkbox'].svelte-1fu900w{vertical-align:middle}"; append(document.head, style); } function get_each_context$9(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[5] = list[i][0]; child_ctx[6] = list[i][1]; return child_ctx; } // (39:4) {#if value.range} function create_if_block_1$5(ctx) { let span; let t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + ""; let t0; let t1; let input; let input_min_value; let input_max_value; let mounted; let dispose; function input_change_input_handler() { /*input_change_input_handler*/ ctx[3].call(input, /*key*/ ctx[5]); } return { c() { span = element("span"); t0 = text(t0_value); t1 = space(); input = element("input"); attr(span, "class", "value svelte-1fu900w"); attr(input, "type", "range"); attr(input, "min", input_min_value = /*value*/ ctx[6].range.min); attr(input, "max", input_max_value = /*value*/ ctx[6].range.max); }, m(target, anchor) { insert(target, span, anchor); append(span, t0); insert(target, t1, anchor); insert(target, input, anchor); set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]); if (!mounted) { dispose = [ listen(input, "change", input_change_input_handler), listen(input, "input", input_change_input_handler), listen(input, "change", /*OnChange*/ ctx[2]) ]; mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if (dirty & /*values, bot*/ 3 && t0_value !== (t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + "")) set_data(t0, t0_value); if (dirty & /*bot*/ 1 && input_min_value !== (input_min_value = /*value*/ ctx[6].range.min)) { attr(input, "min", input_min_value); } if (dirty & /*bot*/ 1 && input_max_value !== (input_max_value = /*value*/ ctx[6].range.max)) { attr(input, "max", input_max_value); } if (dirty & /*values, Object, bot*/ 3) { set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]); } }, d(detaching) { if (detaching) detach(span); if (detaching) detach(t1); if (detaching) detach(input); mounted = false; run_all(dispose); } }; } // (44:4) {#if typeof value.value === 'boolean'} function create_if_block$c(ctx) { let input; let mounted; let dispose; function input_change_handler() { /*input_change_handler*/ ctx[4].call(input, /*key*/ ctx[5]); } return { c() { input = element("input"); attr(input, "type", "checkbox"); attr(input, "class", "svelte-1fu900w"); }, m(target, anchor) { insert(target, input, anchor); input.checked = /*values*/ ctx[1][/*key*/ ctx[5]]; if (!mounted) { dispose = [ listen(input, "change", input_change_handler), listen(input, "change", /*OnChange*/ ctx[2]) ]; mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if (dirty & /*values, Object, bot*/ 3) { input.checked = /*values*/ ctx[1][/*key*/ ctx[5]]; } }, d(detaching) { if (detaching) detach(input); mounted = false; run_all(dispose); } }; } // (35:0) {#each Object.entries(bot.opts()) as [key, value]} function create_each_block$9(ctx) { let div; let label; let t0_value = /*key*/ ctx[5] + ""; let t0; let t1; let t2; let t3; let if_block0 = /*value*/ ctx[6].range && create_if_block_1$5(ctx); let if_block1 = typeof /*value*/ ctx[6].value === "boolean" && create_if_block$c(ctx); return { c() { div = element("div"); label = element("label"); t0 = text(t0_value); t1 = space(); if (if_block0) if_block0.c(); t2 = space(); if (if_block1) if_block1.c(); t3 = space(); attr(label, "class", "svelte-1fu900w"); attr(div, "class", "option svelte-1fu900w"); }, m(target, anchor) { insert(target, div, anchor); append(div, label); append(label, t0); append(div, t1); if (if_block0) if_block0.m(div, null); append(div, t2); if (if_block1) if_block1.m(div, null); append(div, t3); }, p(ctx, dirty) { if (dirty & /*bot*/ 1 && t0_value !== (t0_value = /*key*/ ctx[5] + "")) set_data(t0, t0_value); if (/*value*/ ctx[6].range) { if (if_block0) { if_block0.p(ctx, dirty); } else { if_block0 = create_if_block_1$5(ctx); if_block0.c(); if_block0.m(div, t2); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (typeof /*value*/ ctx[6].value === "boolean") { if (if_block1) { if_block1.p(ctx, dirty); } else { if_block1 = create_if_block$c(ctx); if_block1.c(); if_block1.m(div, t3); } } else if (if_block1) { if_block1.d(1); if_block1 = null; } }, d(detaching) { if (detaching) detach(div); if (if_block0) if_block0.d(); if (if_block1) if_block1.d(); } }; } function create_fragment$w(ctx) { let each_1_anchor; let each_value = Object.entries(/*bot*/ ctx[0].opts()); let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$9(get_each_context$9(ctx, each_value, i)); } return { c() { for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } each_1_anchor = empty(); }, m(target, anchor) { for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(target, anchor); } insert(target, each_1_anchor, anchor); }, p(ctx, [dirty]) { if (dirty & /*values, Object, bot, OnChange*/ 7) { each_value = Object.entries(/*bot*/ ctx[0].opts()); let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$9(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); } else { each_blocks[i] = create_each_block$9(child_ctx); each_blocks[i].c(); each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); } } for (; i < each_blocks.length; i += 1) { each_blocks[i].d(1); } each_blocks.length = each_value.length; } }, i: noop, o: noop, d(detaching) { destroy_each(each_blocks, detaching); if (detaching) detach(each_1_anchor); } }; } function instance$w($$self, $$props, $$invalidate) { let { bot } = $$props; let values = {}; for (let [key, value] of Object.entries(bot.opts())) { values[key] = value.value; } function OnChange() { for (let [key, value] of Object.entries(values)) { bot.setOpt(key, value); } } function input_change_input_handler(key) { values[key] = to_number(this.value); $$invalidate(1, values); $$invalidate(0, bot); } function input_change_handler(key) { values[key] = this.checked; $$invalidate(1, values); $$invalidate(0, bot); } $$self.$set = $$props => { if ("bot" in $$props) $$invalidate(0, bot = $$props.bot); }; return [bot, values, OnChange, input_change_input_handler, input_change_handler]; } class Options extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1fu900w-style")) add_css$o(); init(this, options, instance$w, create_fragment$w, safe_not_equal, { bot: 0 }); } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Base class that bots can extend. */ class Bot { constructor({ enumerate, seed, }) { this.enumerateFn = enumerate; this.seed = seed; this.iterationCounter = 0; this._opts = {}; } addOpt({ key, range, initial, }) { this._opts[key] = { range, value: initial, }; } getOpt(key) { return this._opts[key].value; } setOpt(key, value) { if (key in this._opts) { this._opts[key].value = value; } } opts() { return this._opts; } enumerate(G, ctx, playerID) { const actions = this.enumerateFn(G, ctx, playerID); return actions.map((a) => { if ('payload' in a) { return a; } if ('move' in a) { return makeMove(a.move, a.args, playerID); } if ('event' in a) { return gameEvent(a.event, a.args, playerID); } }); } random(arg) { let number; if (this.seed !== undefined) { const seed = this.prngstate ? '' : this.seed; const rand = alea(seed, this.prngstate); number = rand(); this.prngstate = rand.state(); } else { number = Math.random(); } if (arg) { if (Array.isArray(arg)) { const id = Math.floor(number * arg.length); return arg[id]; } else { return Math.floor(number * arg); } } return number; } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * The number of iterations to run before yielding to * the JS event loop (in async mode). */ const CHUNK_SIZE = 25; /** * Bot that uses Monte-Carlo Tree Search to find promising moves. */ class MCTSBot extends Bot { constructor({ enumerate, seed, objectives, game, iterations, playoutDepth, iterationCallback, }) { super({ enumerate, seed }); if (objectives === undefined) { objectives = () => ({}); } this.objectives = objectives; this.iterationCallback = iterationCallback || (() => { }); this.reducer = CreateGameReducer({ game }); this.iterations = iterations; this.playoutDepth = playoutDepth; this.addOpt({ key: 'async', initial: false, }); this.addOpt({ key: 'iterations', initial: typeof iterations === 'number' ? iterations : 1000, range: { min: 1, max: 2000 }, }); this.addOpt({ key: 'playoutDepth', initial: typeof playoutDepth === 'number' ? playoutDepth : 50, range: { min: 1, max: 100 }, }); } createNode({ state, parentAction, parent, playerID, }) { const { G, ctx } = state; let actions = []; let objectives = []; if (playerID !== undefined) { actions = this.enumerate(G, ctx, playerID); objectives = this.objectives(G, ctx, playerID); } else if (ctx.activePlayers) { for (const playerID in ctx.activePlayers) { actions = actions.concat(this.enumerate(G, ctx, playerID)); objectives = objectives.concat(this.objectives(G, ctx, playerID)); } } else { actions = actions.concat(this.enumerate(G, ctx, ctx.currentPlayer)); objectives = objectives.concat(this.objectives(G, ctx, ctx.currentPlayer)); } return { state, parent, parentAction, actions, objectives, children: [], visits: 0, value: 0, }; } select(node) { // This node has unvisited children. if (node.actions.length > 0) { return node; } // This is a terminal node. if (node.children.length == 0) { return node; } let selectedChild = null; let best = 0; for (const child of node.children) { const childVisits = child.visits + Number.EPSILON; const uct = child.value / childVisits + Math.sqrt((2 * Math.log(node.visits)) / childVisits); if (selectedChild == null || uct > best) { best = uct; selectedChild = child; } } return this.select(selectedChild); } expand(node) { const actions = node.actions; if (actions.length == 0 || node.state.ctx.gameover !== undefined) { return node; } const id = this.random(actions.length); const action = actions[id]; node.actions.splice(id, 1); const childState = this.reducer(node.state, action); const childNode = this.createNode({ state: childState, parentAction: action, parent: node, }); node.children.push(childNode); return childNode; } playout({ state }) { let playoutDepth = this.getOpt('playoutDepth'); if (typeof this.playoutDepth === 'function') { playoutDepth = this.playoutDepth(state.G, state.ctx); } for (let i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) { const { G, ctx } = state; let playerID = ctx.currentPlayer; if (ctx.activePlayers) { playerID = Object.keys(ctx.activePlayers)[0]; } const moves = this.enumerate(G, ctx, playerID); // Check if any objectives are met. const objectives = this.objectives(G, ctx, playerID); const score = Object.keys(objectives).reduce((score, key) => { const objective = objectives[key]; if (objective.checker(G, ctx)) { return score + objective.weight; } return score; }, 0); // If so, stop and return the score. if (score > 0) { return { score }; } if (!moves || moves.length == 0) { return undefined; } const id = this.random(moves.length); const childState = this.reducer(state, moves[id]); state = childState; } return state.ctx.gameover; } backpropagate(node, result = {}) { node.visits++; if (result.score !== undefined) { node.value += result.score; } if (result.draw === true) { node.value += 0.5; } if (node.parentAction && result.winner === node.parentAction.payload.playerID) { node.value++; } if (node.parent) { this.backpropagate(node.parent, result); } } play(state, playerID) { const root = this.createNode({ state, playerID }); let numIterations = this.getOpt('iterations'); if (typeof this.iterations === 'function') { numIterations = this.iterations(state.G, state.ctx); } const getResult = () => { let selectedChild = null; for (const child of root.children) { if (selectedChild == null || child.visits > selectedChild.visits) { selectedChild = child; } } const action = selectedChild && selectedChild.parentAction; const metadata = root; return { action, metadata }; }; return new Promise((resolve) => { const iteration = () => { for (let i = 0; i < CHUNK_SIZE && this.iterationCounter < numIterations; i++) { const leaf = this.select(root); const child = this.expand(leaf); const result = this.playout(child); this.backpropagate(child, result); this.iterationCounter++; } this.iterationCallback({ iterationCounter: this.iterationCounter, numIterations, metadata: root, }); }; this.iterationCounter = 0; if (this.getOpt('async')) { const asyncIteration = () => { if (this.iterationCounter < numIterations) { iteration(); setTimeout(asyncIteration, 0); } else { resolve(getResult()); } }; asyncIteration(); } else { while (this.iterationCounter < numIterations) { iteration(); } resolve(getResult()); } }); } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Bot that picks a move at random. */ class RandomBot extends Bot { play({ G, ctx }, playerID) { const moves = this.enumerate(G, ctx, playerID); return Promise.resolve({ action: this.random(moves) }); } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Make a single move on the client with a bot. * * @param {...object} client - The game client. * @param {...object} bot - The bot. */ async function Step(client, bot) { const state = client.store.getState(); let playerID = state.ctx.currentPlayer; if (state.ctx.activePlayers) { playerID = Object.keys(state.ctx.activePlayers)[0]; } const { action, metadata } = await bot.play(state, playerID); if (action) { const a = { ...action, payload: { ...action.payload, metadata, }, }; client.store.dispatch(a); return a; } } /** * Simulates the game till the end or a max depth. * * @param {...object} game - The game object. * @param {...object} bots - An array of bots. * @param {...object} state - The game state to start from. */ async function Simulate({ game, bots, state, depth, }) { if (depth === undefined) depth = 10000; const reducer = CreateGameReducer({ game }); let metadata = null; let iter = 0; while (state.ctx.gameover === undefined && iter < depth) { let playerID = state.ctx.currentPlayer; if (state.ctx.activePlayers) { playerID = Object.keys(state.ctx.activePlayers)[0]; } const bot = bots instanceof Bot ? bots : bots[playerID]; const t = await bot.play(state, playerID); if (!t.action) { break; } metadata = t.metadata; state = reducer(state, t.action); iter++; } return { state, metadata }; } /* src/client/debug/ai/AI.svelte generated by Svelte v3.24.0 */ function add_css$p() { var style = element("style"); style.id = "svelte-lifdi8-style"; style.textContent = "ul.svelte-lifdi8{padding-left:0}li.svelte-lifdi8{list-style:none;margin:none;margin-bottom:5px}h3.svelte-lifdi8{text-transform:uppercase}label.svelte-lifdi8{color:#666}input[type='checkbox'].svelte-lifdi8{vertical-align:middle}"; append(document.head, style); } function get_each_context$a(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[7] = list[i]; return child_ctx; } // (201:4) {:else} function create_else_block$3(ctx) { let p0; let t1; let p1; return { c() { p0 = element("p"); p0.textContent = "No bots available."; t1 = space(); p1 = element("p"); p1.innerHTML = `Follow the instructions <a href="https://boardgame.io/documentation/#/tutorial?id=bots" target="_blank">here</a> to set up bots.`; }, m(target, anchor) { insert(target, p0, anchor); insert(target, t1, anchor); insert(target, p1, anchor); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) detach(p0); if (detaching) detach(t1); if (detaching) detach(p1); } }; } // (199:4) {#if client.multiplayer} function create_if_block_5(ctx) { let p; return { c() { p = element("p"); p.textContent = "The bot debugger is only available in singleplayer mode."; }, m(target, anchor) { insert(target, p, anchor); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) detach(p); } }; } // (149:2) {#if client.game.ai && !client.multiplayer} function create_if_block$d(ctx) { let section0; let h30; let t1; let ul; let li0; let hotkey0; let t2; let li1; let hotkey1; let t3; let li2; let hotkey2; let t4; let section1; let h31; let t6; let select; let t7; let show_if = Object.keys(/*bot*/ ctx[7].opts()).length; let t8; let if_block1_anchor; let current; let mounted; let dispose; hotkey0 = new Hotkey({ props: { value: "1", onPress: /*Reset*/ ctx[13], label: "reset" } }); hotkey1 = new Hotkey({ props: { value: "2", onPress: /*Step*/ ctx[11], label: "play" } }); hotkey2 = new Hotkey({ props: { value: "3", onPress: /*Simulate*/ ctx[12], label: "simulate" } }); let each_value = Object.keys(/*bots*/ ctx[8]); let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$a(get_each_context$a(ctx, each_value, i)); } let if_block0 = show_if && create_if_block_4(ctx); let if_block1 = (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) && create_if_block_1$6(ctx); return { c() { section0 = element("section"); h30 = element("h3"); h30.textContent = "Controls"; t1 = space(); ul = element("ul"); li0 = element("li"); create_component(hotkey0.$$.fragment); t2 = space(); li1 = element("li"); create_component(hotkey1.$$.fragment); t3 = space(); li2 = element("li"); create_component(hotkey2.$$.fragment); t4 = space(); section1 = element("section"); h31 = element("h3"); h31.textContent = "Bot"; t6 = space(); select = element("select"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } t7 = space(); if (if_block0) if_block0.c(); t8 = space(); if (if_block1) if_block1.c(); if_block1_anchor = empty(); attr(h30, "class", "svelte-lifdi8"); attr(li0, "class", "svelte-lifdi8"); attr(li1, "class", "svelte-lifdi8"); attr(li2, "class", "svelte-lifdi8"); attr(ul, "class", "svelte-lifdi8"); attr(h31, "class", "svelte-lifdi8"); if (/*selectedBot*/ ctx[4] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[16].call(select)); }, m(target, anchor) { insert(target, section0, anchor); append(section0, h30); append(section0, t1); append(section0, ul); append(ul, li0); mount_component(hotkey0, li0, null); append(ul, t2); append(ul, li1); mount_component(hotkey1, li1, null); append(ul, t3); append(ul, li2); mount_component(hotkey2, li2, null); insert(target, t4, anchor); insert(target, section1, anchor); append(section1, h31); append(section1, t6); append(section1, select); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(select, null); } select_option(select, /*selectedBot*/ ctx[4]); insert(target, t7, anchor); if (if_block0) if_block0.m(target, anchor); insert(target, t8, anchor); if (if_block1) if_block1.m(target, anchor); insert(target, if_block1_anchor, anchor); current = true; if (!mounted) { dispose = [ listen(select, "change", /*select_change_handler*/ ctx[16]), listen(select, "change", /*ChangeBot*/ ctx[10]) ]; mounted = true; } }, p(ctx, dirty) { if (dirty & /*Object, bots*/ 256) { each_value = Object.keys(/*bots*/ ctx[8]); let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$a(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); } else { each_blocks[i] = create_each_block$a(child_ctx); each_blocks[i].c(); each_blocks[i].m(select, null); } } for (; i < each_blocks.length; i += 1) { each_blocks[i].d(1); } each_blocks.length = each_value.length; } if (dirty & /*selectedBot, Object, bots*/ 272) { select_option(select, /*selectedBot*/ ctx[4]); } if (dirty & /*bot*/ 128) show_if = Object.keys(/*bot*/ ctx[7].opts()).length; if (show_if) { if (if_block0) { if_block0.p(ctx, dirty); if (dirty & /*bot*/ 128) { transition_in(if_block0, 1); } } else { if_block0 = create_if_block_4(ctx); if_block0.c(); transition_in(if_block0, 1); if_block0.m(t8.parentNode, t8); } } else if (if_block0) { group_outros(); transition_out(if_block0, 1, 1, () => { if_block0 = null; }); check_outros(); } if (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) { if (if_block1) { if_block1.p(ctx, dirty); } else { if_block1 = create_if_block_1$6(ctx); if_block1.c(); if_block1.m(if_block1_anchor.parentNode, if_block1_anchor); } } else if (if_block1) { if_block1.d(1); if_block1 = null; } }, i(local) { if (current) return; transition_in(hotkey0.$$.fragment, local); transition_in(hotkey1.$$.fragment, local); transition_in(hotkey2.$$.fragment, local); transition_in(if_block0); current = true; }, o(local) { transition_out(hotkey0.$$.fragment, local); transition_out(hotkey1.$$.fragment, local); transition_out(hotkey2.$$.fragment, local); transition_out(if_block0); current = false; }, d(detaching) { if (detaching) detach(section0); destroy_component(hotkey0); destroy_component(hotkey1); destroy_component(hotkey2); if (detaching) detach(t4); if (detaching) detach(section1); destroy_each(each_blocks, detaching); if (detaching) detach(t7); if (if_block0) if_block0.d(detaching); if (detaching) detach(t8); if (if_block1) if_block1.d(detaching); if (detaching) detach(if_block1_anchor); mounted = false; run_all(dispose); } }; } // (168:8) {#each Object.keys(bots) as bot} function create_each_block$a(ctx) { let option; let t_value = /*bot*/ ctx[7] + ""; let t; let option_value_value; return { c() { option = element("option"); t = text(t_value); option.__value = option_value_value = /*bot*/ ctx[7]; option.value = option.__value; }, m(target, anchor) { insert(target, option, anchor); append(option, t); }, p: noop, d(detaching) { if (detaching) detach(option); } }; } // (174:4) {#if Object.keys(bot.opts()).length} function create_if_block_4(ctx) { let section; let h3; let t1; let label; let t3; let input; let t4; let options; let current; let mounted; let dispose; options = new Options({ props: { bot: /*bot*/ ctx[7] } }); return { c() { section = element("section"); h3 = element("h3"); h3.textContent = "Options"; t1 = space(); label = element("label"); label.textContent = "debug"; t3 = space(); input = element("input"); t4 = space(); create_component(options.$$.fragment); attr(h3, "class", "svelte-lifdi8"); attr(label, "class", "svelte-lifdi8"); attr(input, "type", "checkbox"); attr(input, "class", "svelte-lifdi8"); }, m(target, anchor) { insert(target, section, anchor); append(section, h3); append(section, t1); append(section, label); append(section, t3); append(section, input); input.checked = /*debug*/ ctx[1]; append(section, t4); mount_component(options, section, null); current = true; if (!mounted) { dispose = [ listen(input, "change", /*input_change_handler*/ ctx[17]), listen(input, "change", /*OnDebug*/ ctx[9]) ]; mounted = true; } }, p(ctx, dirty) { if (dirty & /*debug*/ 2) { input.checked = /*debug*/ ctx[1]; } const options_changes = {}; if (dirty & /*bot*/ 128) options_changes.bot = /*bot*/ ctx[7]; options.$set(options_changes); }, i(local) { if (current) return; transition_in(options.$$.fragment, local); current = true; }, o(local) { transition_out(options.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(section); destroy_component(options); mounted = false; run_all(dispose); } }; } // (183:4) {#if botAction || iterationCounter} function create_if_block_1$6(ctx) { let section; let h3; let t1; let t2; let if_block0 = /*progress*/ ctx[2] && /*progress*/ ctx[2] < 1 && create_if_block_3$1(ctx); let if_block1 = /*botAction*/ ctx[5] && create_if_block_2$4(ctx); return { c() { section = element("section"); h3 = element("h3"); h3.textContent = "Result"; t1 = space(); if (if_block0) if_block0.c(); t2 = space(); if (if_block1) if_block1.c(); attr(h3, "class", "svelte-lifdi8"); }, m(target, anchor) { insert(target, section, anchor); append(section, h3); append(section, t1); if (if_block0) if_block0.m(section, null); append(section, t2); if (if_block1) if_block1.m(section, null); }, p(ctx, dirty) { if (/*progress*/ ctx[2] && /*progress*/ ctx[2] < 1) { if (if_block0) { if_block0.p(ctx, dirty); } else { if_block0 = create_if_block_3$1(ctx); if_block0.c(); if_block0.m(section, t2); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (/*botAction*/ ctx[5]) { if (if_block1) { if_block1.p(ctx, dirty); } else { if_block1 = create_if_block_2$4(ctx); if_block1.c(); if_block1.m(section, null); } } else if (if_block1) { if_block1.d(1); if_block1 = null; } }, d(detaching) { if (detaching) detach(section); if (if_block0) if_block0.d(); if (if_block1) if_block1.d(); } }; } // (186:6) {#if progress && progress < 1.0} function create_if_block_3$1(ctx) { let progress_1; return { c() { progress_1 = element("progress"); progress_1.value = /*progress*/ ctx[2]; }, m(target, anchor) { insert(target, progress_1, anchor); }, p(ctx, dirty) { if (dirty & /*progress*/ 4) { progress_1.value = /*progress*/ ctx[2]; } }, d(detaching) { if (detaching) detach(progress_1); } }; } // (190:6) {#if botAction} function create_if_block_2$4(ctx) { let ul; let li0; let t0; let t1; let t2; let li1; let t3; let t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + ""; let t4; return { c() { ul = element("ul"); li0 = element("li"); t0 = text("Action: "); t1 = text(/*botAction*/ ctx[5]); t2 = space(); li1 = element("li"); t3 = text("Args: "); t4 = text(t4_value); attr(li0, "class", "svelte-lifdi8"); attr(li1, "class", "svelte-lifdi8"); attr(ul, "class", "svelte-lifdi8"); }, m(target, anchor) { insert(target, ul, anchor); append(ul, li0); append(li0, t0); append(li0, t1); append(ul, t2); append(ul, li1); append(li1, t3); append(li1, t4); }, p(ctx, dirty) { if (dirty & /*botAction*/ 32) set_data(t1, /*botAction*/ ctx[5]); if (dirty & /*botActionArgs*/ 64 && t4_value !== (t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "")) set_data(t4, t4_value); }, d(detaching) { if (detaching) detach(ul); } }; } function create_fragment$x(ctx) { let section; let current_block_type_index; let if_block; let current; let mounted; let dispose; const if_block_creators = [create_if_block$d, create_if_block_5, create_else_block$3]; const if_blocks = []; function select_block_type(ctx, dirty) { if (/*client*/ ctx[0].game.ai && !/*client*/ ctx[0].multiplayer) return 0; if (/*client*/ ctx[0].multiplayer) return 1; return 2; } current_block_type_index = select_block_type(ctx); if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); return { c() { section = element("section"); if_block.c(); }, m(target, anchor) { insert(target, section, anchor); if_blocks[current_block_type_index].m(section, null); current = true; if (!mounted) { dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[14]); mounted = true; } }, p(ctx, [dirty]) { let previous_block_index = current_block_type_index; current_block_type_index = select_block_type(ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(ctx, dirty); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block = if_blocks[current_block_type_index]; if (!if_block) { if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block.c(); } transition_in(if_block, 1); if_block.m(section, null); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (detaching) detach(section); if_blocks[current_block_type_index].d(); mounted = false; dispose(); } }; } function instance$x($$self, $$props, $$invalidate) { let { client } = $$props; let { clientManager } = $$props; const { secondaryPane } = getContext("secondaryPane"); const bots = { "MCTS": MCTSBot, "Random": RandomBot }; let debug = false; let progress = null; let iterationCounter = 0; let metadata = null; const iterationCallback = ({ iterationCounter: c, numIterations, metadata: m }) => { $$invalidate(3, iterationCounter = c); $$invalidate(2, progress = c / numIterations); metadata = m; if (debug && metadata) { secondaryPane.set({ component: MCTS, metadata }); } }; function OnDebug() { if (debug && metadata) { secondaryPane.set({ component: MCTS, metadata }); } else { secondaryPane.set(null); } } let bot; if (client.game.ai) { bot = new MCTSBot({ game: client.game, enumerate: client.game.ai.enumerate, iterationCallback }); bot.setOpt("async", true); } let selectedBot; let botAction; let botActionArgs; function ChangeBot() { const botConstructor = bots[selectedBot]; $$invalidate(7, bot = new botConstructor({ game: client.game, enumerate: client.game.ai.enumerate, iterationCallback })); bot.setOpt("async", true); $$invalidate(5, botAction = null); metadata = null; secondaryPane.set(null); $$invalidate(3, iterationCounter = 0); } async function Step$1() { $$invalidate(5, botAction = null); metadata = null; $$invalidate(3, iterationCounter = 0); const t = await Step(client, bot); if (t) { $$invalidate(5, botAction = t.payload.type); $$invalidate(6, botActionArgs = t.payload.args); } } function Simulate(iterations = 10000, sleepTimeout = 100) { $$invalidate(5, botAction = null); metadata = null; $$invalidate(3, iterationCounter = 0); const step = async () => { for (let i = 0; i < iterations; i++) { const action = await Step(client, bot); if (!action) break; await new Promise(resolve => setTimeout(resolve, sleepTimeout)); } }; return step(); } function Exit() { client.overrideGameState(null); secondaryPane.set(null); $$invalidate(1, debug = false); } function Reset() { client.reset(); $$invalidate(5, botAction = null); metadata = null; $$invalidate(3, iterationCounter = 0); Exit(); } function OnKeyDown(e) { // ESC. if (e.keyCode == 27) { Exit(); } } onDestroy(Exit); function select_change_handler() { selectedBot = select_value(this); $$invalidate(4, selectedBot); $$invalidate(8, bots); } function input_change_handler() { debug = this.checked; $$invalidate(1, debug); } $$self.$set = $$props => { if ("client" in $$props) $$invalidate(0, client = $$props.client); if ("clientManager" in $$props) $$invalidate(15, clientManager = $$props.clientManager); }; return [ client, debug, progress, iterationCounter, selectedBot, botAction, botActionArgs, bot, bots, OnDebug, ChangeBot, Step$1, Simulate, Reset, OnKeyDown, clientManager, select_change_handler, input_change_handler ]; } class AI extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-lifdi8-style")) add_css$p(); init(this, options, instance$x, create_fragment$x, safe_not_equal, { client: 0, clientManager: 15 }); } } /* src/client/debug/Debug.svelte generated by Svelte v3.24.0 */ function add_css$q() { var style = element("style"); style.id = "svelte-1dhkl71-style"; style.textContent = ".debug-panel.svelte-1dhkl71{position:fixed;color:#555;font-family:monospace;display:flex;flex-direction:row;text-align:left;right:0;top:0;height:100%;font-size:14px;box-sizing:border-box;opacity:0.9;z-index:99999}.pane.svelte-1dhkl71{flex-grow:2;overflow-x:hidden;overflow-y:scroll;background:#fefefe;padding:20px;border-left:1px solid #ccc;box-shadow:-1px 0 5px rgba(0, 0, 0, 0.2);box-sizing:border-box;width:280px}.secondary-pane.svelte-1dhkl71{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-1dhkl71 button,.debug-panel.svelte-1dhkl71 select{cursor:pointer;font-size:14px;font-family:monospace}.debug-panel.svelte-1dhkl71 select{background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-1dhkl71 section{margin-bottom:20px}.debug-panel.svelte-1dhkl71 .screen-reader-only{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}"; append(document.head, style); } // (118:0) {#if visible} function create_if_block$e(ctx) { let section; let menu; let t0; let div; let switch_instance; let t1; let section_transition; let current; menu = new Menu({ props: { panes: /*panes*/ ctx[6], pane: /*pane*/ ctx[2] } }); menu.$on("change", /*MenuChange*/ ctx[8]); var switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component; function switch_props(ctx) { return { props: { client: /*client*/ ctx[4], clientManager: /*clientManager*/ ctx[0] } }; } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); } let if_block = /*$secondaryPane*/ ctx[5] && create_if_block_1$7(ctx); return { c() { section = element("section"); create_component(menu.$$.fragment); t0 = space(); div = element("div"); if (switch_instance) create_component(switch_instance.$$.fragment); t1 = space(); if (if_block) if_block.c(); attr(div, "class", "pane svelte-1dhkl71"); attr(div, "role", "region"); attr(div, "aria-label", /*pane*/ ctx[2]); attr(div, "tabindex", "-1"); attr(section, "aria-label", "boardgame.io Debug Panel"); attr(section, "class", "debug-panel svelte-1dhkl71"); }, m(target, anchor) { insert(target, section, anchor); mount_component(menu, section, null); append(section, t0); append(section, div); if (switch_instance) { mount_component(switch_instance, div, null); } /*div_binding*/ ctx[10](div); append(section, t1); if (if_block) if_block.m(section, null); current = true; }, p(ctx, dirty) { const menu_changes = {}; if (dirty & /*pane*/ 4) menu_changes.pane = /*pane*/ ctx[2]; menu.$set(menu_changes); const switch_instance_changes = {}; if (dirty & /*client*/ 16) switch_instance_changes.client = /*client*/ ctx[4]; if (dirty & /*clientManager*/ 1) switch_instance_changes.clientManager = /*clientManager*/ ctx[0]; if (switch_value !== (switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component)) { if (switch_instance) { group_outros(); const old_component = switch_instance; transition_out(old_component.$$.fragment, 1, 0, () => { destroy_component(old_component, 1); }); check_outros(); } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); create_component(switch_instance.$$.fragment); transition_in(switch_instance.$$.fragment, 1); mount_component(switch_instance, div, null); } else { switch_instance = null; } } else if (switch_value) { switch_instance.$set(switch_instance_changes); } if (!current || dirty & /*pane*/ 4) { attr(div, "aria-label", /*pane*/ ctx[2]); } if (/*$secondaryPane*/ ctx[5]) { if (if_block) { if_block.p(ctx, dirty); if (dirty & /*$secondaryPane*/ 32) { transition_in(if_block, 1); } } else { if_block = create_if_block_1$7(ctx); if_block.c(); transition_in(if_block, 1); if_block.m(section, null); } } else if (if_block) { group_outros(); transition_out(if_block, 1, 1, () => { if_block = null; }); check_outros(); } }, i(local) { if (current) return; transition_in(menu.$$.fragment, local); if (switch_instance) transition_in(switch_instance.$$.fragment, local); transition_in(if_block); add_render_callback(() => { if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, true); section_transition.run(1); }); current = true; }, o(local) { transition_out(menu.$$.fragment, local); if (switch_instance) transition_out(switch_instance.$$.fragment, local); transition_out(if_block); if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, false); section_transition.run(0); current = false; }, d(detaching) { if (detaching) detach(section); destroy_component(menu); if (switch_instance) destroy_component(switch_instance); /*div_binding*/ ctx[10](null); if (if_block) if_block.d(); if (detaching && section_transition) section_transition.end(); } }; } // (130:4) {#if $secondaryPane} function create_if_block_1$7(ctx) { let div; let switch_instance; let current; var switch_value = /*$secondaryPane*/ ctx[5].component; function switch_props(ctx) { return { props: { metadata: /*$secondaryPane*/ ctx[5].metadata } }; } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); } return { c() { div = element("div"); if (switch_instance) create_component(switch_instance.$$.fragment); attr(div, "class", "secondary-pane svelte-1dhkl71"); }, m(target, anchor) { insert(target, div, anchor); if (switch_instance) { mount_component(switch_instance, div, null); } current = true; }, p(ctx, dirty) { const switch_instance_changes = {}; if (dirty & /*$secondaryPane*/ 32) switch_instance_changes.metadata = /*$secondaryPane*/ ctx[5].metadata; if (switch_value !== (switch_value = /*$secondaryPane*/ ctx[5].component)) { if (switch_instance) { group_outros(); const old_component = switch_instance; transition_out(old_component.$$.fragment, 1, 0, () => { destroy_component(old_component, 1); }); check_outros(); } if (switch_value) { switch_instance = new switch_value(switch_props(ctx)); create_component(switch_instance.$$.fragment); transition_in(switch_instance.$$.fragment, 1); mount_component(switch_instance, div, null); } else { switch_instance = null; } } else if (switch_value) { switch_instance.$set(switch_instance_changes); } }, i(local) { if (current) return; if (switch_instance) transition_in(switch_instance.$$.fragment, local); current = true; }, o(local) { if (switch_instance) transition_out(switch_instance.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(div); if (switch_instance) destroy_component(switch_instance); } }; } function create_fragment$y(ctx) { let if_block_anchor; let current; let mounted; let dispose; let if_block = /*visible*/ ctx[3] && create_if_block$e(ctx); return { c() { if (if_block) if_block.c(); if_block_anchor = empty(); }, m(target, anchor) { if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); current = true; if (!mounted) { dispose = listen(window, "keypress", /*Keypress*/ ctx[9]); mounted = true; } }, p(ctx, [dirty]) { if (/*visible*/ ctx[3]) { if (if_block) { if_block.p(ctx, dirty); if (dirty & /*visible*/ 8) { transition_in(if_block, 1); } } else { if_block = create_if_block$e(ctx); if_block.c(); transition_in(if_block, 1); if_block.m(if_block_anchor.parentNode, if_block_anchor); } } else if (if_block) { group_outros(); transition_out(if_block, 1, 1, () => { if_block = null; }); check_outros(); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (if_block) if_block.d(detaching); if (detaching) detach(if_block_anchor); mounted = false; dispose(); } }; } function instance$y($$self, $$props, $$invalidate) { let $clientManager, $$unsubscribe_clientManager = noop, $$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(11, $clientManager = $$value)), clientManager); let $secondaryPane; $$self.$$.on_destroy.push(() => $$unsubscribe_clientManager()); let { clientManager } = $$props; $$subscribe_clientManager(); const panes = { main: { label: "Main", shortcut: "m", component: Main }, log: { label: "Log", shortcut: "l", component: Log }, info: { label: "Info", shortcut: "i", component: Info }, ai: { label: "AI", shortcut: "a", component: AI } }; const disableHotkeys = writable(false); const secondaryPane = writable(null); component_subscribe($$self, secondaryPane, value => $$invalidate(5, $secondaryPane = value)); setContext("hotkeys", { disableHotkeys }); setContext("secondaryPane", { secondaryPane }); let paneDiv; let pane = "main"; function MenuChange(e) { $$invalidate(2, pane = e.detail); paneDiv.focus(); } let visible = true; function Keypress(e) { // Toggle debugger visibilty if (e.key == ".") { $$invalidate(3, visible = !visible); return; } // Set displayed pane if (!visible) return; Object.entries(panes).forEach(([key, { shortcut }]) => { if (e.key == shortcut) { $$invalidate(2, pane = key); } }); } function div_binding($$value) { binding_callbacks[$$value ? "unshift" : "push"](() => { paneDiv = $$value; $$invalidate(1, paneDiv); }); } $$self.$set = $$props => { if ("clientManager" in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager)); }; let client; $$self.$$.update = () => { if ($$self.$$.dirty & /*$clientManager*/ 2048) { $: $$invalidate(4, client = $clientManager.client); } }; return [ clientManager, paneDiv, pane, visible, client, $secondaryPane, panes, secondaryPane, MenuChange, Keypress, div_binding ]; } class Debug extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1dhkl71-style")) add_css$q(); init(this, options, instance$y, create_fragment$y, safe_not_equal, { clientManager: 0 }); } } /** * Class to manage boardgame.io clients and limit debug panel rendering. */ class ClientManager { constructor() { this.debugPanel = null; this.currentClient = null; this.clients = new Map(); this.subscribers = new Map(); } /** * Register a client with the client manager. */ register(client) { // Add client to clients map. this.clients.set(client, client); // Mount debug for this client (no-op if another debug is already mounted). this.mountDebug(client); this.notifySubscribers(); } /** * Unregister a client from the client manager. */ unregister(client) { // Remove client from clients map. this.clients.delete(client); if (this.currentClient === client) { // If the removed client owned the debug panel, unmount it. this.unmountDebug(); // Mount debug panel for next available client. for (const [client] of this.clients) { if (this.debugPanel) break; this.mountDebug(client); } } this.notifySubscribers(); } /** * Subscribe to the client manager state. * Calls the passed callback each time the current client changes or a client * registers/unregisters. * Returns a function to unsubscribe from the state updates. */ subscribe(callback) { const id = Symbol(); this.subscribers.set(id, callback); callback(this.getState()); return () => { this.subscribers.delete(id); }; } /** * Switch to a client with a matching playerID. */ switchPlayerID(playerID) { // For multiplayer clients, try switching control to a different client // that is using the same transport layer. if (this.currentClient.multiplayer) { for (const [client] of this.clients) { if (client.playerID === playerID && client.debugOpt !== false && client.multiplayer === this.currentClient.multiplayer) { this.switchToClient(client); return; } } } // If no client matches, update the playerID for the current client. this.currentClient.updatePlayerID(playerID); this.notifySubscribers(); } /** * Set the passed client as the active client for debugging. */ switchToClient(client) { if (client === this.currentClient) return; this.unmountDebug(); this.mountDebug(client); this.notifySubscribers(); } /** * Notify all subscribers of changes to the client manager state. */ notifySubscribers() { const arg = this.getState(); this.subscribers.forEach((cb) => { cb(arg); }); } /** * Get the client manager state. */ getState() { return { client: this.currentClient, debuggableClients: this.getDebuggableClients(), }; } /** * Get an array of the registered clients that haven’t disabled the debug panel. */ getDebuggableClients() { return [...this.clients.values()].filter((client) => client.debugOpt !== false); } /** * Mount the debug panel using the passed client. */ mountDebug(client) { if (client.debugOpt === false || this.debugPanel !== null || typeof document === 'undefined') { return; } let DebugImpl; let target = document.body; if (process.env.NODE_ENV !== 'production') { DebugImpl = Debug; } if (client.debugOpt && client.debugOpt !== true) { DebugImpl = client.debugOpt.impl || DebugImpl; target = client.debugOpt.target || target; } if (DebugImpl) { this.currentClient = client; this.debugPanel = new DebugImpl({ target, props: { clientManager: this }, }); } } /** * Unmount the debug panel. */ unmountDebug() { this.debugPanel.$destroy(); this.debugPanel = null; this.currentClient = null; } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Global client manager instance that all clients register with. */ const GlobalClientManager = new ClientManager(); /** * Standardise the passed playerID, using currentPlayer if appropriate. */ function assumedPlayerID(playerID, store, multiplayer) { // In singleplayer mode, if the client does not have a playerID // associated with it, we attach the currentPlayer as playerID. if (!multiplayer && (playerID === null || playerID === undefined)) { const state = store.getState(); playerID = state.ctx.currentPlayer; } return playerID; } /** * createDispatchers * * Create action dispatcher wrappers with bound playerID and credentials */ function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) { return innerActionNames.reduce((dispatchers, name) => { dispatchers[name] = function (...args) { store.dispatch(ActionCreators[storeActionType](name, args, assumedPlayerID(playerID, store, multiplayer), credentials)); }; return dispatchers; }, {}); } // Creates a set of dispatchers to make moves. const createMoveDispatchers = createDispatchers.bind(null, 'makeMove'); // Creates a set of dispatchers to dispatch game flow events. const createEventDispatchers = createDispatchers.bind(null, 'gameEvent'); // Creates a set of dispatchers to dispatch actions to plugins. const createPluginDispatchers = createDispatchers.bind(null, 'plugin'); /** * Implementation of Client (see below). */ class _ClientImpl { constructor({ game, debug, numPlayers, multiplayer, matchID: matchID, playerID, credentials, enhancer, }) { this.game = ProcessGameConfig(game); this.playerID = playerID; this.matchID = matchID; this.credentials = credentials; this.multiplayer = multiplayer; this.debugOpt = debug; this.manager = GlobalClientManager; this.gameStateOverride = null; this.subscribers = {}; this._running = false; this.reducer = CreateGameReducer({ game: this.game, isClient: multiplayer !== undefined, }); this.initialState = null; if (!multiplayer) { this.initialState = InitializeGame({ game: this.game, numPlayers }); } this.reset = () => { this.store.dispatch(reset(this.initialState)); }; this.undo = () => { const undo$1 = undo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials); this.store.dispatch(undo$1); }; this.redo = () => { const redo$1 = redo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials); this.store.dispatch(redo$1); }; this.log = []; /** * Middleware that manages the log object. * Reducers generate deltalogs, which are log events * that are the result of application of a single action. * The master may also send back a deltalog or the entire * log depending on the type of request. * The middleware below takes care of all these cases while * managing the log object. */ const LogMiddleware = (store) => (next) => (action) => { const result = next(action); const state = store.getState(); switch (action.type) { case MAKE_MOVE: case GAME_EVENT: case UNDO: case REDO: { const deltalog = state.deltalog; this.log = [...this.log, ...deltalog]; break; } case RESET: { this.log = []; break; } case UPDATE: { let id = -1; if (this.log.length > 0) { id = this.log[this.log.length - 1]._stateID; } let deltalog = action.deltalog || []; // Filter out actions that are already present // in the current log. This may occur when the // client adds an entry to the log followed by // the update from the master here. deltalog = deltalog.filter((l) => l._stateID > id); this.log = [...this.log, ...deltalog]; break; } case SYNC: { this.initialState = action.initialState; this.log = action.log || []; break; } } return result; }; /** * Middleware that intercepts actions and sends them to the master, * which keeps the authoritative version of the state. */ const TransportMiddleware = (store) => (next) => (action) => { const baseState = store.getState(); const result = next(action); if (!('clientOnly' in action)) { this.transport.onAction(baseState, action); } return result; }; /** * Middleware that intercepts actions and invokes the subscription callback. */ const SubscriptionMiddleware = () => (next) => (action) => { const result = next(action); this.notifySubscribers(); return result; }; const middleware = applyMiddleware(SubscriptionMiddleware, TransportMiddleware, LogMiddleware); enhancer = enhancer !== undefined ? compose(middleware, enhancer) : middleware; this.store = createStore(this.reducer, this.initialState, enhancer); if (!multiplayer) multiplayer = DummyTransport; this.transport = multiplayer({ gameKey: game, game: this.game, store: this.store, matchID, playerID, credentials, gameName: this.game.name, numPlayers, }); this.createDispatchers(); this.transport.subscribeMatchData((metadata) => { this.matchData = metadata; this.notifySubscribers(); }); this.chatMessages = []; this.sendChatMessage = (payload) => { this.transport.onChatMessage(this.matchID, { id: nanoid(7), sender: this.playerID, payload: payload, }); }; this.transport.subscribeChatMessage((message) => { this.chatMessages = [...this.chatMessages, message]; this.notifySubscribers(); }); } notifySubscribers() { Object.values(this.subscribers).forEach((fn) => fn(this.getState())); } overrideGameState(state) { this.gameStateOverride = state; this.notifySubscribers(); } start() { this.transport.connect(); this._running = true; this.manager.register(this); } stop() { this.transport.disconnect(); this._running = false; this.manager.unregister(this); } subscribe(fn) { const id = Object.keys(this.subscribers).length; this.subscribers[id] = fn; this.transport.subscribe(() => this.notifySubscribers()); if (this._running || !this.multiplayer) { fn(this.getState()); } // Return a handle that allows the caller to unsubscribe. return () => { delete this.subscribers[id]; }; } getInitialState() { return this.initialState; } getState() { let state = this.store.getState(); if (this.gameStateOverride !== null) { state = this.gameStateOverride; } // This is the state before a sync with the game master. if (state === null) { return state; } // isActive. let isActive = true; const isPlayerActive = this.game.flow.isPlayerActive(state.G, state.ctx, this.playerID); if (this.multiplayer && !isPlayerActive) { isActive = false; } if (!this.multiplayer && this.playerID !== null && this.playerID !== undefined && !isPlayerActive) { isActive = false; } if (state.ctx.gameover !== undefined) { isActive = false; } // Secrets are normally stripped on the server, // but we also strip them here so that game developers // can see their effects while prototyping. // Do not strip again if this is a multiplayer game // since the server has already stripped secret info. (issue #818) if (!this.multiplayer) { state = { ...state, G: this.game.playerView(state.G, state.ctx, this.playerID), plugins: PlayerView(state, this), }; } // Combine into return value. return { ...state, log: this.log, isActive, isConnected: this.transport.isConnected, }; } createDispatchers() { this.moves = createMoveDispatchers(this.game.moveNames, this.store, this.playerID, this.credentials, this.multiplayer); this.events = createEventDispatchers(this.game.flow.enabledEventNames, this.store, this.playerID, this.credentials, this.multiplayer); this.plugins = createPluginDispatchers(this.game.pluginNames, this.store, this.playerID, this.credentials, this.multiplayer); } updatePlayerID(playerID) { this.playerID = playerID; this.createDispatchers(); this.transport.updatePlayerID(playerID); this.notifySubscribers(); } updateMatchID(matchID) { this.matchID = matchID; this.createDispatchers(); this.transport.updateMatchID(matchID); this.notifySubscribers(); } updateCredentials(credentials) { this.credentials = credentials; this.createDispatchers(); this.transport.updateCredentials(credentials); this.notifySubscribers(); } } /** * Client * * boardgame.io JS client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} matchID - The matchID that you want to connect to. * @param {...object} playerID - The playerID associated with this client. * @param {...string} credentials - The authentication credentials associated with this client. * * Returns: * A JS object that provides an API to interact with the * game by dispatching moves and events. */ function Client(opts) { return new _ClientImpl(opts); } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Client * * boardgame.io React client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} debug - Enables the Debug UI. * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET, * UNDO and REDO. */ function Client$1(opts) { var _a; let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting..."); loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _a = class WrappedBoard extends React.Component { constructor(props) { super(props); if (debug === undefined) { debug = props.debug; } this.client = Client({ game, debug, numPlayers, multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, enhancer, }); } componentDidMount() { this.unsubscribe = this.client.subscribe(() => this.forceUpdate()); this.client.start(); } componentWillUnmount() { this.client.stop(); this.unsubscribe(); } componentDidUpdate(prevProps) { if (this.props.matchID != prevProps.matchID) { this.client.updateMatchID(this.props.matchID); } if (this.props.playerID != prevProps.playerID) { this.client.updatePlayerID(this.props.playerID); } if (this.props.credentials != prevProps.credentials) { this.client.updateCredentials(this.props.credentials); } } render() { const state = this.client.getState(); if (state === null) { return React.createElement(loading); } let _board = null; if (board) { _board = React.createElement(board, { ...state, ...this.props, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, matchID: this.client.matchID, playerID: this.client.playerID, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, log: this.client.log, matchData: this.client.matchData, sendChatMessage: this.client.sendChatMessage, chatMessages: this.client.chatMessages, }); } return React.createElement("div", { className: "bgio-client" }, _board); } }, _a.propTypes = { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string, // Enable / disable the Debug UI. debug: PropTypes.any, }, _a.defaultProps = { matchID: 'default', playerID: null, credentials: null, debug: true, }, _a; } /** * Client * * boardgame.io React Native client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React Native component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE. */ function Client$2(opts) { var _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer; /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _temp = _class = /*#__PURE__*/function (_React$Component) { _inherits(WrappedBoard, _React$Component); var _super = _createSuper(WrappedBoard); function WrappedBoard(props) { var _this; _classCallCheck(this, WrappedBoard); _this = _super.call(this, props); _this.client = Client({ game: game, numPlayers: numPlayers, multiplayer: multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, debug: false, enhancer: enhancer }); return _this; } _createClass(WrappedBoard, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.client.subscribe(function () { return _this2.forceUpdate(); }); this.client.start(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.client.stop(); this.unsubscribe(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.matchID != this.props.matchID) { this.client.updateMatchID(this.props.matchID); } if (prevProps.playerID != this.props.playerID) { this.client.updatePlayerID(this.props.playerID); } if (prevProps.credentials != this.props.credentials) { this.client.updateCredentials(this.props.credentials); } } }, { key: "render", value: function render() { var _board = null; var state = this.client.getState(); var _this$props = this.props, matchID = _this$props.matchID, playerID = _this$props.playerID, rest = _objectWithoutProperties(_this$props, ["matchID", "playerID"]); if (board) { _board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, { matchID: matchID, playerID: playerID, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, step: this.client.step, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, matchData: this.client.matchData, sendChatMessage: this.client.sendChatMessage, chatMessages: this.client.chatMessages })); } return _board; } }]); return WrappedBoard; }(React.Component), _defineProperty(_class, "propTypes", { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string }), _defineProperty(_class, "defaultProps", { matchID: 'default', playerID: null, credentials: null }), _temp; } var Type; (function (Type) { Type[Type["SYNC"] = 0] = "SYNC"; Type[Type["ASYNC"] = 1] = "ASYNC"; })(Type || (Type = {})); /** * Type guard that checks if a storage implementation is synchronous. */ function isSynchronous(storageAPI) { return storageAPI.type() === Type.SYNC; } class Sync { type() { return Type.SYNC; } /** * Connect. */ connect() { return; } /** * Create a new match. * * This might just need to call setState and setMetadata in * most implementations. * * However, it exists as a separate call so that the * implementation can provision things differently when * a match is created. For example, it might stow away the * initial match state in a separate field for easier retrieval. */ /* istanbul ignore next */ createMatch(matchID, opts) { if (this.createGame) { console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.'); return this.createGame(matchID, opts); } else { console.error('The database connector does not implement a createMatch method.'); } } /** * Return all matches. */ /* istanbul ignore next */ listMatches(opts) { if (this.listGames) { console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.'); return this.listGames(opts); } else { console.error('The database connector does not implement a listMatches method.'); } } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * InMemory data storage. */ class InMemory extends Sync { /** * Creates a new InMemory storage. */ constructor() { super(); this.state = new Map(); this.initial = new Map(); this.metadata = new Map(); this.log = new Map(); } /** * Create a new match. * * @override */ createMatch(matchID, opts) { this.initial.set(matchID, opts.initialState); this.setState(matchID, opts.initialState); this.setMetadata(matchID, opts.metadata); } /** * Write the match metadata to the in-memory object. */ setMetadata(matchID, metadata) { this.metadata.set(matchID, metadata); } /** * Write the match state to the in-memory object. */ setState(matchID, state, deltalog) { if (deltalog && deltalog.length > 0) { const log = this.log.get(matchID) || []; this.log.set(matchID, log.concat(deltalog)); } this.state.set(matchID, state); } /** * Fetches state for a particular matchID. */ fetch(matchID, opts) { const result = {}; if (opts.state) { result.state = this.state.get(matchID); } if (opts.metadata) { result.metadata = this.metadata.get(matchID); } if (opts.log) { result.log = this.log.get(matchID) || []; } if (opts.initialState) { result.initialState = this.initial.get(matchID); } return result; } /** * Remove the match state from the in-memory object. */ wipe(matchID) { this.state.delete(matchID); this.metadata.delete(matchID); } /** * Return all keys. * * @override */ listMatches(opts) { return [...this.metadata.entries()] .filter(([, metadata]) => { if (!opts) { return true; } if (opts.gameName !== undefined && metadata.gameName !== opts.gameName) { return false; } if (opts.where !== undefined) { if (opts.where.isGameover !== undefined) { const isGameover = metadata.gameover !== undefined; if (isGameover !== opts.where.isGameover) { return false; } } if (opts.where.updatedBefore !== undefined && metadata.updatedAt >= opts.where.updatedBefore) { return false; } if (opts.where.updatedAfter !== undefined && metadata.updatedAt <= opts.where.updatedAfter) { return false; } } return true; }) .map(([key]) => key); } } class WithLocalStorageMap extends Map { constructor(key) { super(); this.key = key; const cache = JSON.parse(localStorage.getItem(this.key)) || []; cache.forEach((entry) => this.set(...entry)); } sync() { const entries = [...this.entries()]; localStorage.setItem(this.key, JSON.stringify(entries)); } set(key, value) { super.set(key, value); this.sync(); return this; } delete(key) { const result = super.delete(key); this.sync(); return result; } } /** * locaStorage data storage. */ class LocalStorage extends InMemory { constructor(storagePrefix = 'bgio') { super(); const StorageMap = (stateKey) => new WithLocalStorageMap(`${storagePrefix}_${stateKey}`); this.state = StorageMap('state'); this.initial = StorageMap('initial'); this.metadata = StorageMap('metadata'); this.log = StorageMap('log'); } } /** * Creates a new match metadata object. */ const createMetadata = ({ game, unlisted, setupData, numPlayers, }) => { const metadata = { gameName: game.name, unlisted: !!unlisted, players: {}, createdAt: Date.now(), updatedAt: Date.now(), }; if (setupData !== undefined) metadata.setupData = setupData; for (let playerIndex = 0; playerIndex < numPlayers; playerIndex++) { metadata.players[playerIndex] = { id: playerIndex }; } return metadata; }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Filter match data to get a player metadata object with credentials stripped. */ const filterMatchData = (matchData) => Object.values(matchData.players).map((player) => { const { credentials, ...filteredData } = player; return filteredData; }); /** * Redact the log. * * @param {Array} log - The game log (or deltalog). * @param {String} playerID - The playerID that this log is * to be sent to. */ function redactLog(log, playerID) { if (log === undefined) { return log; } return log.map((logEvent) => { // filter for all other players and spectators. if (playerID !== null && +playerID === +logEvent.action.payload.playerID) { return logEvent; } if (logEvent.redact !== true) { return logEvent; } const payload = { ...logEvent.action.payload, args: null, }; const filteredEvent = { ...logEvent, action: { ...logEvent.action, payload }, }; const { redact, ...remaining } = filteredEvent; return remaining; }); } /** * Remove player credentials from action payload */ const stripCredentialsFromAction = (action) => { const { credentials, ...payload } = action.payload; return { ...action, payload }; }; /** * Master * * Class that runs the game and maintains the authoritative state. * It uses the transportAPI to communicate with clients and the * storageAPI to communicate with the database. */ class Master { constructor(game, storageAPI, transportAPI, auth) { this.game = ProcessGameConfig(game); this.storageAPI = storageAPI; this.transportAPI = transportAPI; this.subscribeCallback = () => { }; this.auth = auth; } subscribe(fn) { this.subscribeCallback = fn; } /** * Called on each move / event made by the client. * Computes the new value of the game state and returns it * along with a deltalog. */ async onUpdate(credAction, stateID, matchID, playerID) { let metadata; if (isSynchronous(this.storageAPI)) { ({ metadata } = this.storageAPI.fetch(matchID, { metadata: true })); } else { ({ metadata } = await this.storageAPI.fetch(matchID, { metadata: true })); } if (this.auth) { const isAuthentic = await this.auth.authenticateCredentials({ playerID, credentials: credAction.payload.credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized action' }; } } const action = stripCredentialsFromAction(credAction); const key = matchID; let state; if (isSynchronous(this.storageAPI)) { ({ state } = this.storageAPI.fetch(key, { state: true })); } else { ({ state } = await this.storageAPI.fetch(key, { state: true })); } if (state === undefined) { error(`game not found, matchID=[${key}]`); return { error: 'game not found' }; } if (state.ctx.gameover !== undefined) { error(`game over - matchID=[${key}] - playerID=[${playerID}]` + ` - action[${action.payload.type}]`); return; } const reducer = CreateGameReducer({ game: this.game, }); const store = createStore(reducer, state); // Only allow UNDO / REDO if there is exactly one player // that can make moves right now and the person doing the // action is that player. if (action.type == UNDO || action.type == REDO) { const hasActivePlayers = state.ctx.activePlayers !== null; const isCurrentPlayer = state.ctx.currentPlayer === playerID; if ( // If activePlayers is empty, non-current players can’t undo. (!hasActivePlayers && !isCurrentPlayer) || // If player is not active or multiple players are active, can’t undo. (hasActivePlayers && (state.ctx.activePlayers[playerID] === undefined || Object.keys(state.ctx.activePlayers).length > 1))) { error(`playerID=[${playerID}] cannot undo / redo right now`); return; } } // Check whether the player is active. if (!this.game.flow.isPlayerActive(state.G, state.ctx, playerID)) { error(`player not active - playerID=[${playerID}]` + ` - action[${action.payload.type}]`); return; } // Get move for further checkings const move = action.type == MAKE_MOVE ? this.game.flow.getMove(state.ctx, action.payload.type, playerID) : null; // Check whether the player is allowed to make the move. if (action.type == MAKE_MOVE && !move) { error(`move not processed - canPlayerMakeMove=false - playerID=[${playerID}]` + ` - action[${action.payload.type}]`); return; } // Check if action's stateID is different than store's stateID // and if move does not have ignoreStaleStateID truthy. if (state._stateID !== stateID && !(move && IsLongFormMove(move) && move.ignoreStaleStateID)) { error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]` + ` - playerID=[${playerID}] - action[${action.payload.type}]`); return; } // Update server's version of the store. store.dispatch(action); state = store.getState(); this.subscribeCallback({ state, action, matchID, }); this.transportAPI.sendAll((playerID) => { const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), plugins: PlayerView(state, { playerID, game: this.game }), deltalog: undefined, _undo: [], _redo: [], }; const log = redactLog(state.deltalog, playerID); return { type: 'update', args: [matchID, filteredState, log], }; }); const { deltalog, ...stateWithoutDeltalog } = state; let newMetadata; if (metadata && !('gameover' in metadata)) { newMetadata = { ...metadata, updatedAt: Date.now(), }; if (state.ctx.gameover !== undefined) { newMetadata.gameover = state.ctx.gameover; } } if (isSynchronous(this.storageAPI)) { this.storageAPI.setState(key, stateWithoutDeltalog, deltalog); if (newMetadata) this.storageAPI.setMetadata(key, newMetadata); } else { const writes = [ this.storageAPI.setState(key, stateWithoutDeltalog, deltalog), ]; if (newMetadata) { writes.push(this.storageAPI.setMetadata(key, newMetadata)); } await Promise.all(writes); } } /** * Called when the client connects / reconnects. * Returns the latest game state and the entire log. */ async onSync(matchID, playerID, credentials, numPlayers = 2) { const key = matchID; const fetchOpts = { state: true, metadata: true, log: true, initialState: true, }; const fetchResult = isSynchronous(this.storageAPI) ? this.storageAPI.fetch(key, fetchOpts) : await this.storageAPI.fetch(key, fetchOpts); let { state, initialState, log, metadata } = fetchResult; if (this.auth && playerID !== undefined && playerID !== null) { const isAuthentic = await this.auth.authenticateCredentials({ playerID, credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized' }; } } // If the game doesn't exist, then create one on demand. // TODO: Move this out of the sync call. if (state === undefined) { initialState = state = InitializeGame({ game: this.game, numPlayers }); metadata = createMetadata({ game: this.game, unlisted: true, numPlayers, }); this.subscribeCallback({ state, matchID }); if (isSynchronous(this.storageAPI)) { this.storageAPI.createMatch(key, { initialState, metadata }); } else { await this.storageAPI.createMatch(key, { initialState, metadata }); } } const filteredMetadata = metadata ? filterMatchData(metadata) : undefined; const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), plugins: PlayerView(state, { playerID, game: this.game }), deltalog: undefined, _undo: [], _redo: [], }; log = redactLog(log, playerID); const syncInfo = { state: filteredState, log, filteredMetadata, initialState, }; this.transportAPI.send({ playerID, type: 'sync', args: [matchID, syncInfo], }); return; } /** * Called when a client connects or disconnects. * Updates and sends out metadata to reflect the player’s connection status. */ async onConnectionChange(matchID, playerID, credentials, connected) { const key = matchID; // Ignore changes for clients without a playerID, e.g. spectators. if (playerID === undefined || playerID === null) { return; } let metadata; if (isSynchronous(this.storageAPI)) { ({ metadata } = this.storageAPI.fetch(key, { metadata: true })); } else { ({ metadata } = await this.storageAPI.fetch(key, { metadata: true })); } if (metadata === undefined) { error(`metadata not found for matchID=[${key}]`); return { error: 'metadata not found' }; } if (metadata.players[playerID] === undefined) { error(`Player not in the match, matchID=[${key}] playerID=[${playerID}]`); return { error: 'player not in the match' }; } if (this.auth) { const isAuthentic = await this.auth.authenticateCredentials({ playerID, credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized' }; } } metadata.players[playerID].isConnected = connected; const filteredMetadata = filterMatchData(metadata); this.transportAPI.sendAll(() => ({ type: 'matchData', args: [matchID, filteredMetadata], })); if (isSynchronous(this.storageAPI)) { this.storageAPI.setMetadata(key, metadata); } else { await this.storageAPI.setMetadata(key, metadata); } } async onChatMessage(matchID, chatMessage, credentials) { const key = matchID; if (this.auth) { const { metadata } = await this.storageAPI.fetch(key, { metadata: true, }); const isAuthentic = await this.auth.authenticateCredentials({ playerID: chatMessage.sender, credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized' }; } } this.transportAPI.sendAll(() => ({ type: 'chat', args: [matchID, chatMessage], })); } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Returns null if it is not a bot's turn. * Otherwise, returns a playerID of a bot that may play now. */ function GetBotPlayer(state, bots) { if (state.ctx.gameover !== undefined) { return null; } if (state.ctx.activePlayers) { for (const key of Object.keys(bots)) { if (key in state.ctx.activePlayers) { return key; } } } else if (state.ctx.currentPlayer in bots) { return state.ctx.currentPlayer; } return null; } /** * Creates a local version of the master that the client * can interact with. */ class LocalMaster extends Master { constructor({ game, bots, storageKey, persist }) { const clientCallbacks = {}; const initializedBots = {}; if (game && game.ai && bots) { for (const playerID in bots) { const bot = bots[playerID]; initializedBots[playerID] = new bot({ game, enumerate: game.ai.enumerate, seed: game.seed, }); } } const send = ({ playerID, ...data }) => { const callback = clientCallbacks[playerID]; if (callback !== undefined) { callback(data); } }; const transportAPI = { send, sendAll: (makePlayerData) => { for (const playerID in clientCallbacks) { const data = makePlayerData(playerID); send({ playerID, ...data }); } }, }; const storage = persist ? new LocalStorage(storageKey) : new InMemory(); super(game, storage, transportAPI); this.connect = (matchID, playerID, callback) => { clientCallbacks[playerID] = callback; }; this.subscribe(({ state, matchID }) => { if (!bots) { return; } const botPlayer = GetBotPlayer(state, initializedBots); if (botPlayer !== null) { setTimeout(async () => { const botAction = await initializedBots[botPlayer].play(state, botPlayer); await this.onUpdate(botAction.action, state._stateID, matchID, botAction.action.payload.playerID); }, 100); } }); } } /** * Local * * Transport interface that embeds a GameMaster within it * that you can connect multiple clients to. */ class LocalTransport extends Transport { /** * Creates a new Mutiplayer instance. * @param {string} matchID - The game ID to connect to. * @param {string} playerID - The player ID associated with this client. * @param {string} gameName - The game type (the `name` field in `Game`). * @param {string} numPlayers - The number of players. */ constructor({ master, store, matchID, playerID, credentials, gameName, numPlayers, }) { super({ store, gameName, playerID, matchID, credentials, numPlayers }); this.master = master; this.isConnected = true; } /** * Called when any player sends a chat message and the * master broadcasts the update to other clients (including * this one). */ onChatMessage(matchID, chatMessage) { const args = [ matchID, chatMessage, this.credentials, ]; this.master.onChatMessage(...args); } /** * Called when another player makes a move and the * master broadcasts the update to other clients (including * this one). */ async onUpdate(matchID, state, deltalog) { const currentState = this.store.getState(); if (matchID == this.matchID && state._stateID >= currentState._stateID) { const action = update$1(state, deltalog); this.store.dispatch(action); } } /** * Called when the client first connects to the master * and requests the current game state. */ onSync(matchID, syncInfo) { if (matchID == this.matchID) { const action = sync(syncInfo); this.store.dispatch(action); } } /** * Called when an action that has to be relayed to the * game master is made. */ onAction(state, action) { this.master.onUpdate(action, state._stateID, this.matchID, this.playerID); } /** * Connect to the master. */ connect() { this.master.connect(this.matchID, this.playerID, (data) => { switch (data.type) { case 'sync': return this.onSync(...data.args); case 'update': return this.onUpdate(...data.args); case 'chat': return this.chatMessageCallback(data.args[1]); } }); this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers); } /** * Disconnect from the master. */ disconnect() { } /** * Subscribe to connection state changes. */ subscribe() { } subscribeMatchData() { } subscribeChatMessage(fn) { this.chatMessageCallback = fn; } /** * Dispatches a reset action, then requests a fresh sync from the master. */ resetAndSync() { const action = reset(null); this.store.dispatch(action); this.connect(); } /** * Updates the game id. * @param {string} id - The new game id. */ updateMatchID(id) { this.matchID = id; this.resetAndSync(); } /** * Updates the player associated with this client. * @param {string} id - The new player id. */ updatePlayerID(id) { this.playerID = id; this.resetAndSync(); } /** * Updates the credentials associated with this client. * @param {string|undefined} credentials - The new credentials to use. */ updateCredentials(credentials) { this.credentials = credentials; this.resetAndSync(); } } /** * Global map storing local master instances. */ const localMasters = new Map(); /** * Create a local transport. */ function Local({ bots, persist, storageKey } = {}) { return (transportOpts) => { const { gameKey, game } = transportOpts; let master; const instance = localMasters.get(gameKey); if (instance && instance.bots === bots && instance.storageKey === storageKey && instance.persist === persist) { master = instance.master; } if (!master) { master = new LocalMaster({ game, bots, persist, storageKey }); localMasters.set(gameKey, { master, bots, persist, storageKey }); } return new LocalTransport({ master, ...transportOpts }); }; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const io = ioNamespace__default; /** * SocketIO * * Transport interface that interacts with the Master via socket.io. */ class SocketIOTransport extends Transport { /** * Creates a new Mutiplayer instance. * @param {object} socket - Override for unit tests. * @param {object} socketOpts - Options to pass to socket.io. * @param {string} matchID - The game ID to connect to. * @param {string} playerID - The player ID associated with this client. * @param {string} gameName - The game type (the `name` field in `Game`). * @param {string} numPlayers - The number of players. * @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided. */ constructor({ socket, socketOpts, store, matchID, playerID, credentials, gameName, numPlayers, server, } = {}) { super({ store, gameName, playerID, matchID, credentials, numPlayers }); this.server = server; this.socket = socket; this.socketOpts = socketOpts; this.isConnected = false; this.callback = () => { }; this.matchDataCallback = () => { }; this.chatMessageCallback = () => { }; } /** * Called when an action that has to be relayed to the * game master is made. */ onAction(state, action) { const args = [ action, state._stateID, this.matchID, this.playerID, ]; this.socket.emit('update', ...args); } onChatMessage(matchID, chatMessage) { const args = [ matchID, chatMessage, this.credentials, ]; this.socket.emit('chat', ...args); } /** * Connect to the server. */ connect() { if (!this.socket) { if (this.server) { let server = this.server; if (server.search(/^https?:\/\//) == -1) { server = 'http://' + this.server; } if (server.slice(-1) != '/') { // add trailing slash if not already present server = server + '/'; } this.socket = io(server + this.gameName, this.socketOpts); } else { this.socket = io('/' + this.gameName, this.socketOpts); } } // Called when another player makes a move and the // master broadcasts the update to other clients (including // this one). this.socket.on('update', (matchID, state, deltalog) => { const currentState = this.store.getState(); if (matchID == this.matchID && state._stateID >= currentState._stateID) { const action = update$1(state, deltalog); this.store.dispatch(action); } }); // Called when the client first connects to the master // and requests the current game state. this.socket.on('sync', (matchID, syncInfo) => { if (matchID == this.matchID) { const action = sync(syncInfo); this.matchDataCallback(syncInfo.filteredMetadata); this.store.dispatch(action); } }); // Called when new player joins the match or changes // it's connection status this.socket.on('matchData', (matchID, matchData) => { if (matchID == this.matchID) { this.matchDataCallback(matchData); } }); this.socket.on('chat', (matchID, chatMessage) => { if (matchID === this.matchID) { this.chatMessageCallback(chatMessage); } }); // Keep track of connection status. this.socket.on('connect', () => { // Initial sync to get game state. this.sync(); this.isConnected = true; this.callback(); }); this.socket.on('disconnect', () => { this.isConnected = false; this.callback(); }); } /** * Disconnect from the server. */ disconnect() { this.socket.close(); this.socket = null; this.isConnected = false; this.callback(); } /** * Subscribe to connection state changes. */ subscribe(fn) { this.callback = fn; } subscribeMatchData(fn) { this.matchDataCallback = fn; } subscribeChatMessage(fn) { this.chatMessageCallback = fn; } /** * Send a “sync” event to the server. */ sync() { if (this.socket) { const args = [ this.matchID, this.playerID, this.credentials, this.numPlayers, ]; this.socket.emit('sync', ...args); } } /** * Dispatches a reset action, then requests a fresh sync from the server. */ resetAndSync() { const action = reset(null); this.store.dispatch(action); this.sync(); } /** * Updates the game id. * @param {string} id - The new game id. */ updateMatchID(id) { this.matchID = id; this.resetAndSync(); } /** * Updates the player associated with this client. * @param {string} id - The new player id. */ updatePlayerID(id) { this.playerID = id; this.resetAndSync(); } /** * Updates the credentials associated with this client. * @param {string|undefined} credentials - The new credentials to use. */ updateCredentials(credentials) { this.credentials = credentials; this.resetAndSync(); } } function SocketIO({ server, socketOpts } = {}) { return (transportOpts) => new SocketIOTransport({ server, socketOpts, ...transportOpts, }); } export { Client, Local, MCTSBot, RandomBot, Client$1 as ReactClient, Client$2 as ReactNativeClient, Simulate, SocketIO, Step, TurnOrder };
ajax/libs/react-instantsearch/4.3.0-beta.0/Connectors.js
cdnjs/cdnjs
/*! ReactInstantSearch 4.3.0-beta.0 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Connectors = {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto$2 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto$2.toString; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$2.call(value, symToStringTag$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$3.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$1.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$1.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]'; var arrayTag = '[object Array]'; var boolTag = '[object Boolean]'; var dateTag = '[object Date]'; var errorTag = '[object Error]'; var funcTag = '[object Function]'; var mapTag = '[object Map]'; var numberTag = '[object Number]'; var objectTag = '[object Object]'; var regexpTag = '[object RegExp]'; var setTag = '[object Set]'; var stringTag = '[object String]'; var weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]'; var dataViewTag = '[object DataView]'; var float32Tag = '[object Float32Array]'; var float64Tag = '[object Float64Array]'; var int8Tag = '[object Int8Array]'; var int16Tag = '[object Int16Array]'; var int32Tag = '[object Int32Array]'; var uint8Tag = '[object Uint8Array]'; var uint8ClampedTag = '[object Uint8ClampedArray]'; var uint16Tag = '[object Uint16Array]'; var uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$3.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]'; var funcTag$1 = '[object Function]'; var genTag = '[object GeneratorFunction]'; var proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto$1 = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString$1.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype; var objectProto$6 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$6.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$7.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$5.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$8.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$6.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } var _baseFindIndex = baseFindIndex; /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } var _baseIsNaN = baseIsNaN; /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } var _strictIndexOf = strictIndexOf; /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); } var _baseIndexOf = baseIndexOf; /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && _baseIndexOf(array, value, 0) > -1; } var _arrayIncludes = arrayIncludes; /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } var _arrayIncludesWith = arrayIncludesWith; /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = _arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = _arrayMap(values, _baseUnary(iteratee)); } if (comparator) { includes = _arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = _cacheHas; isCommon = false; values = new _SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } var _baseDifference = baseDifference; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty = defineProperty; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { return _defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800; var HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = _baseRest(function(array, values) { return isArrayLikeObject_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE$1 - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty) { _defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$9.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty$7.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$10 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$10.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$8.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$11 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$11.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag$2 = '[object Map]'; var objectTag$2 = '[object Object]'; var promiseTag = '[object Promise]'; var setTag$2 = '[object Set]'; var weakMapTag$2 = '[object WeakMap]'; var dataViewTag$2 = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView); var mapCtorString = _toSource(_Map); var promiseCtorString = _toSource(_Promise); var setCtorString = _toSource(_Set); var weakMapCtorString = _toSource(_WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2) || (_Map && getTag(new _Map) != mapTag$2) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$2) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$2 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$2; case mapCtorString: return mapTag$2; case promiseCtorString: return promiseTag; case setCtorString: return setTag$2; case weakMapCtorString: return weakMapTag$2; } } return result; }; } var _getTag = getTag; /** Used for built-in method references. */ var objectProto$12 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$12.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$9.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } var _addMapEntry = addMapEntry; /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } var _arrayReduce = arrayReduce; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$2 = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(_mapToArray(map), CLONE_DEEP_FLAG$2) : _mapToArray(map); return _arrayReduce(array, _addMapEntry, new map.constructor); } var _cloneMap = cloneMap; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } var _addSetEntry = addSetEntry; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$3 = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(_setToArray(set), CLONE_DEEP_FLAG$3) : _setToArray(set); return _arrayReduce(array, _addSetEntry, new set.constructor); } var _cloneSet = cloneSet; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined; var symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$2 = '[object Boolean]'; var dateTag$2 = '[object Date]'; var mapTag$3 = '[object Map]'; var numberTag$2 = '[object Number]'; var regexpTag$2 = '[object RegExp]'; var setTag$3 = '[object Set]'; var stringTag$2 = '[object String]'; var symbolTag$1 = '[object Symbol]'; var arrayBufferTag$2 = '[object ArrayBuffer]'; var dataViewTag$3 = '[object DataView]'; var float32Tag$2 = '[object Float32Array]'; var float64Tag$2 = '[object Float64Array]'; var int8Tag$2 = '[object Int8Array]'; var int16Tag$2 = '[object Int16Array]'; var int32Tag$2 = '[object Int32Array]'; var uint8Tag$2 = '[object Uint8Array]'; var uint8ClampedTag$2 = '[object Uint8ClampedArray]'; var uint16Tag$2 = '[object Uint16Array]'; var uint32Tag$2 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$2: return _cloneArrayBuffer(object); case boolTag$2: case dateTag$2: return new Ctor(+object); case dataViewTag$3: return _cloneDataView(object, isDeep); case float32Tag$2: case float64Tag$2: case int8Tag$2: case int16Tag$2: case int32Tag$2: case uint8Tag$2: case uint8ClampedTag$2: case uint16Tag$2: case uint32Tag$2: return _cloneTypedArray(object, isDeep); case mapTag$3: return _cloneMap(object, isDeep, cloneFunc); case numberTag$2: case stringTag$2: return new Ctor(object); case regexpTag$2: return _cloneRegExp(object); case setTag$3: return _cloneSet(object, isDeep, cloneFunc); case symbolTag$1: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1; var CLONE_FLAT_FLAG$1 = 2; var CLONE_SYMBOLS_FLAG$1 = 4; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]'; var arrayTag$1 = '[object Array]'; var boolTag$1 = '[object Boolean]'; var dateTag$1 = '[object Date]'; var errorTag$1 = '[object Error]'; var funcTag$2 = '[object Function]'; var genTag$1 = '[object GeneratorFunction]'; var mapTag$1 = '[object Map]'; var numberTag$1 = '[object Number]'; var objectTag$1 = '[object Object]'; var regexpTag$1 = '[object RegExp]'; var setTag$1 = '[object Set]'; var stringTag$1 = '[object String]'; var symbolTag = '[object Symbol]'; var weakMapTag$1 = '[object WeakMap]'; var arrayBufferTag$1 = '[object ArrayBuffer]'; var dataViewTag$1 = '[object DataView]'; var float32Tag$1 = '[object Float32Array]'; var float64Tag$1 = '[object Float64Array]'; var int8Tag$1 = '[object Int8Array]'; var int16Tag$1 = '[object Int16Array]'; var int32Tag$1 = '[object Int32Array]'; var uint8Tag$1 = '[object Uint8Array]'; var uint8ClampedTag$1 = '[object Uint8ClampedArray]'; var uint16Tag$1 = '[object Uint16Array]'; var uint32Tag$1 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] = cloneableTags[boolTag$1] = cloneableTags[dateTag$1] = cloneableTags[float32Tag$1] = cloneableTags[float64Tag$1] = cloneableTags[int8Tag$1] = cloneableTags[int16Tag$1] = cloneableTags[int32Tag$1] = cloneableTags[mapTag$1] = cloneableTags[numberTag$1] = cloneableTags[objectTag$1] = cloneableTags[regexpTag$1] = cloneableTags[setTag$1] = cloneableTags[stringTag$1] = cloneableTags[symbolTag] = cloneableTags[uint8Tag$1] = cloneableTags[uint8ClampedTag$1] = cloneableTags[uint16Tag$1] = cloneableTags[uint32Tag$1] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$1] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG$1, isFlat = bitmask & CLONE_FLAT_FLAG$1, isFull = bitmask & CLONE_SYMBOLS_FLAG$1; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$1 || tag == argsTag$2 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = _initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** `Object#toString` result references. */ var symbolTag$2 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; var reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var reLeadingDot = /^\./; var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined; var symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } var last_1 = last; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1)); } var _parent = parent; /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = _castPath(path, object); object = _parent(object, path); return object == null || delete object[_toKey(last_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype; var objectProto$13 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$10 = objectProto$13.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$10.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? _baseFlatten(array, 1) : []; } var flatten_1 = flatten; /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return _setToString(_overRest(func, undefined, flatten_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; var CLONE_FLAT_FLAG = 2; var CLONE_SYMBOLS_FLAG = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = _flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = _arrayMap(paths, function(path) { path = _castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); _copyObject(object, _getAllKeysIn(object), result); if (isDeep) { result = _baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, _customOmitClone); } var length = paths.length; while (length--) { _baseUnset(result, paths[length]); } return result; }); var omit_1 = omit; var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } 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); } function nextTick(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); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd() { return '/'; } function chdir(dir) { throw new Error('process.chdir is not supported'); } function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp) { var clocktime = performanceNow.call(performance) * 1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor(clocktime % 1 * 1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds < 0) { seconds--; nanoseconds += 1e9; } } return [seconds, nanoseconds]; } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1; var COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; var COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]'; var dateTag$3 = '[object Date]'; var errorTag$2 = '[object Error]'; var mapTag$4 = '[object Map]'; var numberTag$3 = '[object Number]'; var regexpTag$3 = '[object RegExp]'; var setTag$4 = '[object Set]'; var stringTag$3 = '[object String]'; var symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]'; var dataViewTag$4 = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined; var symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag$4: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag$3: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag$3: case dateTag$3: case numberTag$3: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag$2: return object.name == other.name && object.message == other.message; case regexpTag$3: case stringTag$3: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag$4: var convert = _mapToArray; case setTag$4: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag$3: if (symbolValueOf$1) { return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); } } return false; } var _equalByTag = equalByTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** Used for built-in method references. */ var objectProto$15 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$12 = objectProto$15.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$12.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]'; var arrayTag$2 = '[object Array]'; var objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var objectProto$14 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$11 = objectProto$14.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$2 : _getTag(object), othTag = othIsArr ? arrayTag$2 : _getTag(other); objTag = objTag == argsTag$3 ? objectTag$4 : objTag; othTag = othTag == argsTag$3 ? objectTag$4 : othTag; var objIsObj = objTag == objectTag$4, othIsObj = othTag == objectTag$4, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty$11.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$11.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** Used for built-in method references. */ var objectProto$16 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$13 = objectProto$16.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$13.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has; /** * 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; }; var emptyFunction_1 = emptyFunction; function invariant(condition, format, a, b, c, d, e, f) { 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; } } var invariant_1 = invariant; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty$14 = 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; } } var objectAssign = 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$14.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; }; /** * 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'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // It is still safe when called from React. return; } invariant_1( false, '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' ); } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * 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. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); /** `Object#toString` result references. */ var mapTag$5 = '[object Map]'; var setTag$5 = '[object Set]'; /** Used for built-in method references. */ var objectProto$17 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$15 = objectProto$17.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$5 || tag == setTag$5) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$15.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } 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. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function getDisplayName(Component$$1) { return Component$$1.displayName || Component$$1.name || 'UnknownComponent'; } function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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 defineProperty$2 = function (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; }; 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 inherits = function (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 possibleConstructorReturn = function (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; }; var slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var toConsumableArray = function (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); } }; /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { inherits(Connector, _Component); function Connector(props, context) { classCallCheck(this, Connector); var _this = possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; var canRender = false; _this.state = { props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })), canRender: canRender // use to know if a component is rendered (browser), or not (server). }; _this.unsubscribe = store.subscribe(function () { if (_this.state.canRender) { _this.setState({ props: _this.getProvidedProps(_extends({}, _this.props, { canRender: _this.state.canRender })) }); } }); if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget(_this); } return _this; } createClass(Connector, [{ key: 'getMetadata', value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: 'transitionState', value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: 'componentDidMount', value: function componentDidMount() { this.setState({ canRender: true }); } }, { key: 'componentWillMount', value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); // will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange(removeEmptyKey(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: 'render', value: function render() { var _this2 = this; if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues, searchForFacetValues: function searchForFacetValues(facetName, query) { _this2.searchForFacetValues(facetName, query); } } : {}; return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }, _initialiseProps = function _initialiseProps() { var _this3 = this; this.getProvidedProps = function (props) { var store = _this3.context.ais.store; var _store$getState = store.getState(), results = _store$getState.results, searching = _store$getState.searching, error = _store$getState.error, widgets = _store$getState.widgets, metadata = _store$getState.metadata, resultsFacetValues = _store$getState.resultsFacetValues, searchingForFacetValues = _store$getState.searchingForFacetValues; var searchState = { results: results, searching: searching, error: error, searchingForFacetValues: searchingForFacetValues }; return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args)); }; }, _temp; }; } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get$1(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get$1; function getIndex(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndex(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndex(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { /* If we have a multi index page with shared widgets we should also reset their page to 1 see: https://github.com/algolia/react-instantsearch/issues/310 */ if (searchState.indices) { Object.keys(searchState.indices).forEach(function (targetedIndex) { searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace); }); } return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var index = getIndex(context); var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, nextRefinement, page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) { var _babelHelpers$extends3; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], (_babelHelpers$extends3 = {}, defineProperty$2(_babelHelpers$extends3, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), defineProperty$2(_babelHelpers$extends3, 'page', 1), _babelHelpers$extends3)))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends(defineProperty$2({}, namespace, nextRefinement), page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, defineProperty$2({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page); } function getNamespaceAndAttributeName(id) { var parts = id.match(/^([^.]*)\.(.*)/); var namespace = parts && parts[1]; var attributeName = parts && parts[2]; return { namespace: namespace, attributeName: attributeName }; } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) { var index = getIndex(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id); if (refinements) { var currentRefinement = void 0; if (hasMultipleIndex(context)) { currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id); } else { currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id); } return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var index = getIndex(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndex(context)) { return namespace ? _extends({}, searchState, { indices: _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], defineProperty$2({}, namespace, omit_1(searchState.indices[index][namespace], '' + attributeName))))) }) : omit_1(searchState, 'indices.' + index + '.' + id); } else { return namespace ? _extends({}, searchState, defineProperty$2({}, namespace, omit_1(searchState[namespace], '' + attributeName))) : omit_1(searchState, '' + id); } } function getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = defineProperty$2({}, id, _extends({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = getIndex(this.context); var subState = hasMultipleIndex(this.context) && searchState.indices ? searchState.indices[index] : searchState; var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = subState[id][item]; } return acc; }, {}); var nextValue = defineProperty$2({}, id, configureState); return refineValue(searchState, nextValue, this.context); } }); /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items); } } return res; }, []); return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? _arrayIncludesWith : _arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = _arrayMap(array, _baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new _SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } var _baseIntersection = baseIntersection; /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = _baseRest(function(arrays) { var mapped = _arrayMap(arrays, _castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? _baseIntersection(mapped) : []; }); var intersection_1 = intersection; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity_1; } var _castFunction = castFunction; /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && _baseForOwn(object, _castFunction(iteratee)); } var forOwn_1 = forOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var _baseFilter = baseFilter; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1; var COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1; var COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } var _baseReduce = baseReduce; /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0; var MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$1(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } var _createFind = createFind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = _createFind(findIndex_1); var find_1 = find; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : _baseSlice(array, start, end); } var _castSlice = castSlice; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsEndIndex = charsEndIndex; /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsStartIndex = charsStartIndex; /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff'; var rsComboMarksRange = '\\u0300-\\u036f'; var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange = '\\u20d0-\\u20ff'; var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; var rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff'; var rsComboMarksRange$1 = '\\u0300-\\u036f'; var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; var rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']'; var rsCombo = '[' + rsComboRange$1 + ']'; var rsFitz = '\\ud83c[\\udffb-\\udfff]'; var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; var rsNonAstral = '[^' + rsAstralRange$1 + ']'; var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; var rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?'; var rsOptVar = '[' + rsVarRange$1 + ']?'; var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; var rsSeq = rsOptVar + reOptMod + rsOptJoin; var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } var _unicodeToArray = unicodeToArray; /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } if (!string || !(chars = _baseToString(chars))) { return string; } var strSymbols = _stringToArray(string), chrSymbols = _stringToArray(chars), start = _charsStartIndex(strSymbols, chrSymbols), end = _charsEndIndex(strSymbols, chrSymbols) + 1; return _castSlice(strSymbols, start, end).join(''); } var trim_1 = trim; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return _baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var _createAssigner = createAssigner; /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = _createAssigner(function(object, source, srcIndex, customizer) { _copyObject(source, keysIn_1(source), object, customizer); }); var assignInWith_1 = assignInWith; /** Used for built-in method references. */ var objectProto$18 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$16 = objectProto$18.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq_1(objValue, objectProto$18[key]) && !hasOwnProperty$16.call(object, key))) { return srcValue; } return objValue; } var _customDefaultsAssignIn = customDefaultsAssignIn; /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults$1 = _baseRest(function(args) { args.push(undefined, _customDefaultsAssignIn); return _apply(assignInWith_1, undefined, args); }); var defaults_1 = defaults$1; /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return _copyObject(value, keysIn_1(value)); } var toPlainObject_1 = toPlainObject; /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { _assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(objValue)) { newValue = _copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = _cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = _cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || (srcIndex && isFunction_1(objValue))) { newValue = _initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } _assignMergeValue(object, key, newValue); } var _baseMergeDeep = baseMergeDeep; /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } _baseFor(source, function(srcValue, key) { if (isObject_1(srcValue)) { stack || (stack = new _Stack); _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } _assignMergeValue(object, key, newValue); } }, keysIn_1); } var _baseMerge = baseMerge; /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = _createAssigner(function(object, source, srcIndex) { _baseMerge(object, source, srcIndex); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (isArray_1(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated refinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults_1({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * kinds of behavior can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optional parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { return reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(facetList)) memo[key] = facetList; return memo; }, {}); } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find_1(array, function(currentValue) { return isEqual_1(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * separated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each faceted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys_1(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (isArray_1(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach_1(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) faceting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber_1(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { return reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) operatorList[operator] = outValues; }); if (!isEmpty_1(operatorList)) memo[key] = operatorList; return memo; }, {}); } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter_1(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the faceted attribute. * @method * @param {string} facet name of the attribute used for faceting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf_1(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf_1(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value, optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf_1(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf_1(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys_1(params); forEach_1(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState_1(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find_1( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map_1(path, trim_1); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ var SearchParameters_1 = SearchParameters; /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } var compact_1 = compact; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? _baseSum(array, _baseIteratee(iteratee, 2)) : 0; } var sumBy_1 = sumBy; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !_metaMap ? identity_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = _baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG$1, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax$5(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax$6(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } var _composeArgsRight = composeArgsRight; /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$19 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$17 = objectProto$19.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = _realNames[result], length = hasOwnProperty$17.call(_realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } var _getFuncName = getFuncName; /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = _baseCreate(_baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; var _LodashWrapper = LodashWrapper; /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof _LazyWrapper) { return wrapper.clone(); } var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = _copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$20 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$18 = objectProto$20.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$18.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = _getFuncName(func), other = wrapperLodash[funcName]; if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = _getData(other); return !!data && func === data[0]; } var _isLaziable = isLaziable; /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = _shortOut(_baseSetData); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/; var reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } var _getWrapDetails = getWrapDetails; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; var WRAP_BIND_KEY_FLAG$3 = 2; var WRAP_CURRY_FLAG$3 = 8; var WRAP_CURRY_RIGHT_FLAG$2 = 16; var WRAP_PARTIAL_FLAG$3 = 32; var WRAP_PARTIAL_RIGHT_FLAG$2 = 64; var WRAP_ARY_FLAG$1 = 128; var WRAP_REARG_FLAG = 256; var WRAP_FLIP_FLAG$1 = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG$1], ['bind', WRAP_BIND_FLAG$4], ['bindKey', WRAP_BIND_KEY_FLAG$3], ['curry', WRAP_CURRY_FLAG$3], ['curryRight', WRAP_CURRY_RIGHT_FLAG$2], ['flip', WRAP_FLIP_FLAG$1], ['partial', WRAP_PARTIAL_FLAG$3], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { _arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } var _updateWrapDetails = updateWrapDetails; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1; var WRAP_BIND_KEY_FLAG$2 = 2; var WRAP_CURRY_BOUND_FLAG = 4; var WRAP_CURRY_FLAG$2 = 8; var WRAP_PARTIAL_FLAG$2 = 32; var WRAP_PARTIAL_RIGHT_FLAG$1 = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG$2, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$2 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$2); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$3 | WRAP_BIND_KEY_FLAG$2); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (_isLaziable(func)) { _setData(result, newData); } result.placeholder = placeholder; return _setWrapToString(result, func, bitmask); } var _createRecurry = createRecurry; /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1; var WRAP_BIND_KEY_FLAG$1 = 2; var WRAP_CURRY_FLAG$1 = 8; var WRAP_CURRY_RIGHT_FLAG$1 = 16; var WRAP_ARY_FLAG = 128; var WRAP_FLIP_FLAG = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG$2, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$1, isCurried = bitmask & (WRAP_CURRY_FLAG$1 | WRAP_CURRY_RIGHT_FLAG$1), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = _getHolder(wrapper), holdersCount = _countHolders(args, placeholder); } if (partials) { args = _composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = _composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = _replaceHolders(args, placeholder); return _createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = _reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== _root && this instanceof wrapper) { fn = Ctor || _createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } var _createHybrid = createHybrid; /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = _getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : _replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return _createRecurry( func, bitmask, _createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return _apply(fn, this, args); } return wrapper; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG$5, Ctor = _createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return _apply(fn, isBind ? thisArg : this, args); } return wrapper; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1; var WRAP_BIND_KEY_FLAG$4 = 2; var WRAP_CURRY_BOUND_FLAG$1 = 4; var WRAP_CURRY_FLAG$4 = 8; var WRAP_ARY_FLAG$2 = 128; var WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG$6 | WRAP_BIND_KEY_FLAG$4 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$4)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$4)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$6) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$6 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? _composeArgs(partials, value, source[4]) : value; data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; var WRAP_BIND_KEY_FLAG = 2; var WRAP_CURRY_FLAG = 8; var WRAP_CURRY_RIGHT_FLAG = 16; var WRAP_PARTIAL_FLAG$1 = 32; var WRAP_PARTIAL_RIGHT_FLAG = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$1 | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$4(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : _getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { _mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax$4(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = _createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = _createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG$1 || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG$1)) && !holders.length) { result = _createPartial(func, bitmask, thisArg, partials); } else { result = _createHybrid.apply(undefined, newData); } var setter = data ? _baseSetData : _setData; return _setWrapToString(setter(result, newData), func, bitmask); } var _createWrap = createWrap; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partial)); return _createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partialRight)); return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } var _baseClamp = baseClamp; /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject_1(object)) { return object; } path = _castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = _toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = _baseGet(object, path); if (predicate(value, path)) { _baseSet(result, _castPath(path, object), value); } } return result; } var _basePickBy = basePickBy; /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = _arrayMap(_getAllKeysIn(object), function(prop) { return [prop]; }); predicate = _baseIteratee(predicate); return _basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce_1(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find_1(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy_1( map_1( pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the faceting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objects matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} name the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric filters. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach_1(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy_1(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @deprecated * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @deprecated * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * True if the counts of the facets is exhaustive * @member {boolean} */ this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount; /** * True if the number of hits is exhaustive * @member {boolean} */ this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the faceted attribute * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the faceted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find_1(results.facets, predicate); if (!facet) return []; return map_1(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (isArray_1(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (isArray_1(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (isArray_1(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the faceted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find_1(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var util = createCommonjsModule(function (module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(commonjsGlobal.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = inherits_browser; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } var events = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber$2(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject$2(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined$2(handler)) return false; if (isFunction$2(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject$2(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction$2(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction$2(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject$2(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject$2(this._events[type]) && !this._events[type].warned) { if (!isUndefined$2(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction$2(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction$2(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction$2(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$2(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction$2(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction$2(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction$2(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$2(arg) { return typeof arg === 'function'; } function isNumber$2(arg) { return typeof arg === 'number'; } function isObject$2(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$2(arg) { return arg === void 0; } /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; var DerivedHelper_1 = DerivedHelper; var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters, analytics: false }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (isArray_1(value)) { var vs = map_1(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce_1( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var searchForFacetSearchParameters = { facetQuery: query, facetName: facetName }; if (typeof maxFacetHits === 'number') { searchForFacetSearchParameters.maxFacetHits = maxFacetHits; } var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { _baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } var _baseInverter = baseInverter; /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return _baseInverter(object, setter, toIteratee(iteratee), {}); }; } var _createInverter = createInverter; /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = _createInverter(function(result, value, key) { result[value] = key; }, constant_1(identity_1)); var invert_1 = invert; var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; var utils = createCommonjsModule(function (module, exports) { var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults$3 = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults$3.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$3.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$3.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; var stringify_1 = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults$3.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$3.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$3.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$3.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$3.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$3.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$3.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; var has$1 = Object.prototype.hasOwnProperty; var defaults$4 = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults$4.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$4.decoder); val = options.decoder(part.slice(pos + 1), defaults$4.decoder); } if (has$1.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has$1.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has$1.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var parse = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$4.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$4.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$4.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$4.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$4.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$4.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$4.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$4.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$4.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1; var WRAP_PARTIAL_FLAG$4 = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = _baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return _basePickBy(object, paths, function(value, path) { return hasIn_1(object, path); }); } var _basePick = basePick; /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = _flatRest(function(object, paths) { return object == null ? {} : _basePick(object, paths); }); var pick_1 = pick; /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, iteratee(value, key, object), value); }); return result; } var mapKeys_1 = mapKeys; /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (isArray_1(input)) { return map_1(input, recursiveEncode); } if (isString_1(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ var getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.22.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {SearchParameters} state the parameters used for this search * it is the first search. * @property {string} facet the facet searched into * @property {string} query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(state, facet, query) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {SearchParameters} state the parameters used for this search * it is the first search. * @example * helper.on('searchOnce', function(state) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Event triggered when the queue of queries have been depleted (with any result or outdated queries) * @event AlgoliaSearchHelper#event:searchQueueEmpty * @example * helper.on('searchQueueEmpty', function() { * console.log('No more search pending'); * // This is received before the result event if we're not expecting new results * }); * * helper.search(); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version$1); this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; this._currentNbQueries = 0; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder_1._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occurred it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder_1._getQueries(tempState.index, tempState); var self = this; this._currentNbQueries++; this.emit('searchOnce', tempState); if (cb) { return this.client.search( queries, function(err, content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); if (err) cb(err, null, tempState); else cb(err, new SearchResults_1(tempState, content.results), tempState); } ); } return this.client.search(queries).then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); return { content: new SearchResults_1(tempState, content.results), state: tempState, _originalResponse: content }; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurrence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {object} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query inside the engine */ /** * Search for facet values based on an query and the name of a faceted attribute. This * triggers a search and will return a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed down to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} facet the name of the faceted attribute * @param {string} query the string query for the search * @param {number} maxFacetHits the maximum number values returned. Should be > 0 and <= 100 * @return {promise<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits) { var state = this.state; var index = this.client.initIndex(this.state.index); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, this.state); this._currentNbQueries++; var self = this; this.emit('searchForFacetValues', state, facet, query); return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); content.facetHits = forEach_1(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this.state = this.state.setPage(0).setQuery(q); this._change(); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this.state = this.state.setPage(0).clearRefinements(name); this._change(); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this.state = this.state.setPage(0).clearTags(); this._change(); return this; }; /** * Adds a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value); this._change(); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Adds a filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).addExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this.state = this.state.setPage(0).addTagRefinement(tag); this._change(); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optional, triggering different behavior: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Removes a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet); this._change(); return this; }; /** * Removes a filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).removeExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this.state = this.state.setPage(0).removeTagRefinement(tag); this._change(); return this; }; /** * Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).toggleFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this.state = this.state.setPage(0).toggleTagRefinement(tag); this._change(); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this.state = this.state.setPage(page); this._change(); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this.state = this.state.setPage(0).setIndex(name); this._change(); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { var newState = this.state.setPage(0).setQueryParameter(parameter, value); if (this.state === newState) return this; this.state = newState; this._change(); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this.state = SearchParameters_1.make(newState); this._change(); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optional filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optional parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters_1(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty_1(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific faceted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for faceting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten_1(derivedQueries)); var queryId = this._queryId++; this._currentNbQueries++; this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId)); }; /** * Transform the responses as sent by the server and transform them into a user * usable object that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {Error} err error if any, null otherwise * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) { // FIXME remove the number of outdated queries discarded instead of just one if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= (queryId - this._lastQueryIdReceived); this._lastQueryIdReceived = queryId; if (err) { this.emit('error', err); if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); } else { if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); var results = content.results; forEach_1(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults); helper.emit('result', formattedResponse, state); }); } }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function() { this.emit('change', this.state, this.lastResults); }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper_1(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * This method returns true if there is currently at least one on-going search. * @return {boolean} true if there is a search pending */ AlgoliaSearchHelper.prototype.hasPendingRequests = function() { return this._currentNbQueries > 0; }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the faceting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } var algoliasearch_helper = AlgoliaSearchHelper; /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters; var getId$1 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace + '.' + getId$1(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$2(path, props, searchState, context) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement(props, searchState, context); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_4({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue$2(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _extends({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine(props, searchState, nextRefinement, context) { var id = getId$1(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, namespace + '.' + getId$1(props)); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ var connectHierarchicalMenu = createConnector({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: propTypes.string, rootPath: propTypes.string, showParentLevel: propTypes.bool, defaultRefinement: propTypes.string, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, transformItems: propTypes.func }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var id = getId$1(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: false }; } var limit = showMore ? limitMax : limitMin; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue(value.data, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, limit), currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var id = getId$1(props); var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); var currentRefinement = getCurrentRefinement(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId$1(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attributeName: rootAttribute, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /** * Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attributeName - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseAlgoliaHit(_ref) { var _ref$preTag = _ref.preTag, preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag, highlightProperty = _ref.highlightProperty, attributeName = _ref.attributeName, hit = _ref.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = get_1(hit[highlightProperty], attributeName); var highlightedValue = !highlightObject ? '' : highlightObject.value; return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue }); } /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref2) { var preTag = _ref2.preTag, postTag = _ref2.postTag, highlightedValue = _ref2.highlightedValue; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } var highlightTags = { highlightPreTag: "<ais-highlight-0000000000>", highlightPostTag: "</ais-highlight-0000000000>" }; var highlight = function highlight(_ref) { var attributeName = _ref.attributeName, hit = _ref.hit, highlightProperty = _ref.highlightProperty; return parseAlgoliaHit({ attributeName: attributeName, hit: hit, preTag: highlightTags.highlightPreTag, postTag: highlightTags.highlightPostTag, highlightProperty: highlightProperty }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`. * @example * import React from 'react'; * import { connectHighlight } from 'react-instantsearch/connectors'; * import { InstantSearch, Hits } from 'react-instantsearch/dom'; * * const CustomHighlight = connectHighlight( * ({ highlight, attributeName, hit, highlightProperty }) => { * const parsedHit = highlight({ attributeName, hit, highlightProperty: '_highlightResult' }); * const highlightedHits = parsedHit.map(part => { * if (part.isHighlighted) return <mark>{part.value}</mark>; * return part.value; * }); * return <div>{highlightedHits}</div>; * } * ); * * const Hit = ({hit}) => * <p> * <CustomHighlight attributeName="description" hit={hit} /> * </p>; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea"> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); * } */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * * import { Highlight, InstantSearch } from 'react-instantsearch/dom'; * import { connectHits } from 'react-instantsearch/connectors'; * const CustomHits = connectHits(({ hits }) => * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attributeName="description" hit={hit} /> * </p> * )} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); var hits = results ? results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); var getId$2 = function getId() { return 'query'; }; function getCurrentRefinement$1(props, searchState, context) { var id = getId$2(); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function getHits(searchResults) { if (searchResults.results) { if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) { return searchResults.results.hits; } else { return Object.keys(searchResults.results).reduce(function (hits, index) { return [].concat(toConsumableArray(hits), [{ index: index, hits: searchResults.results[index].hits }]); }, []); } } else { return []; } } function _refine$1(props, searchState, nextRefinement, context) { var id = getId$2(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, getId$2()); } /** * connectAutoComplete connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * @name connectAutoComplete * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state. * @providedPropType {function} refine - a function to change the query. * @providedPropType {string} currentRefinement - the query to search for. */ var connectAutoComplete = createConnector({ displayName: 'AlgoliaAutoComplete', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { hits: getHits(searchResults), currentRefinement: getCurrentRefinement$1(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, this.context); }, /* connectAutoComplete needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$1(props, searchState, this.context)); } }); function getId$3() { return 'hitsPerPage'; } function getCurrentRefinement$2(props, searchState, context) { var id = getId$3(); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectHitsPerPage = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$2(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$3(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$3()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$2(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId$3() }; } }); function getId$4() { return 'page'; } function getCurrentRefinement$3(props, searchState, context) { var id = getId$4(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ var connectInfiniteHits = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var hits = results.hits, page = results.page, nbPages = results.nbPages; // If it is the same page we do not touch the page result list if (page === 0) { this._allResults = hits; } else if (page > this.previousPage) { this._allResults = [].concat(toConsumableArray(this._allResults), toConsumableArray(hits)); } else if (page < this.previousPage) { this._allResults = hits; } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; this.previousPage = page; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$3(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId$4(); var nextPage = getCurrentRefinement$3(props, searchState, this.context) + 1; var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, this.context, resetPage); } }); var namespace$1 = 'menu'; function getId$5(props) { return props.attributeName; } function getCurrentRefinement$4(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$5(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$3(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$4(props, searchState, context); return name === currentRefinement ? '' : name; } function _refine$2(props, searchState, nextRefinement, context) { var id = getId$5(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, namespace$1 + '.' + getId$5(props)); } var sortBy$1 = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user the ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [withSearchBox=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attributeName: propTypes.string.isRequired, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, withSearchBox: propTypes.bool, searchForFacetValues: propTypes.bool // @deprecated }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$4(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = withSearchBox && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement$4(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters.addDisjunctiveFacet(attributeName); var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId$5(props); var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: props.attributeName + ': ' + currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _refine$2(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'), _value$split2 = slicedToArray(_value$split, 2), startStr = _value$split2[0], endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace$2 = 'multiRange'; function getId$6(props) { return props.attributeName; } function getCurrentRefinement$5(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$6(props), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attributeName, results, value) { var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine$3(props, searchState, nextRefinement, context) { var nextValue = defineProperty$2({}, getId$6(props, searchState), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, namespace$2 + '.' + getId$6(props)); } /** * connectMultiRange connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectMultiRange * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @kind connector * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display. */ var connectMultiRange = createConnector({ displayName: 'AlgoliaMultiRange', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement$5(props, searchState, this.context); var results = getResults(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId$6(props), results, value) : false }; }); var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$3(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var _parseItem = parseItem(getCurrentRefinement$5(props, searchState, this.context)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attributeName); if (start) { searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$6(props); var value = getCurrentRefinement$5(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (value !== '') { var _find2 = find_1(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: props.attributeName + ': ' + label, attributeName: props.attributeName, currentRefinement: label, value: function value(nextState) { return _refine$3(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); function getId$7() { return 'page'; } function getCurrentRefinement$6(props, searchState, context) { var id = getId$7(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine$4(props, searchState, nextPage, context) { var id = getId$7(); var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, context, resetPage); } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ var connectPagination = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$6(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$4(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$7()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$6(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$7() }; } }); /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ var connectPoweredBy = createConnector({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps(props) { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite; /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - Name of the attribute for faceting * @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {number} [precision=2] - Number of digits after decimal point to use. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied */ function getId$8(props) { return props.attributeName; } var namespace$3 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min = void 0; if (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max = void 0; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$7(props, searchState, currentRange, context) { var refinement = getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$8(props), {}, function (currentRefinement) { var min = currentRefinement.min, max = currentRefinement.max; if (typeof min === 'string') { min = parseInt(min, 10); } if (typeof max === 'string') { max = parseInt(max, 10); } return { min: min, max: max }; }); var hasMinBound = props.min !== undefined; var hasMaxBound = props.max !== undefined; var hasMinRefinment = refinement.min !== undefined; var hasMaxRefinment = refinement.max !== undefined; if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) { throw Error("You can't provide min value lower than range."); } if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) { throw Error("You can't provide max value greater than range."); } if (hasMinBound && !hasMinRefinment) { refinement.min = currentRange.min; } if (hasMaxBound && !hasMaxRefinment) { refinement.max = currentRange.max; } return refinement; } function nextValueForRefinement(hasBound, isReset, range, value) { var next = void 0; if (!hasBound && range === value) { next = undefined; } else if (hasBound && isReset) { next = range; } else { next = value; } return next; } function _refine$5(props, searchState, nextRefinement, currentRange, context) { var nextMin = nextRefinement.min, nextMax = nextRefinement.max; var currentMinRange = currentRange.min, currentMaxRange = currentRange.max; var isMinReset = nextMin === undefined || nextMin === ''; var isMaxReset = nextMax === undefined || nextMax === ''; var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined; var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined; var isNextMinValid = isMinReset || _isFinite(nextMinAsNumber); var isNextMaxValid = isMaxReset || _isFinite(nextMaxAsNumber); if (!isNextMinValid || !isNextMaxValid) { throw Error("You can't provide non finite values to the range connector."); } if (nextMinAsNumber < currentMinRange) { throw Error("You can't provide min value lower than range."); } if (nextMaxAsNumber > currentMaxRange) { throw Error("You can't provide max value greater than range."); } var id = getId$8(props); var resetPage = true; var nextValue = defineProperty$2({}, id, { min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber), max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber) }); return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, namespace$3 + '.' + getId$8(props)); } var connectRange = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number.isRequired, max: propTypes.number.isRequired }), min: propTypes.number, max: propTypes.number, precision: propTypes.number }, defaultProps: { precision: 2 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var stats = results ? results.getFacetStats(attributeName) || {} : {}; var count = results ? results.getFacetValues(attributeName).map(function (v) { return { value: v.name, count: v.count }; }) : []; var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var _getCurrentRefinement = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), valueMin = _getCurrentRefinement.min, valueMax = _getCurrentRefinement.max; return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: { min: valueMin === undefined ? rangeMin : valueMin, max: valueMax === undefined ? rangeMax : valueMax }, count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$5(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attributeName = props.attributeName; var _getCurrentRefinement2 = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), min = _getCurrentRefinement2.min, max = _getCurrentRefinement2.max; params = params.addDisjunctiveFacet(attributeName); if (min !== undefined) { params = params.addNumericRefinement(attributeName, '>=', min); } if (max !== undefined) { params = params.addNumericRefinement(attributeName, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var _currentRange = this._currentRange, minRange = _currentRange.min, maxRange = _currentRange.max; var _getCurrentRefinement3 = getCurrentRefinement$7(props, searchState, this._currentRange, this.context), minValue = _getCurrentRefinement3.min, maxValue = _getCurrentRefinement3.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? minValue + ' <= ' : '', props.attributeName, hasMax ? ' <= ' + maxValue : '']; items.push({ label: fragments.join(''), attributeName: props.attributeName, value: function value(nextState) { return _refine$5(props, nextState, {}, _this._currentRange, _this.context); }, currentRefinement: { min: minValue, max: maxValue } }); } return { id: getId$8(props), index: getIndex(this.context), items: items }; } }); var namespace$4 = 'refinementList'; function getId$9(props) { return props.attributeName; } function getCurrentRefinement$8(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$9(props), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue$4(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$8(props, searchState, context); var isAnewValue = currentRefinement.indexOf(name) === -1; var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates : currentRefinement.filter(function (selectedValue) { return selectedValue !== name; }); // cannot use .splice(), it mutates return nextRefinement; } function _refine$6(props, searchState, nextRefinement, context) { var id = getId$9(props); // Setting the value to an empty string ensures that it is persisted in // the URL as an empty value. // This is necessary in the case where `defaultRefinement` contains one // item and we try to deselect it. `nextSelected` would be an empty array, // which would not be persisted to the URL. // {foo: ['bar']} => "foo[0]=bar" // {foo: []} => "" var nextValue = defineProperty$2({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$4); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, namespace$4 + '.' + getId$9(props)); } /** * connectRefinementList connector provides the logic to build a widget that will * give the user the ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), withSearchBox: propTypes.bool, searchForFacetValues: propTypes.bool, // @deprecated transformItems: propTypes.func }, defaultProps: { operator: 'or', showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$8(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, withSearchBox: withSearchBox }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue$4(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$4(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement$8(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, operator = props.operator, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters[addKey](attributeName); return getCurrentRefinement$8(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attributeName, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$9(props); var context = this.context; return { id: id, index: getIndex(this.context), items: getCurrentRefinement$8(props, searchState, context).length > 0 ? [{ attributeName: props.attributeName, label: props.attributeName + ': ', currentRefinement: getCurrentRefinement$8(props, searchState, context), value: function value(nextState) { return _refine$6(props, nextState, [], context); }, items: getCurrentRefinement$8(props, searchState, context).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$8(props, nextState, context).filter(function (other) { return other !== item; }); return _refine$6(props, searchState, nextSelectedItems, context); } }; }) }] : [] }; } }); /** * connectScrollTo connector provides the logic to build a widget that will * let the page scroll to a certain point. * @name connectScrollTo * @kind connector * @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget. * @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo * @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default) */ var connectScrollTo = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); if (!this._prevSearchState) { this._prevSearchState = {}; } /* Get the subpart of the state that interest us*/ if (hasMultipleIndex(this.context)) { var index = getIndex(this.context); searchState = searchState.indices ? searchState.indices[index] : {}; } /* if there is a change in the app that has been triggered by another element than "props.scrollOn (id) or the Configure widget, we need to keep track of the search state to know if there's a change in the app that was not triggered by the props.scrollOn (id) or the Configure widget. This is useful when using ScrollTo in combination of Pagination. As pagination can be change by every widget, we want to scroll only if it cames from the pagination widget itself. We also remove the configure key from the search state to do this comparaison because for now configure values are not present in the search state before a first refinement has been made and will false the results. See: https://github.com/algolia/react-instantsearch/issues/164 */ var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); var getId$10 = function getId(props) { return props.attributes[0]; }; var namespace$5 = 'hierarchicalMenu'; function _refine$7(props, searchState, nextRefinement, context) { var id = getId$10(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function transformValue$1(values) { return values.reduce(function (acc, item) { if (item.isRefined) { acc.push({ label: item.name, // If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label // If dealing with the first level, "value" is equal to the current label value: item.path }); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one if (item.data) { acc = acc.concat(transformValue$1(item.data, acc)); } } return acc; }, []); } /** * The breadcrumb component is s a type of secondary navigation scheme that * reveals the user’s location in a website or web application. * * @name connectBreadcrumb * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a Breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} {React.Element} [separator=' > '] - Specifies the level separator used in the data. * @propType {string} [rootURL=null] - The root element's URL (the originating page). * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display. */ var connectBreadcrumb = createConnector({ displayName: 'AlgoliaBreadcrumb', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, rootURL: propTypes.string, separator: propTypes.oneOfType([propTypes.string, propTypes.element]), transformItems: propTypes.func }, defaultProps: { rootURL: null, separator: ' > ' }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$10(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], canRefine: false }; } var values = results.getFacetValues(id); var items = values.data ? transformValue$1(values.data) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { canRefine: transformedItems.length > 0, items: transformedItems }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, this.context); } }); function getId$11() { return 'query'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$11(props); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine$8(props, searchState, nextRefinement, context) { var id = getId$11(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$6(props, searchState, context) { return cleanUpValue(searchState, context, getId$11()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query. * @name connectSearchBox * @kind connector * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the query to search for. */ var connectSearchBox = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState) { return { currentRefinement: getCurrentRefinement$9(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$9(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$11(props); var currentRefinement = getCurrentRefinement$9(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine$8(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); function getId$12() { return 'sortBy'; } function getCurrentRefinement$10(props, searchState, context) { var id = getId$12(props); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * The connectSortBy connector provides the logic to build a widget that will * display a list of indices. This allows a user to change how the hits are being sorted. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectSortBy = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$10(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$12(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$12()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$10(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$12() }; } }); /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ var connectStats = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function getId$13(props) { return props.attributeName; } var namespace$6 = 'toggle'; function getCurrentRefinement$11(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$6 + '.' + getId$13(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } function _refine$9(props, searchState, nextRefinement, context) { var id = getId$13(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function _cleanUp$7(props, searchState, context) { return cleanUpValue(searchState, context, namespace$6 + '.' + getId$13(props)); } /** * connectToggle connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization. * @name connectToggle * @kind connector * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName`. * @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {boolean} currentRefinement - the refinement currently applied */ var connectToggle = createConnector({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string, filter: propTypes.func, attributeName: propTypes.string, value: propTypes.any, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$11(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$9(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$7(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, value = props.value, filter = props.filter; var checked = getCurrentRefinement$11(props, searchState, this.context); if (checked) { if (attributeName) { searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$13(props); var checked = getCurrentRefinement$11(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (checked) { items.push({ label: props.label, currentRefinement: props.label, attributeName: props.attributeName, value: function value(nextState) { return _refine$9(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); /** * The `connectStateResults` connector provides a way to access the `searchState` and the `searchResults` * of InstantSearch. * For instance this connector allows you to create results/noResults or query/noQuery pages. * @name connectStateResults * @kind connector * @providedPropType {object} searchState - The search state of the instant search component. <br/><br/> See: [Search state structure](https://community.algolia.com/react-instantsearch/guide/Search_state.html) * @providedPropType {object} searchResults - The search results. <br/><br/> In case of multiple indices: if used under `<Index>`, results will be those of the corresponding index otherwise it'll be those of the root index See: [Search results structure](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults) * @providedPropType {object} allSearchResults - In case of multiple indices you can retrieve all the results * @providedPropType {string} error - If the search failed, the error will be logged here. * @providedPropType {boolean} searching - If there is a search in progress. * @providedPropType {boolean} searchingForFacetValues - If there is a search in a list in progress. * @providedPropType {boolean} props - component props. * @example * import React from 'react'; * * import { InstantSearch, Hits } from 'react-instantsearch/dom'; * import { connectStateResults } from 'react-instantsearch/connectors'; * * const Content = connectStateResults( * ({ searchState, searchResults }) => * searchResults && searchResults.nbHits !== 0 * ? <Hits/> * : <div> * No results has been found for {searchState.query} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Content /> * </InstantSearch> * ); * } */ var connectStateResults = createConnector({ displayName: 'AlgoliaStateResults', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); return { searchState: searchState, searchResults: results, allSearchResults: searchResults.results, searching: searchResults.searching, error: searchResults.error, searchingForFacetValues: searchResults.searchingForFacetValues, props: props }; } }); exports.connectConfigure = connectConfigure; exports.connectCurrentRefinements = connectCurrentRefinements; exports.connectHierarchicalMenu = connectHierarchicalMenu; exports.connectHighlight = connectHighlight; exports.connectHits = connectHits; exports.connectAutoComplete = connectAutoComplete; exports.connectHitsPerPage = connectHitsPerPage; exports.connectInfiniteHits = connectInfiniteHits; exports.connectMenu = connectMenu; exports.connectMultiRange = connectMultiRange; exports.connectPagination = connectPagination; exports.connectPoweredBy = connectPoweredBy; exports.connectRange = connectRange; exports.connectRefinementList = connectRefinementList; exports.connectScrollTo = connectScrollTo; exports.connectBreadcrumb = connectBreadcrumb; exports.connectSearchBox = connectSearchBox; exports.connectSortBy = connectSortBy; exports.connectStats = connectStats; exports.connectToggle = connectToggle; exports.connectStateResults = connectStateResults; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Connectors.js.map
ajax/libs/react-native-web/0.11.6/vendor/react-native/VirtualizedSectionList/index.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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 _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } /** * Copyright (c) 2015-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. * * * @format */ import React from 'react'; import View from '../../../exports/View'; import VirtualizedList from '../VirtualizedList'; import invariant from 'fbjs/lib/invariant'; /** * Right now this just flattens everything into one list and uses VirtualizedList under the * hood. The only operation that might not scale well is concatting the data arrays of all the * sections when new props are received, which should be plenty fast for up to ~10,000 items. */ var VirtualizedSectionList = /*#__PURE__*/ function (_React$PureComponent) { _inheritsLoose(VirtualizedSectionList, _React$PureComponent); var _proto = VirtualizedSectionList.prototype; _proto.scrollToLocation = function scrollToLocation(params) { var index = params.itemIndex + 1; for (var ii = 0; ii < params.sectionIndex; ii++) { index += this.props.sections[ii].data.length + 2; } var toIndexParams = _objectSpread({}, params, { index: index }); this._listRef.scrollToIndex(toIndexParams); }; _proto.getListRef = function getListRef() { return this._listRef; }; _proto._subExtractor = function _subExtractor(index) { var itemIndex = index; var defaultKeyExtractor = this.props.keyExtractor; for (var ii = 0; ii < this.props.sections.length; ii++) { var section = this.props.sections[ii]; var key = section.key || String(ii); itemIndex -= 1; // The section adds an item for the header if (itemIndex >= section.data.length + 1) { itemIndex -= section.data.length + 1; // The section adds an item for the footer. } else if (itemIndex === -1) { return { section: section, key: key + ':header', index: null, header: true, trailingSection: this.props.sections[ii + 1] }; } else if (itemIndex === section.data.length) { return { section: section, key: key + ':footer', index: null, header: false, trailingSection: this.props.sections[ii + 1] }; } else { var keyExtractor = section.keyExtractor || defaultKeyExtractor; return { section: section, key: key + ':' + keyExtractor(section.data[itemIndex], itemIndex), index: itemIndex, leadingItem: section.data[itemIndex - 1], leadingSection: this.props.sections[ii - 1], trailingItem: section.data[itemIndex + 1], trailingSection: this.props.sections[ii + 1] }; } } }; _proto._getSeparatorComponent = function _getSeparatorComponent(index, info) { info = info || this._subExtractor(index); if (!info) { return null; } var ItemSeparatorComponent = info.section.ItemSeparatorComponent || this.props.ItemSeparatorComponent; var SectionSeparatorComponent = this.props.SectionSeparatorComponent; var isLastItemInList = index === this.state.childProps.getItemCount() - 1; var isLastItemInSection = info.index === info.section.data.length - 1; if (SectionSeparatorComponent && isLastItemInSection) { return SectionSeparatorComponent; } if (ItemSeparatorComponent && !isLastItemInSection && !isLastItemInList) { return ItemSeparatorComponent; } return null; }; _proto._computeState = function _computeState(props) { var offset = props.ListHeaderComponent ? 1 : 0; var stickyHeaderIndices = []; var itemCount = props.sections.reduce(function (v, section) { stickyHeaderIndices.push(v + offset); return v + section.data.length + 2; // Add two for the section header and footer. }, 0); return { childProps: _objectSpread({}, props, { renderItem: this._renderItem, ItemSeparatorComponent: undefined, // Rendered with renderItem data: props.sections, getItemCount: function getItemCount() { return itemCount; }, getItem: getItem, keyExtractor: this._keyExtractor, onViewableItemsChanged: props.onViewableItemsChanged ? this._onViewableItemsChanged : undefined, stickyHeaderIndices: props.stickySectionHeadersEnabled ? stickyHeaderIndices : undefined }) }; }; function VirtualizedSectionList(props, context) { var _this; _this = _React$PureComponent.call(this, props, context) || this; _this._keyExtractor = function (item, index) { var info = _this._subExtractor(index); return info && info.key || String(index); }; _this._convertViewable = function (viewable) { invariant(viewable.index != null, 'Received a broken ViewToken'); var info = _this._subExtractor(viewable.index); if (!info) { return null; } var keyExtractor = info.section.keyExtractor || _this.props.keyExtractor; return _objectSpread({}, viewable, { index: info.index, /* $FlowFixMe(>=0.63.0 site=react_native_fb) This comment suppresses an * error found when Flow v0.63 was deployed. To see the error delete this * comment and run Flow. */ key: keyExtractor(viewable.item, info.index), section: info.section }); }; _this._onViewableItemsChanged = function (_ref) { var viewableItems = _ref.viewableItems, changed = _ref.changed; if (_this.props.onViewableItemsChanged) { _this.props.onViewableItemsChanged({ viewableItems: viewableItems.map(_this._convertViewable, _assertThisInitialized(_assertThisInitialized(_this))).filter(Boolean), changed: changed.map(_this._convertViewable, _assertThisInitialized(_assertThisInitialized(_this))).filter(Boolean) }); } }; _this._renderItem = function (_ref2) { var item = _ref2.item, index = _ref2.index; var info = _this._subExtractor(index); if (!info) { return null; } var infoIndex = info.index; if (infoIndex == null) { var section = info.section; if (info.header === true) { var renderSectionHeader = _this.props.renderSectionHeader; return renderSectionHeader ? renderSectionHeader({ section: section }) : null; } else { var renderSectionFooter = _this.props.renderSectionFooter; return renderSectionFooter ? renderSectionFooter({ section: section }) : null; } } else { var renderItem = info.section.renderItem || _this.props.renderItem; var SeparatorComponent = _this._getSeparatorComponent(index, info); invariant(renderItem, 'no renderItem!'); return React.createElement(ItemWithSeparator, { SeparatorComponent: SeparatorComponent, LeadingSeparatorComponent: infoIndex === 0 ? _this.props.SectionSeparatorComponent : undefined, cellKey: info.key, index: infoIndex, item: item, leadingItem: info.leadingItem, leadingSection: info.leadingSection, onUpdateSeparator: _this._onUpdateSeparator, prevCellKey: (_this._subExtractor(index - 1) || {}).key, ref: function ref(_ref3) { _this._cellRefs[info.key] = _ref3; }, renderItem: renderItem, section: info.section, trailingItem: info.trailingItem, trailingSection: info.trailingSection }); } }; _this._onUpdateSeparator = function (key, newProps) { var ref = _this._cellRefs[key]; ref && ref.updateSeparatorProps(newProps); }; _this._cellRefs = {}; _this._captureRef = function (ref) { /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment * suppresses an error when upgrading Flow's support for React. To see the * error delete this comment and run Flow. */ _this._listRef = ref; }; _this.state = _this._computeState(props); return _this; } _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) { this.setState(this._computeState(nextProps)); }; _proto.render = function render() { return React.createElement(VirtualizedList, _extends({}, this.state.childProps, { ref: this._captureRef })); }; return VirtualizedSectionList; }(React.PureComponent); VirtualizedSectionList.defaultProps = _objectSpread({}, VirtualizedList.defaultProps, { data: [] }); var ItemWithSeparator = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(ItemWithSeparator, _React$Component); function ItemWithSeparator() { var _this2; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this2 = _React$Component.call.apply(_React$Component, [this].concat(args)) || this; _this2.state = { separatorProps: { highlighted: false, leadingItem: _this2.props.item, leadingSection: _this2.props.leadingSection, section: _this2.props.section, trailingItem: _this2.props.trailingItem, trailingSection: _this2.props.trailingSection }, leadingSeparatorProps: { highlighted: false, leadingItem: _this2.props.leadingItem, leadingSection: _this2.props.leadingSection, section: _this2.props.section, trailingItem: _this2.props.item, trailingSection: _this2.props.trailingSection } }; _this2._separators = { highlight: function highlight() { ['leading', 'trailing'].forEach(function (s) { return _this2._separators.updateProps(s, { highlighted: true }); }); }, unhighlight: function unhighlight() { ['leading', 'trailing'].forEach(function (s) { return _this2._separators.updateProps(s, { highlighted: false }); }); }, updateProps: function updateProps(select, newProps) { var _this2$props = _this2.props, LeadingSeparatorComponent = _this2$props.LeadingSeparatorComponent, cellKey = _this2$props.cellKey, prevCellKey = _this2$props.prevCellKey; if (select === 'leading' && LeadingSeparatorComponent) { _this2.setState(function (state) { return { leadingSeparatorProps: _objectSpread({}, state.leadingSeparatorProps, newProps) }; }); } else { _this2.props.onUpdateSeparator(select === 'leading' && prevCellKey || cellKey, newProps); } } }; return _this2; } var _proto2 = ItemWithSeparator.prototype; _proto2.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(props) { var _this3 = this; this.setState(function (state) { return { separatorProps: _objectSpread({}, _this3.state.separatorProps, { leadingItem: props.item, leadingSection: props.leadingSection, section: props.section, trailingItem: props.trailingItem, trailingSection: props.trailingSection }), leadingSeparatorProps: _objectSpread({}, _this3.state.leadingSeparatorProps, { leadingItem: props.leadingItem, leadingSection: props.leadingSection, section: props.section, trailingItem: props.item, trailingSection: props.trailingSection }) }; }); }; _proto2.updateSeparatorProps = function updateSeparatorProps(newProps) { this.setState(function (state) { return { separatorProps: _objectSpread({}, state.separatorProps, newProps) }; }); }; _proto2.render = function render() { var _this$props = this.props, LeadingSeparatorComponent = _this$props.LeadingSeparatorComponent, SeparatorComponent = _this$props.SeparatorComponent, item = _this$props.item, index = _this$props.index, section = _this$props.section; var element = this.props.renderItem({ item: item, index: index, section: section, separators: this._separators }); var leadingSeparator = LeadingSeparatorComponent && React.createElement(LeadingSeparatorComponent, this.state.leadingSeparatorProps); var separator = SeparatorComponent && React.createElement(SeparatorComponent, this.state.separatorProps); return leadingSeparator || separator ? React.createElement(View, null, leadingSeparator, element, separator) : element; }; return ItemWithSeparator; }(React.Component); function getItem(sections, index) { if (!sections) { return null; } var itemIdx = index - 1; for (var ii = 0; ii < sections.length; ii++) { if (itemIdx === -1 || itemIdx === sections[ii].data.length) { // We intend for there to be overflow by one on both ends of the list. // This will be for headers and footers. When returning a header or footer // item the section itself is the item. return sections[ii]; } else if (itemIdx < sections[ii].data.length) { // If we are in the bounds of the list's data then return the item. return sections[ii].data[itemIdx]; } else { itemIdx -= sections[ii].data.length + 2; // Add two for the header and footer } } return null; } export default VirtualizedSectionList;
ajax/libs/primereact/6.6.0-rc.1/dataview/dataview.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Paginator } from 'primereact/paginator'; import { classNames, Ripple, ObjectUtils } from 'primereact/core'; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var DataViewLayoutOptions = /*#__PURE__*/function (_Component) { _inherits(DataViewLayoutOptions, _Component); var _super = _createSuper(DataViewLayoutOptions); function DataViewLayoutOptions(props) { var _this; _classCallCheck(this, DataViewLayoutOptions); _this = _super.call(this, props); _this.changeLayout = _this.changeLayout.bind(_assertThisInitialized(_this)); return _this; } _createClass(DataViewLayoutOptions, [{ key: "changeLayout", value: function changeLayout(event, layoutMode) { this.props.onChange({ originalEvent: event, value: layoutMode }); event.preventDefault(); } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-dataview-layout-options p-selectbutton p-buttonset', this.props.className); var buttonListClass = classNames('p-button p-button-icon-only', { 'p-highlight': this.props.layout === 'list' }); var buttonGridClass = classNames('p-button p-button-icon-only', { 'p-highlight': this.props.layout === 'grid' }); return /*#__PURE__*/React.createElement("div", { id: this.props.id, style: this.props.style, className: className }, /*#__PURE__*/React.createElement("button", { type: "button", className: buttonListClass, onClick: function onClick(event) { return _this2.changeLayout(event, 'list'); } }, /*#__PURE__*/React.createElement("i", { className: "pi pi-bars" }), /*#__PURE__*/React.createElement(Ripple, null)), /*#__PURE__*/React.createElement("button", { type: "button", className: buttonGridClass, onClick: function onClick(event) { return _this2.changeLayout(event, 'grid'); } }, /*#__PURE__*/React.createElement("i", { className: "pi pi-th-large" }), /*#__PURE__*/React.createElement(Ripple, null))); } }]); return DataViewLayoutOptions; }(Component); _defineProperty(DataViewLayoutOptions, "defaultProps", { id: null, style: null, className: null, layout: null, onChange: null }); var DataViewItem = /*#__PURE__*/function (_Component2) { _inherits(DataViewItem, _Component2); var _super2 = _createSuper(DataViewItem); function DataViewItem() { _classCallCheck(this, DataViewItem); return _super2.apply(this, arguments); } _createClass(DataViewItem, [{ key: "render", value: function render() { return this.props.template(this.props.item, this.props.layout); } }]); return DataViewItem; }(Component); _defineProperty(DataViewItem, "defaultProps", { template: null, item: null, layout: null }); var DataView = /*#__PURE__*/function (_Component3) { _inherits(DataView, _Component3); var _super3 = _createSuper(DataView); function DataView(props) { var _this3; _classCallCheck(this, DataView); _this3 = _super3.call(this, props); if (!_this3.props.onPage) { _this3.state = { first: _this3.props.first, rows: _this3.props.rows }; } _this3.sortChange = false; _this3.onPageChange = _this3.onPageChange.bind(_assertThisInitialized(_this3)); return _this3; } _createClass(DataView, [{ key: "getItemRenderKey", value: function getItemRenderKey(value) { return this.props.dataKey ? ObjectUtils.resolveFieldData(value, this.props.dataKey) : null; } }, { key: "getTotalRecords", value: function getTotalRecords() { if (this.props.totalRecords) return this.props.totalRecords;else return this.props.value ? this.props.value.length : 0; } }, { key: "createPaginator", value: function createPaginator(position) { var className = classNames('p-paginator-' + position, this.props.paginatorClassName); var first = this.props.onPage ? this.props.first : this.state.first; var rows = this.props.onPage ? this.props.rows : this.state.rows; var totalRecords = this.getTotalRecords(); return /*#__PURE__*/React.createElement(Paginator, { first: first, rows: rows, pageLinkSize: this.props.pageLinkSize, className: className, onPageChange: this.onPageChange, template: this.props.paginatorTemplate, totalRecords: totalRecords, rowsPerPageOptions: this.props.rowsPerPageOptions, currentPageReportTemplate: this.props.currentPageReportTemplate, leftContent: this.props.paginatorLeft, rightContent: this.props.paginatorRight, alwaysShow: this.props.alwaysShowPaginator, dropdownAppendTo: this.props.paginatorDropdownAppendTo }); } }, { key: "onPageChange", value: function onPageChange(event) { if (this.props.onPage) { this.props.onPage(event); } else { this.setState({ first: event.first, rows: event.rows }); } } }, { key: "isEmpty", value: function isEmpty() { return !this.props.value || this.props.value.length === 0; } }, { key: "sort", value: function sort() { var _this4 = this; if (this.props.value) { var value = _toConsumableArray(this.props.value); value.sort(function (data1, data2) { var value1 = ObjectUtils.resolveFieldData(data1, _this4.props.sortField); var value2 = ObjectUtils.resolveFieldData(data2, _this4.props.sortField); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return _this4.props.sortOrder * result; }); return value; } else { return null; } } }, { key: "renderLoader", value: function renderLoader() { if (this.props.loading) { var iconClassName = classNames('p-dataview-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-dataview-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: iconClassName })); } return null; } }, { key: "renderTopPaginator", value: function renderTopPaginator() { if (this.props.paginator && (this.props.paginatorPosition !== 'bottom' || this.props.paginatorPosition === 'both')) { return this.createPaginator('top'); } return null; } }, { key: "renderBottomPaginator", value: function renderBottomPaginator() { if (this.props.paginator && (this.props.paginatorPosition !== 'top' || this.props.paginatorPosition === 'both')) { return this.createPaginator('bottom'); } return null; } }, { key: "renderEmptyMessage", value: function renderEmptyMessage() { if (!this.props.loading) { return /*#__PURE__*/React.createElement("div", { className: "p-col-12 p-dataview-emptymessage" }, this.props.emptyMessage); } return null; } }, { key: "renderHeader", value: function renderHeader() { if (this.props.header) { return /*#__PURE__*/React.createElement("div", { className: "p-dataview-header" }, this.props.header); } return null; } }, { key: "renderFooter", value: function renderFooter() { if (this.props.footer) { return /*#__PURE__*/React.createElement("div", { className: "p-dataview-footer" }, " ", this.props.footer); } return null; } }, { key: "renderItems", value: function renderItems(value) { var _this5 = this; if (value && value.length) { if (this.props.paginator) { var rows = this.props.onPage ? this.props.rows : this.state.rows; var first = this.props.lazy ? 0 : this.props.onPage ? this.props.first : this.state.first; var totalRecords = this.getTotalRecords(); var last = Math.min(rows + first, totalRecords); var items = []; for (var i = first; i < last; i++) { var val = value[i]; val && items.push( /*#__PURE__*/React.createElement(DataViewItem, { key: this.getItemRenderKey(value) || i, template: this.props.itemTemplate, layout: this.props.layout, item: val })); } return items; } else { return value.map(function (item, index) { return /*#__PURE__*/React.createElement(DataViewItem, { key: _this5.getItemRenderKey(item) || index, template: _this5.props.itemTemplate, layout: _this5.props.layout, item: item }); }); } } else { return this.renderEmptyMessage(); } } }, { key: "renderContent", value: function renderContent(value) { var items = this.renderItems(value); return /*#__PURE__*/React.createElement("div", { className: "p-dataview-content" }, /*#__PURE__*/React.createElement("div", { className: "p-grid p-nogutter" }, items)); } }, { key: "processData", value: function processData() { var data = this.props.value; if (data && data.length) { if (this.props.sortField) { data = this.sort(); } } return data; } }, { key: "render", value: function render() { var value = this.processData(); var className = classNames('p-dataview p-component', { 'p-dataview-list': this.props.layout === 'list', 'p-dataview-grid': this.props.layout === 'grid', 'p-dataview-loading': this.props.loading }, this.props.className); var loader = this.renderLoader(); var topPaginator = this.renderTopPaginator(); var bottomPaginator = this.renderBottomPaginator(); var header = this.renderHeader(); var footer = this.renderFooter(); var content = this.renderContent(value); return /*#__PURE__*/React.createElement("div", { id: this.props.id, style: this.props.style, className: className }, loader, header, topPaginator, content, bottomPaginator, footer); } }]); return DataView; }(Component); _defineProperty(DataView, "defaultProps", { id: null, header: null, footer: null, value: null, layout: 'list', dataKey: null, rows: null, first: 0, totalRecords: null, paginator: false, paginatorPosition: 'bottom', alwaysShowPaginator: true, paginatorClassName: null, paginatorTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', paginatorLeft: null, paginatorRight: null, paginatorDropdownAppendTo: null, pageLinkSize: 5, rowsPerPageOptions: null, currentPageReportTemplate: '({currentPage} of {totalPages})', emptyMessage: 'No records found', sortField: null, sortOrder: null, style: null, className: null, lazy: false, loading: false, loadingIcon: 'pi pi-spinner', itemTemplate: null, onPage: null }); export { DataView, DataViewLayoutOptions };
ajax/libs/material-ui/4.9.3/esm/internal/svg-icons/MoreHoriz.js
cdnjs/cdnjs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" }), 'MoreHoriz');
ajax/libs/material-ui/4.9.3/esm/Modal/TrapFocus.js
cdnjs/cdnjs
/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */ import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import ownerDocument from '../utils/ownerDocument'; import useForkRef from '../utils/useForkRef'; /** * @ignore - internal component. */ function TrapFocus(props) { var children = props.children, _props$disableAutoFoc = props.disableAutoFocus, disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc, _props$disableEnforce = props.disableEnforceFocus, disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce, _props$disableRestore = props.disableRestoreFocus, disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore, getDoc = props.getDoc, isEnabled = props.isEnabled, open = props.open; var ignoreNextEnforceFocus = React.useRef(); var sentinelStart = React.useRef(null); var sentinelEnd = React.useRef(null); var nodeToRestore = React.useRef(); var rootRef = React.useRef(null); // can be removed once we drop support for non ref forwarding class components var handleOwnRef = React.useCallback(function (instance) { // #StrictMode ready rootRef.current = ReactDOM.findDOMNode(instance); }, []); var handleRef = useForkRef(children.ref, handleOwnRef); // ⚠️ You may rely on React.useMemo as a performance optimization, not as a semantic guarantee. // https://reactjs.org/docs/hooks-reference.html#usememo React.useMemo(function () { if (!open || typeof window === 'undefined') { return; } nodeToRestore.current = getDoc().activeElement; }, [open]); // eslint-disable-line react-hooks/exhaustive-deps React.useEffect(function () { if (!open) { return; } var doc = ownerDocument(rootRef.current); // We might render an empty child. if (!disableAutoFocus && rootRef.current && !rootRef.current.contains(doc.activeElement)) { if (!rootRef.current.hasAttribute('tabIndex')) { if (process.env.NODE_ENV !== 'production') { console.error(['Material-UI: the modal content node does not accept focus.', 'For the benefit of assistive technologies, ' + 'the tabIndex of the node is being set to "-1".'].join('\n')); } rootRef.current.setAttribute('tabIndex', -1); } rootRef.current.focus(); } var contain = function contain() { if (disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) { ignoreNextEnforceFocus.current = false; return; } if (rootRef.current && !rootRef.current.contains(doc.activeElement)) { rootRef.current.focus(); } }; var loopFocus = function loopFocus(event) { // 9 = Tab if (disableEnforceFocus || !isEnabled() || event.keyCode !== 9) { return; } // Make sure the next tab starts from the right place. if (doc.activeElement === rootRef.current) { // We need to ignore the next contain as // it will try to move the focus back to the rootRef element. ignoreNextEnforceFocus.current = true; if (event.shiftKey) { sentinelEnd.current.focus(); } else { sentinelStart.current.focus(); } } }; doc.addEventListener('focus', contain, true); doc.addEventListener('keydown', loopFocus, true); // With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area // e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561. // // The whatwg spec defines how the browser should behave but does not explicitly mention any events: // https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule. var interval = setInterval(function () { contain(); }, 50); return function () { clearInterval(interval); doc.removeEventListener('focus', contain, true); doc.removeEventListener('keydown', loopFocus, true); // restoreLastFocus() if (!disableRestoreFocus) { // In IE 11 it is possible for document.activeElement to be null resulting // in nodeToRestore.current being null. // Not all elements in IE 11 have a focus method. // Once IE 11 support is dropped the focus() call can be unconditional. if (nodeToRestore.current && nodeToRestore.current.focus) { nodeToRestore.current.focus(); } nodeToRestore.current = null; } }; }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open]); return React.createElement(React.Fragment, null, React.createElement("div", { tabIndex: 0, ref: sentinelStart, "data-test": "sentinelStart" }), React.cloneElement(children, { ref: handleRef }), React.createElement("div", { tabIndex: 0, ref: sentinelEnd, "data-test": "sentinelEnd" })); } process.env.NODE_ENV !== "production" ? TrapFocus.propTypes = { /** * A single child content element. */ children: PropTypes.element.isRequired, /** * If `true`, the modal will not automatically shift focus to itself when it opens, and * replace it to the last focused element when it closes. * This also works correctly with any modal children that have the `disableAutoFocus` prop. * * Generally this should never be set to `true` as it makes the modal less * accessible to assistive technologies, like screen readers. */ disableAutoFocus: PropTypes.bool, /** * If `true`, the modal will not prevent focus from leaving the modal while open. * * Generally this should never be set to `true` as it makes the modal less * accessible to assistive technologies, like screen readers. */ disableEnforceFocus: PropTypes.bool, /** * If `true`, the modal will not restore focus to previously focused element once * modal is hidden. */ disableRestoreFocus: PropTypes.bool, /** * Return the document to consider. * We use it to implement the restore focus between different browser documents. */ getDoc: PropTypes.func.isRequired, /** * Do we still want to enforce the focus? * This prop helps nesting TrapFocus elements. */ isEnabled: PropTypes.func.isRequired, /** * If `true`, the modal is open. */ open: PropTypes.bool.isRequired } : void 0; /* In the future, we should be able to replace TrapFocus with: https://github.com/facebook/react/blob/master/packages/react-events/docs/FocusScope.md ```jsx import FocusScope from 'react-dom/FocusScope'; function TrapFocus(props) { const { children disableAutoFocus = false, disableEnforceFocus = false, disableRestoreFocus = false, open, } = props; if (!open) { return children; } return ( <FocusScope autoFocus={!disableAutoFocus} contain={!disableEnforceFocus} restoreFocus={!disableRestoreFocus} > {children} </FocusScope> ); } ``` */ export default TrapFocus;
ajax/libs/react-native-web/0.15.4/exports/YellowBox/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import React from 'react'; import UnimplementedView from '../../modules/UnimplementedView'; function YellowBox(props) { return ( /*#__PURE__*/ React.createElement(UnimplementedView, props) ); } YellowBox.ignoreWarnings = function () {}; export default YellowBox;
ajax/libs/material-ui/4.11.4/esm/utils/createSvgIcon.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import SvgIcon from '../SvgIcon'; /** * Private module reserved for @material-ui/x packages. */ export default function createSvgIcon(path, displayName) { var Component = function Component(props, ref) { return /*#__PURE__*/React.createElement(SvgIcon, _extends({ ref: ref }, props), path); }; if (process.env.NODE_ENV !== 'production') { // Need to set `displayName` on the inner component for React.memo. // React prior to 16.14 ignores `displayName` on the wrapper. Component.displayName = "".concat(displayName, "Icon"); } Component.muiName = SvgIcon.muiName; return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component)); }
ajax/libs/react-native-web/0.13.5/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AppContainer from './AppContainer'; import invariant from 'fbjs/lib/invariant'; import render, { hydrate } from '../render'; import styleResolver from '../StyleSheet/styleResolver'; import React from 'react'; export default function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? hydrate : render; invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn(React.createElement(AppContainer, { rootTag: rootTag, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)), rootTag, callback); } export function getApplication(RootComponent, initialProps, WrapperComponent) { var element = React.createElement(AppContainer, { rootTag: {}, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = styleResolver.getStyleSheet(); return React.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
ajax/libs/material-ui/5.0.0-alpha.4/RootRef/RootRef.js
cdnjs/cdnjs
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var React = _interopRequireWildcard(require("react")); var ReactDOM = _interopRequireWildcard(require("react-dom")); var _propTypes = _interopRequireDefault(require("prop-types")); var _utils = require("@material-ui/utils"); var _setRef = _interopRequireDefault(require("../utils/setRef")); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * ⚠️⚠️⚠️ * If you want the DOM element of a Material-UI component check out * [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element) * first. * * This component uses `findDOMNode` which is deprecated in React.StrictMode. * * Helper component to allow attaching a ref to a * wrapped element to access the underlying DOM element. * * It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801. * For example: * ```jsx * import React from 'react'; * import RootRef from '@material-ui/core/RootRef'; * * function MyComponent() { * const domRef = React.useRef(); * * React.useEffect(() => { * console.log(domRef.current); // DOM node * }, []); * * return ( * <RootRef rootRef={domRef}> * <SomeChildComponent /> * </RootRef> * ); * } * ``` */ var RootRef = /*#__PURE__*/function (_React$Component) { (0, _inherits2.default)(RootRef, _React$Component); var _super = _createSuper(RootRef); function RootRef() { (0, _classCallCheck2.default)(this, RootRef); return _super.apply(this, arguments); } (0, _createClass2.default)(RootRef, [{ key: "componentDidMount", value: function componentDidMount() { this.ref = ReactDOM.findDOMNode(this); (0, _setRef.default)(this.props.rootRef, this.ref); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var ref = ReactDOM.findDOMNode(this); if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) { if (prevProps.rootRef !== this.props.rootRef) { (0, _setRef.default)(prevProps.rootRef, null); } this.ref = ref; (0, _setRef.default)(this.props.rootRef, this.ref); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.ref = null; (0, _setRef.default)(this.props.rootRef, null); } }, { key: "render", value: function render() { return this.props.children; } }]); return RootRef; }(React.Component); process.env.NODE_ENV !== "production" ? RootRef.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The wrapped element. */ children: _propTypes.default.element.isRequired, /** * A ref that points to the first DOM node of the wrapped element. */ rootRef: _utils.refType.isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? RootRef.propTypes = (0, _utils.exactProp)(RootRef.propTypes) : void 0; } var _default = RootRef; exports.default = _default;
ajax/libs/material-ui/4.9.4/es/Backdrop/Backdrop.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Fade from '../Fade'; export const styles = { /* Styles applied to the root element. */ root: { // Improve scrollable dialog support. zIndex: -1, position: 'fixed', display: 'flex', alignItems: 'center', justifyContent: 'center', right: 0, bottom: 0, top: 0, left: 0, backgroundColor: 'rgba(0, 0, 0, 0.5)', WebkitTapHighlightColor: 'transparent' }, /* Styles applied to the root element if `invisible={true}`. */ invisible: { backgroundColor: 'transparent' } }; const Backdrop = React.forwardRef(function Backdrop(props, ref) { const { children, classes, className, invisible = false, open, transitionDuration } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "invisible", "open", "transitionDuration"]); return React.createElement(Fade, _extends({ in: open, timeout: transitionDuration }, other), React.createElement("div", { className: clsx(classes.root, className, invisible && classes.invisible), "aria-hidden": true, ref: ref }, children)); }); process.env.NODE_ENV !== "production" ? Backdrop.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * If `true`, the backdrop is invisible. * It can be used when rendering a popover or a custom select component. */ invisible: PropTypes.bool, /** * If `true`, the backdrop is open. */ open: PropTypes.bool.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number })]) } : void 0; export default withStyles(styles, { name: 'MuiBackdrop' })(Backdrop);
ajax/libs/react-native-web/0.14.10/exports/YellowBox/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import React from 'react'; import UnimplementedView from '../../modules/UnimplementedView'; function YellowBox(props) { return React.createElement(UnimplementedView, props); } YellowBox.ignoreWarnings = function () {}; export default YellowBox;
ajax/libs/primereact/7.2.0/selectbutton/selectbutton.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames, ObjectUtils } from 'primereact/utils'; import { Ripple } from 'primereact/ripple'; import { tip } from 'primereact/tooltip'; function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var SelectButtonItem = /*#__PURE__*/function (_Component) { _inherits(SelectButtonItem, _Component); var _super = _createSuper$1(SelectButtonItem); function SelectButtonItem(props) { var _this; _classCallCheck(this, SelectButtonItem); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(SelectButtonItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { var keyCode = event.which; if (keyCode === 32 || keyCode === 13) { //space and enter this.onClick(event); event.preventDefault(); } } }, { key: "renderContent", value: function renderContent() { if (this.props.template) { return this.props.template(this.props.option); } else { return /*#__PURE__*/React.createElement("span", { className: "p-button-label p-c" }, this.props.label); } } }, { key: "render", value: function render() { var className = classNames('p-button p-component', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }, this.props.className); var content = this.renderContent(); return /*#__PURE__*/React.createElement("div", { className: className, role: "button", "aria-label": this.props.label, "aria-pressed": this.props.selected, "aria-labelledby": this.props.ariaLabelledBy, onClick: this.onClick, onKeyDown: this.onKeyDown, tabIndex: this.props.tabIndex, onFocus: this.onFocus, onBlur: this.onBlur }, content, !this.props.disabled && /*#__PURE__*/React.createElement(Ripple, null)); } }]); return SelectButtonItem; }(Component); _defineProperty(SelectButtonItem, "defaultProps", { option: null, label: null, className: null, selected: null, tabIndex: null, ariaLabelledBy: null, template: null, onClick: null }); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var SelectButton = /*#__PURE__*/function (_Component) { _inherits(SelectButton, _Component); var _super = _createSuper(SelectButton); function SelectButton(props) { var _this; _classCallCheck(this, SelectButton); _this = _super.call(this, props); _this.onOptionClick = _this.onOptionClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(SelectButton, [{ key: "onOptionClick", value: function onOptionClick(event) { var _this2 = this; if (this.props.disabled || this.isOptionDisabled(event.option)) { return; } var selected = this.isSelected(event.option); if (selected && !this.props.unselectable) { return; } var optionValue = this.getOptionValue(event.option); var newValue; if (this.props.multiple) { var currentValue = this.props.value ? _toConsumableArray(this.props.value) : []; if (selected) newValue = currentValue.filter(function (val) { return !ObjectUtils.equals(val, optionValue, _this2.props.dataKey); });else newValue = [].concat(_toConsumableArray(currentValue), [optionValue]); } else { if (selected) newValue = null;else newValue = optionValue; } if (this.props.onChange) { this.props.onChange({ originalEvent: event.originalEvent, value: newValue, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: newValue } }); } } }, { key: "getOptionLabel", value: function getOptionLabel(option) { return this.props.optionLabel ? ObjectUtils.resolveFieldData(option, this.props.optionLabel) : option && option['label'] !== undefined ? option['label'] : option; } }, { key: "getOptionValue", value: function getOptionValue(option) { return this.props.optionValue ? ObjectUtils.resolveFieldData(option, this.props.optionValue) : option && option['value'] !== undefined ? option['value'] : option; } }, { key: "isOptionDisabled", value: function isOptionDisabled(option) { if (this.props.optionDisabled) { return ObjectUtils.isFunction(this.props.optionDisabled) ? this.props.optionDisabled(option) : ObjectUtils.resolveFieldData(option, this.props.optionDisabled); } return option && option['disabled'] !== undefined ? option['disabled'] : false; } }, { key: "isSelected", value: function isSelected(option) { var selected = false; var optionValue = this.getOptionValue(option); if (this.props.multiple) { if (this.props.value && this.props.value.length) { var _iterator = _createForOfIteratorHelper(this.props.value), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var val = _step.value; if (ObjectUtils.equals(val, optionValue, this.props.dataKey)) { selected = true; break; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } } else { selected = ObjectUtils.equals(this.props.value, optionValue, this.props.dataKey); } return selected; } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = tip({ target: this.element, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "renderItems", value: function renderItems() { var _this3 = this; if (this.props.options && this.props.options.length) { return this.props.options.map(function (option, index) { var isDisabled = _this3.props.disabled || _this3.isOptionDisabled(option); var optionLabel = _this3.getOptionLabel(option); var tabIndex = isDisabled ? null : 0; return /*#__PURE__*/React.createElement(SelectButtonItem, { key: "".concat(optionLabel, "_").concat(index), label: optionLabel, className: option.className, option: option, onClick: _this3.onOptionClick, template: _this3.props.itemTemplate, selected: _this3.isSelected(option), tabIndex: tabIndex, disabled: isDisabled, ariaLabelledBy: _this3.props.ariaLabelledBy }); }); } return null; } }, { key: "render", value: function render() { var _this4 = this; var className = classNames('p-selectbutton p-buttonset p-component', this.props.className); var items = this.renderItems(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, ref: function ref(el) { return _this4.element = el; }, className: className, style: this.props.style, role: "group" }, items); } }]); return SelectButton; }(Component); _defineProperty(SelectButton, "defaultProps", { id: null, value: null, options: null, optionLabel: null, optionValue: null, optionDisabled: null, tabIndex: null, multiple: false, unselectable: true, disabled: false, style: null, className: null, dataKey: null, tooltip: null, tooltipOptions: null, ariaLabelledBy: null, itemTemplate: null, onChange: null }); export { SelectButton };
ajax/libs/react-native-web/0.11.5/exports/ScrollView/ScrollViewBase.js
cdnjs/cdnjs
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import debounce from 'debounce'; import StyleSheet from '../StyleSheet'; import View from '../View'; import ViewPropTypes from '../ViewPropTypes'; import React, { Component } from 'react'; import { bool, func, number } from 'prop-types'; var normalizeScrollEvent = function normalizeScrollEvent(e) { return { nativeEvent: { contentOffset: { get x() { return e.target.scrollLeft; }, get y() { return e.target.scrollTop; } }, contentSize: { get height() { return e.target.scrollHeight; }, get width() { return e.target.scrollWidth; } }, layoutMeasurement: { get height() { return e.target.offsetHeight; }, get width() { return e.target.offsetWidth; } } }, timeStamp: Date.now() }; }; /** * Encapsulates the Web-specific scroll throttling and disabling logic */ var ScrollViewBase = /*#__PURE__*/ function (_Component) { _inheritsLoose(ScrollViewBase, _Component); function ScrollViewBase() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _Component.call.apply(_Component, [this].concat(args)) || this; _this._debouncedOnScrollEnd = debounce(_this._handleScrollEnd, 100); _this._state = { isScrolling: false, scrollLastTick: 0 }; _this._createPreventableScrollHandler = function (handler) { return function (e) { if (_this.props.scrollEnabled) { if (handler) { handler(e); } } else { // To disable scrolling in all browsers except Chrome e.preventDefault(); } }; }; _this._handleScroll = function (e) { e.persist(); e.stopPropagation(); var scrollEventThrottle = _this.props.scrollEventThrottle; // A scroll happened, so the scroll bumps the debounce. _this._debouncedOnScrollEnd(e); if (_this._state.isScrolling) { // Scroll last tick may have changed, check if we need to notify if (_this._shouldEmitScrollEvent(_this._state.scrollLastTick, scrollEventThrottle)) { _this._handleScrollTick(e); } } else { // Weren't scrolling, so we must have just started _this._handleScrollStart(e); } }; _this._setViewRef = function (element) { _this._viewRef = element; }; return _this; } var _proto = ScrollViewBase.prototype; _proto.setNativeProps = function setNativeProps(props) { if (this._viewRef) { this._viewRef.setNativeProps(props); } }; _proto.render = function render() { var _this$props = this.props, scrollEnabled = _this$props.scrollEnabled, style = _this$props.style, alwaysBounceHorizontal = _this$props.alwaysBounceHorizontal, alwaysBounceVertical = _this$props.alwaysBounceVertical, automaticallyAdjustContentInsets = _this$props.automaticallyAdjustContentInsets, bounces = _this$props.bounces, bouncesZoom = _this$props.bouncesZoom, canCancelContentTouches = _this$props.canCancelContentTouches, centerContent = _this$props.centerContent, contentInset = _this$props.contentInset, contentInsetAdjustmentBehavior = _this$props.contentInsetAdjustmentBehavior, contentOffset = _this$props.contentOffset, decelerationRate = _this$props.decelerationRate, directionalLockEnabled = _this$props.directionalLockEnabled, endFillColor = _this$props.endFillColor, indicatorStyle = _this$props.indicatorStyle, keyboardShouldPersistTaps = _this$props.keyboardShouldPersistTaps, maximumZoomScale = _this$props.maximumZoomScale, minimumZoomScale = _this$props.minimumZoomScale, onMomentumScrollBegin = _this$props.onMomentumScrollBegin, onMomentumScrollEnd = _this$props.onMomentumScrollEnd, onScrollBeginDrag = _this$props.onScrollBeginDrag, onScrollEndDrag = _this$props.onScrollEndDrag, overScrollMode = _this$props.overScrollMode, pinchGestureEnabled = _this$props.pinchGestureEnabled, removeClippedSubviews = _this$props.removeClippedSubviews, scrollEventThrottle = _this$props.scrollEventThrottle, scrollIndicatorInsets = _this$props.scrollIndicatorInsets, scrollPerfTag = _this$props.scrollPerfTag, scrollsToTop = _this$props.scrollsToTop, showsHorizontalScrollIndicator = _this$props.showsHorizontalScrollIndicator, showsVerticalScrollIndicator = _this$props.showsVerticalScrollIndicator, snapToInterval = _this$props.snapToInterval, snapToAlignment = _this$props.snapToAlignment, zoomScale = _this$props.zoomScale, other = _objectWithoutPropertiesLoose(_this$props, ["scrollEnabled", "style", "alwaysBounceHorizontal", "alwaysBounceVertical", "automaticallyAdjustContentInsets", "bounces", "bouncesZoom", "canCancelContentTouches", "centerContent", "contentInset", "contentInsetAdjustmentBehavior", "contentOffset", "decelerationRate", "directionalLockEnabled", "endFillColor", "indicatorStyle", "keyboardShouldPersistTaps", "maximumZoomScale", "minimumZoomScale", "onMomentumScrollBegin", "onMomentumScrollEnd", "onScrollBeginDrag", "onScrollEndDrag", "overScrollMode", "pinchGestureEnabled", "removeClippedSubviews", "scrollEventThrottle", "scrollIndicatorInsets", "scrollPerfTag", "scrollsToTop", "showsHorizontalScrollIndicator", "showsVerticalScrollIndicator", "snapToInterval", "snapToAlignment", "zoomScale"]); var hideScrollbar = showsHorizontalScrollIndicator === false || showsVerticalScrollIndicator === false; return React.createElement(View, _extends({}, other, { onScroll: this._handleScroll, onTouchMove: this._createPreventableScrollHandler(this.props.onTouchMove), onWheel: this._createPreventableScrollHandler(this.props.onWheel), ref: this._setViewRef, style: [style, !scrollEnabled && styles.scrollDisabled, hideScrollbar && styles.hideScrollbar] })); }; _proto._handleScrollStart = function _handleScrollStart(e) { this._state.isScrolling = true; this._state.scrollLastTick = Date.now(); }; _proto._handleScrollTick = function _handleScrollTick(e) { var onScroll = this.props.onScroll; this._state.scrollLastTick = Date.now(); if (onScroll) { onScroll(normalizeScrollEvent(e)); } }; _proto._handleScrollEnd = function _handleScrollEnd(e) { var onScroll = this.props.onScroll; this._state.isScrolling = false; if (onScroll) { onScroll(normalizeScrollEvent(e)); } }; _proto._shouldEmitScrollEvent = function _shouldEmitScrollEvent(lastTick, eventThrottle) { var timeSinceLastTick = Date.now() - lastTick; return eventThrottle > 0 && timeSinceLastTick >= eventThrottle; }; return ScrollViewBase; }(Component); // Chrome doesn't support e.preventDefault in this case; touch-action must be // used to disable scrolling. // https://developers.google.com/web/updates/2017/01/scrolling-intervention ScrollViewBase.defaultProps = { scrollEnabled: true, scrollEventThrottle: 0 }; export { ScrollViewBase as default }; ScrollViewBase.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, ViewPropTypes, { onMomentumScrollBegin: func, onMomentumScrollEnd: func, onScroll: func, onScrollBeginDrag: func, onScrollEndDrag: func, onTouchMove: func, onWheel: func, removeClippedSubviews: bool, scrollEnabled: bool, scrollEventThrottle: number, showsHorizontalScrollIndicator: bool, showsVerticalScrollIndicator: bool }) : {}; var styles = StyleSheet.create({ scrollDisabled: { touchAction: 'none' }, hideScrollbar: { scrollbarWidth: 'none' } });
ajax/libs/material-ui/4.9.4/es/TableSortLabel/TableSortLabel.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import ArrowDownwardIcon from '../internal/svg-icons/ArrowDownward'; import withStyles from '../styles/withStyles'; import ButtonBase from '../ButtonBase'; import capitalize from '../utils/capitalize'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { cursor: 'pointer', display: 'inline-flex', justifyContent: 'flex-start', flexDirection: 'inherit', alignItems: 'center', '&:focus': { color: theme.palette.text.secondary }, '&:hover': { color: theme.palette.text.secondary, '& $icon': { opacity: 0.5 } }, '&$active': { color: theme.palette.text.primary, // && instead of & is a workaround for https://github.com/cssinjs/jss/issues/1045 '&& $icon': { opacity: 1, color: theme.palette.text.secondary } } }, /* Pseudo-class applied to the root element if `active={true}`. */ active: {}, /* Styles applied to the icon component. */ icon: { fontSize: 18, marginRight: 4, marginLeft: 4, opacity: 0, transition: theme.transitions.create(['opacity', 'transform'], { duration: theme.transitions.duration.shorter }), userSelect: 'none' }, /* Styles applied to the icon component if `direction="desc"`. */ iconDirectionDesc: { transform: 'rotate(0deg)' }, /* Styles applied to the icon component if `direction="asc"`. */ iconDirectionAsc: { transform: 'rotate(180deg)' } }); /** * A button based label for placing inside `TableCell` for column sorting. */ const TableSortLabel = React.forwardRef(function TableSortLabel(props, ref) { const { active = false, children, classes, className, direction = 'asc', hideSortIcon = false, IconComponent = ArrowDownwardIcon } = props, other = _objectWithoutPropertiesLoose(props, ["active", "children", "classes", "className", "direction", "hideSortIcon", "IconComponent"]); return React.createElement(ButtonBase, _extends({ className: clsx(classes.root, className, active && classes.active), component: "span", disableRipple: true, ref: ref }, other), children, hideSortIcon && !active ? null : React.createElement(IconComponent, { className: clsx(classes.icon, classes[`iconDirection${capitalize(direction)}`]) })); }); process.env.NODE_ENV !== "production" ? TableSortLabel.propTypes = { /** * If `true`, the label will have the active styling (should be true for the sorted column). */ active: PropTypes.bool, /** * Label contents, the arrow will be appended automatically. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The current sort direction. */ direction: PropTypes.oneOf(['asc', 'desc']), /** * Hide sort icon when active is false. */ hideSortIcon: PropTypes.bool, /** * Sort icon to use. */ IconComponent: PropTypes.elementType } : void 0; export default withStyles(styles, { name: 'MuiTableSortLabel' })(TableSortLabel);
ajax/libs/react-native-web/0.13.15/vendor/react-native/Animated/createAnimatedComponent.js
cdnjs/cdnjs
/** * Copyright (c) 2015-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. * * * @format */ 'use strict'; function _extends() { _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; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } import { AnimatedEvent } from './AnimatedEvent'; import AnimatedProps from './nodes/AnimatedProps'; import React from 'react'; import invariant from 'fbjs/lib/invariant'; import mergeRefs from '../../../modules/mergeRefs'; function createAnimatedComponent(Component, defaultProps) { invariant(typeof Component !== 'function' || Component.prototype && Component.prototype.isReactComponent, '`createAnimatedComponent` does not support stateless functional components; ' + 'use a class component instead.'); var AnimatedComponent = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(AnimatedComponent, _React$Component); function AnimatedComponent(props) { var _this; _this = _React$Component.call(this, props) || this; _this._invokeAnimatedPropsCallbackOnMount = false; _this._eventDetachers = []; _this._animatedPropsCallback = function () { if (_this._component == null) { // AnimatedProps is created in will-mount because it's used in render. // But this callback may be invoked before mount in async mode, // In which case we should defer the setNativeProps() call. // React may throw away uncommitted work in async mode, // So a deferred call won't always be invoked. _this._invokeAnimatedPropsCallbackOnMount = true; } else if (AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY || typeof _this._component.setNativeProps !== 'function') { _this.forceUpdate(); } else if (!_this._propsAnimated.__isNative) { _this._component.setNativeProps(_this._propsAnimated.__getAnimatedValue()); } else { throw new Error('Attempting to run JS driven animation on animated ' + 'node that has been moved to "native" earlier by starting an ' + 'animation with `useNativeDriver: true`'); } }; _this._setComponentRef = mergeRefs(_this.props.forwardedRef, function (ref) { _this._prevComponent = _this._component; _this._component = ref; // TODO: Delete this in a future release. if (ref != null && ref.getNode == null) { ref.getNode = function () { var _ref$constructor$name; console.warn('%s: Calling `getNode()` on the ref of an Animated component ' + 'is no longer necessary. You can now directly use the ref ' + 'instead. This method will be removed in a future release.', (_ref$constructor$name = ref.constructor.name) !== null && _ref$constructor$name !== void 0 ? _ref$constructor$name : '<<anonymous>>'); return ref; }; } }); return _this; } var _proto = AnimatedComponent.prototype; _proto.componentWillUnmount = function componentWillUnmount() { this._propsAnimated && this._propsAnimated.__detach(); this._detachNativeEvents(); }; _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() { this._attachProps(this.props); }; _proto.componentDidMount = function componentDidMount() { if (this._invokeAnimatedPropsCallbackOnMount) { this._invokeAnimatedPropsCallbackOnMount = false; this._animatedPropsCallback(); } this._propsAnimated.setNativeView(this._component); this._attachNativeEvents(); }; _proto._attachNativeEvents = function _attachNativeEvents() { var _this2 = this; // Make sure to get the scrollable node for components that implement // `ScrollResponder.Mixin`. var scrollableNode = this._component && this._component.getScrollableNode ? this._component.getScrollableNode() : this._component; var _loop = function _loop(key) { var prop = _this2.props[key]; if (prop instanceof AnimatedEvent && prop.__isNative) { prop.__attach(scrollableNode, key); _this2._eventDetachers.push(function () { return prop.__detach(scrollableNode, key); }); } }; for (var key in this.props) { _loop(key); } }; _proto._detachNativeEvents = function _detachNativeEvents() { this._eventDetachers.forEach(function (remove) { return remove(); }); this._eventDetachers = []; } // The system is best designed when setNativeProps is implemented. It is // able to avoid re-rendering and directly set the attributes that changed. // However, setNativeProps can only be implemented on leaf native // components. If you want to animate a composite component, you need to // re-render it. In this case, we have a fallback that uses forceUpdate. ; _proto._attachProps = function _attachProps(nextProps) { var oldPropsAnimated = this._propsAnimated; this._propsAnimated = new AnimatedProps(nextProps, this._animatedPropsCallback); // When you call detach, it removes the element from the parent list // of children. If it goes to 0, then the parent also detaches itself // and so on. // An optimization is to attach the new elements and THEN detach the old // ones instead of detaching and THEN attaching. // This way the intermediate state isn't to go to 0 and trigger // this expensive recursive detaching to then re-attach everything on // the very next operation. oldPropsAnimated && oldPropsAnimated.__detach(); }; _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(newProps) { this._attachProps(newProps); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { if (this._component !== this._prevComponent) { this._propsAnimated.setNativeView(this._component); } if (this._component !== this._prevComponent || prevProps !== this.props) { this._detachNativeEvents(); this._attachNativeEvents(); } }; _proto.render = function render() { var props = this._propsAnimated.__getValue(); return React.createElement(Component, _extends({}, defaultProps, props, { ref: this._setComponentRef // The native driver updates views directly through the UI thread so we // have to make sure the view doesn't get optimized away because it cannot // go through the NativeViewHierarchyManager since it operates on the shadow // thread. , collapsable: false })); }; return AnimatedComponent; }(React.Component); AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY = false; var propTypes = Component.propTypes; return React.forwardRef(function AnimatedComponentWrapper(props, ref) { return React.createElement(AnimatedComponent, _extends({}, props, ref == null ? null : { forwardedRef: ref })); }); } export default createAnimatedComponent;
ajax/libs/react-native-web/0.12.0/exports/Text/index.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import applyLayout from '../../modules/applyLayout'; import applyNativeMethods from '../../modules/applyNativeMethods'; import createElement from '../createElement'; import css from '../StyleSheet/css'; import filterSupportedProps from '../View/filterSupportedProps'; import React from 'react'; import StyleSheet from '../StyleSheet'; import TextAncestorContext from './TextAncestorContext'; var Text = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Text, _React$Component); function Text() { return _React$Component.apply(this, arguments) || this; } var _proto = Text.prototype; _proto.renderText = function renderText(hasTextAncestor) { var _this$props = this.props, dir = _this$props.dir, forwardedRef = _this$props.forwardedRef, numberOfLines = _this$props.numberOfLines, onPress = _this$props.onPress, selectable = _this$props.selectable, style = _this$props.style; var supportedProps = filterSupportedProps(this.props); if (onPress) { supportedProps.accessible = true; supportedProps.onClick = this._createPressHandler(onPress); supportedProps.onKeyDown = this._createEnterHandler(onPress); } supportedProps.classList = [classes.text, hasTextAncestor === true && classes.textHasAncestor, numberOfLines === 1 && classes.textOneLine, numberOfLines != null && numberOfLines > 1 && classes.textMultiLine]; // allow browsers to automatically infer the language writing direction supportedProps.dir = dir !== undefined ? dir : 'auto'; supportedProps.ref = forwardedRef; supportedProps.style = [style, numberOfLines != null && numberOfLines > 1 && { WebkitLineClamp: numberOfLines }, selectable === false && styles.notSelectable, onPress && styles.pressable]; var component = hasTextAncestor ? 'span' : 'div'; return createElement(component, supportedProps); }; _proto.render = function render() { var _this = this; return React.createElement(TextAncestorContext.Consumer, null, function (hasTextAncestor) { var element = _this.renderText(hasTextAncestor); return hasTextAncestor ? element : React.createElement(TextAncestorContext.Provider, { value: true }, element); }); }; _proto._createEnterHandler = function _createEnterHandler(fn) { return function (e) { if (e.keyCode === 13) { fn && fn(e); } }; }; _proto._createPressHandler = function _createPressHandler(fn) { return function (e) { e.stopPropagation(); fn && fn(e); }; }; return Text; }(React.Component); Text.displayName = 'Text'; var classes = css.create({ text: { border: '0 solid black', boxSizing: 'border-box', color: 'black', display: 'inline', font: '14px System', margin: 0, padding: 0, whiteSpace: 'pre-wrap', wordWrap: 'break-word' }, textHasAncestor: { color: 'inherit', font: 'inherit', whiteSpace: 'inherit' }, textOneLine: { maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, // See #13 textMultiLine: { display: '-webkit-box', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', WebkitBoxOrient: 'vertical' } }); var styles = StyleSheet.create({ notSelectable: { userSelect: 'none' }, pressable: { cursor: 'pointer' } }); export default applyLayout(applyNativeMethods(Text));
ajax/libs/react-native-web/0.11.3/exports/Touchable/index.js
cdnjs/cdnjs
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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; } /* eslint-disable react/prop-types */ /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import BoundingDimensions from './BoundingDimensions'; import findNodeHandle from '../findNodeHandle'; import normalizeColor from 'normalize-css-color'; import Position from './Position'; import React from 'react'; import TouchEventUtils from 'fbjs/lib/TouchEventUtils'; import UIManager from '../UIManager'; import View from '../View'; /** * `Touchable`: Taps done right. * * You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable` * will measure time/geometry and tells you when to give feedback to the user. * * ====================== Touchable Tutorial =============================== * The `Touchable` mixin helps you handle the "press" interaction. It analyzes * the geometry of elements, and observes when another responder (scroll view * etc) has stolen the touch lock. It notifies your component when it should * give feedback to the user. (bouncing/highlighting/unhighlighting). * * - When a touch was activated (typically you highlight) * - When a touch was deactivated (typically you unhighlight) * - When a touch was "pressed" - a touch ended while still within the geometry * of the element, and no other element (like scroller) has "stolen" touch * lock ("responder") (Typically you bounce the element). * * A good tap interaction isn't as simple as you might think. There should be a * slight delay before showing a highlight when starting a touch. If a * subsequent touch move exceeds the boundary of the element, it should * unhighlight, but if that same touch is brought back within the boundary, it * should rehighlight again. A touch can move in and out of that boundary * several times, each time toggling highlighting, but a "press" is only * triggered if that touch ends while within the element's boundary and no * scroller (or anything else) has stolen the lock on touches. * * To create a new type of component that handles interaction using the * `Touchable` mixin, do the following: * * - Initialize the `Touchable` state. * * getInitialState: function() { * return merge(this.touchableGetInitialState(), yourComponentState); * } * * - Choose the rendered component who's touches should start the interactive * sequence. On that rendered node, forward all `Touchable` responder * handlers. You can choose any rendered node you like. Choose a node whose * hit target you'd like to instigate the interaction sequence: * * // In render function: * return ( * <View * onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} * onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest} * onResponderGrant={this.touchableHandleResponderGrant} * onResponderMove={this.touchableHandleResponderMove} * onResponderRelease={this.touchableHandleResponderRelease} * onResponderTerminate={this.touchableHandleResponderTerminate}> * <View> * Even though the hit detection/interactions are triggered by the * wrapping (typically larger) node, we usually end up implementing * custom logic that highlights this inner one. * </View> * </View> * ); * * - You may set up your own handlers for each of these events, so long as you * also invoke the `touchable*` handlers inside of your custom handler. * * - Implement the handlers on your component class in order to provide * feedback to the user. See documentation for each of these class methods * that you should implement. * * touchableHandlePress: function() { * this.performBounceAnimation(); // or whatever you want to do. * }, * touchableHandleActivePressIn: function() { * this.beginHighlighting(...); // Whatever you like to convey activation * }, * touchableHandleActivePressOut: function() { * this.endHighlighting(...); // Whatever you like to convey deactivation * }, * * - There are more advanced methods you can implement (see documentation below): * touchableGetHighlightDelayMS: function() { * return 20; * } * // In practice, *always* use a predeclared constant (conserve memory). * touchableGetPressRectOffset: function() { * return {top: 20, left: 20, right: 20, bottom: 100}; * } */ /** * Touchable states. */ var States = { NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect` RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect` RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect` RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect` RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT', // Responder, active, out of `PressRect`, after long press threshold ERROR: 'ERROR' }; /** * Quick lookup map for states that are considered to be "active" */ var IsActive = { RESPONDER_ACTIVE_PRESS_OUT: true, RESPONDER_ACTIVE_PRESS_IN: true }; /** * Quick lookup for states that are considered to be "pressing" and are * therefore eligible to result in a "selection" if the press stops. */ var IsPressingIn = { RESPONDER_INACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_LONG_PRESS_IN: true }; var IsLongPressingIn = { RESPONDER_ACTIVE_LONG_PRESS_IN: true }; /** * Inputs to the state machine. */ var Signals = { DELAY: 'DELAY', RESPONDER_GRANT: 'RESPONDER_GRANT', RESPONDER_RELEASE: 'RESPONDER_RELEASE', RESPONDER_TERMINATED: 'RESPONDER_TERMINATED', ENTER_PRESS_RECT: 'ENTER_PRESS_RECT', LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT', LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED' }; /** * Mapping from States x Signals => States */ var Transitions = { NOT_RESPONDER: { DELAY: States.ERROR, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.ERROR, RESPONDER_TERMINATED: States.ERROR, ENTER_PRESS_RECT: States.ERROR, LEAVE_PRESS_RECT: States.ERROR, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_IN: { DELAY: States.RESPONDER_ACTIVE_PRESS_IN, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_OUT: { DELAY: States.RESPONDER_ACTIVE_PRESS_OUT, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_LONG_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_LONG_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, error: { DELAY: States.NOT_RESPONDER, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.NOT_RESPONDER, LEAVE_PRESS_RECT: States.NOT_RESPONDER, LONG_PRESS_DETECTED: States.NOT_RESPONDER } }; // ==== Typical Constants for integrating into UI components ==== // var HIT_EXPAND_PX = 20; // var HIT_VERT_OFFSET_PX = 10; var HIGHLIGHT_DELAY_MS = 130; var PRESS_EXPAND_PX = 20; var LONG_PRESS_THRESHOLD = 500; var LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS; var LONG_PRESS_ALLOWED_MOVEMENT = 10; // Default amount "active" region protrudes beyond box /** * By convention, methods prefixed with underscores are meant to be @private, * and not @protected. Mixers shouldn't access them - not even to provide them * as callback handlers. * * * ========== Geometry ========= * `Touchable` only assumes that there exists a `HitRect` node. The `PressRect` * is an abstract box that is extended beyond the `HitRect`. * * +--------------------------+ * | | - "Start" events in `HitRect` cause `HitRect` * | +--------------------+ | to become the responder. * | | +--------------+ | | - `HitRect` is typically expanded around * | | | | | | the `VisualRect`, but shifted downward. * | | | VisualRect | | | - After pressing down, after some delay, * | | | | | | and before letting up, the Visual React * | | +--------------+ | | will become "active". This makes it eligible * | | HitRect | | for being highlighted (so long as the * | +--------------------+ | press remains in the `PressRect`). * | PressRect o | * +----------------------|---+ * Out Region | * +-----+ This gap between the `HitRect` and * `PressRect` allows a touch to move far away * from the original hit rect, and remain * highlighted, and eligible for a "Press". * Customize this via * `touchableGetPressRectOffset()`. * * * * ======= State Machine ======= * * +-------------+ <---+ RESPONDER_RELEASE * |NOT_RESPONDER| * +-------------+ <---+ RESPONDER_TERMINATED * + * | RESPONDER_GRANT (HitRect) * v * +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+ * |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN| * +---------------------------+ +-------------------------+ +------------------------------+ * + ^ + ^ + ^ * |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ * |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT * | | | | | | * v + v + v + * +----------------------------+ DELAY +--------------------------+ +-------------------------------+ * |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT| * +----------------------------+ +--------------------------+ +-------------------------------+ * * T + DELAY => LONG_PRESS_DELAY_MS + DELAY * * Not drawn are the side effects of each transition. The most important side * effect is the `touchableHandlePress` abstract method invocation that occurs * when a responder is released while in either of the "Press" states. * * The other important side effects are the highlight abstract method * invocations (internal callbacks) to be implemented by the mixer. * * * @lends Touchable.prototype */ var TouchableMixin = { // HACK (part 1): basic support for touchable interactions using a keyboard componentDidMount: function componentDidMount() { var _this = this; this._touchableNode = findNodeHandle(this); if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableBlurListener = function (e) { if (_this._isTouchableKeyboardActive) { if (_this.state.touchable.touchState && _this.state.touchable.touchState !== States.NOT_RESPONDER) { _this.touchableHandleResponderTerminate({ nativeEvent: e }); } _this._isTouchableKeyboardActive = false; } }; this._touchableNode.addEventListener('blur', this._touchableBlurListener); } }, /** * Clear all timeouts on unmount */ componentWillUnmount: function componentWillUnmount() { if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableNode.removeEventListener('blur', this._touchableBlurListener); } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); }, /** * It's prefer that mixins determine state in this way, having the class * explicitly mix the state in the one and only `getInitialState` method. * * @return {object} State object to be placed inside of * `this.state.touchable`. */ touchableGetInitialState: function touchableGetInitialState() { return { touchable: { touchState: undefined, responderID: null } }; }, // ==== Hooks to Gesture Responder system ==== /** * Must return true if embedded in a native platform scroll view. */ touchableHandleResponderTerminationRequest: function touchableHandleResponderTerminationRequest() { return !this.props.rejectResponderTermination; }, /** * Must return true to start the process of `Touchable`. */ touchableHandleStartShouldSetResponder: function touchableHandleStartShouldSetResponder() { return !this.props.disabled; }, /** * Return true to cancel press on long press. */ touchableLongPressCancelsPress: function touchableLongPressCancelsPress() { return true; }, /** * Place as callback for a DOM element's `onResponderGrant` event. */ touchableHandleResponderGrant: function touchableHandleResponderGrant(e) { var dispatchID = e.currentTarget; // Since e is used in a callback invoked on another event loop // (as in setTimeout etc), we need to call e.persist() on the // event to make sure it doesn't get reused in the event object pool. e.persist(); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); this.pressOutDelayTimeout = null; this.state.touchable.touchState = States.NOT_RESPONDER; this.state.touchable.responderID = dispatchID; this._receiveSignal(Signals.RESPONDER_GRANT, e); var delayMS = this.touchableGetHighlightDelayMS !== undefined ? Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS; delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS; if (delayMS !== 0) { this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS); } else { this.state.touchable.positionOnActivate = null; this._handleDelay(e); } var longDelayMS = this.touchableGetLongPressDelayMS !== undefined ? Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS; longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS; this.longPressDelayTimeout = setTimeout(this._handleLongDelay.bind(this, e), longDelayMS + delayMS); }, /** * Place as callback for a DOM element's `onResponderRelease` event. */ touchableHandleResponderRelease: function touchableHandleResponderRelease(e) { this._receiveSignal(Signals.RESPONDER_RELEASE, e); }, /** * Place as callback for a DOM element's `onResponderTerminate` event. */ touchableHandleResponderTerminate: function touchableHandleResponderTerminate(e) { this._receiveSignal(Signals.RESPONDER_TERMINATED, e); }, /** * Place as callback for a DOM element's `onResponderMove` event. */ touchableHandleResponderMove: function touchableHandleResponderMove(e) { // Not enough time elapsed yet, wait for highlight - // this is just a perf optimization. if (this.state.touchable.touchState === States.RESPONDER_INACTIVE_PRESS_IN) { return; } // Measurement may not have returned yet. if (!this.state.touchable.positionOnActivate) { return; } var positionOnActivate = this.state.touchable.positionOnActivate; var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate; var pressRectOffset = this.touchableGetPressRectOffset ? this.touchableGetPressRectOffset() : { left: PRESS_EXPAND_PX, right: PRESS_EXPAND_PX, top: PRESS_EXPAND_PX, bottom: PRESS_EXPAND_PX }; var pressExpandLeft = pressRectOffset.left; var pressExpandTop = pressRectOffset.top; var pressExpandRight = pressRectOffset.right; var pressExpandBottom = pressRectOffset.bottom; var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null; if (hitSlop) { pressExpandLeft += hitSlop.left; pressExpandTop += hitSlop.top; pressExpandRight += hitSlop.right; pressExpandBottom += hitSlop.bottom; } var touch = TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; if (this.pressInLocation) { var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY); if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) { this._cancelLongPressDelayTimeout(); } } var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && pageY > positionOnActivate.top - pressExpandTop && pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom; if (isTouchWithinActive) { this._receiveSignal(Signals.ENTER_PRESS_RECT, e); var curState = this.state.touchable.touchState; if (curState === States.RESPONDER_INACTIVE_PRESS_IN) { // fix for t7967420 this._cancelLongPressDelayTimeout(); } } else { this._cancelLongPressDelayTimeout(); this._receiveSignal(Signals.LEAVE_PRESS_RECT, e); } }, // ==== Abstract Application Callbacks ==== /** * Invoked when the item should be highlighted. Mixers should implement this * to visually distinguish the `VisualRect` so that the user knows that * releasing a touch will result in a "selection" (analog to click). * * @abstract * touchableHandleActivePressIn: function, */ /** * Invoked when the item is "active" (in that it is still eligible to become * a "select") but the touch has left the `PressRect`. Usually the mixer will * want to unhighlight the `VisualRect`. If the user (while pressing) moves * back into the `PressRect` `touchableHandleActivePressIn` will be invoked * again and the mixer should probably highlight the `VisualRect` again. This * event will not fire on an `touchEnd/mouseUp` event, only move events while * the user is depressing the mouse/touch. * * @abstract * touchableHandleActivePressOut: function */ /** * Invoked when the item is "selected" - meaning the interaction ended by * letting up while the item was either in the state * `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`. * * @abstract * touchableHandlePress: function */ /** * Invoked when the item is long pressed - meaning the interaction ended by * letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If * `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will * be called as it normally is. If `touchableHandleLongPress` is provided, by * default any `touchableHandlePress` callback will not be invoked. To * override this default behavior, override `touchableLongPressCancelsPress` * to return false. As a result, `touchableHandlePress` will be called when * lifting up, even if `touchableHandleLongPress` has also been called. * * @abstract * touchableHandleLongPress: function */ /** * Returns the number of millis to wait before triggering a highlight. * * @abstract * touchableGetHighlightDelayMS: function */ /** * Returns the amount to extend the `HitRect` into the `PressRect`. Positive * numbers mean the size expands outwards. * * @abstract * touchableGetPressRectOffset: function */ // ==== Internal Logic ==== /** * Measures the `HitRect` node on activation. The Bounding rectangle is with * respect to viewport - not page, so adding the `pageXOffset/pageYOffset` * should result in points that are in the same coordinate system as an * event's `globalX/globalY` data values. * * - Consider caching this for the lifetime of the component, or possibly * being able to share this cache between any `ScrollMap` view. * * @sideeffects * @private */ _remeasureMetricsOnActivation: function _remeasureMetricsOnActivation() { var tag = this.state.touchable.responderID; if (tag == null) { return; } UIManager.measure(tag, this._handleQueryLayout); }, _handleQueryLayout: function _handleQueryLayout(x, y, width, height, globalX, globalY) { // don't do anything if UIManager failed to measure node if (!x && !y && !width && !height && !globalX && !globalY) { return; } this.state.touchable.positionOnActivate && Position.release(this.state.touchable.positionOnActivate); this.state.touchable.dimensionsOnActivate && // $FlowFixMe BoundingDimensions.release(this.state.touchable.dimensionsOnActivate); this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY); // $FlowFixMe this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(width, height); }, _handleDelay: function _handleDelay(e) { this.touchableDelayTimeout = null; this._receiveSignal(Signals.DELAY, e); }, _handleLongDelay: function _handleLongDelay(e) { this.longPressDelayTimeout = null; var curState = this.state.touchable.touchState; if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) { console.error('Attempted to transition from state `' + curState + '` to `' + States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.'); } else { this._receiveSignal(Signals.LONG_PRESS_DETECTED, e); } }, /** * Receives a state machine signal, performs side effects of the transition * and stores the new state. Validates the transition as well. * * @param {Signals} signal State machine signal. * @throws Error if invalid state transition or unrecognized signal. * @sideeffects */ _receiveSignal: function _receiveSignal(signal, e) { var responderID = this.state.touchable.responderID; var curState = this.state.touchable.touchState; var nextState = Transitions[curState] && Transitions[curState][signal]; if (!responderID && signal === Signals.RESPONDER_RELEASE) { return; } if (!nextState) { throw new Error('Unrecognized signal `' + signal + '` or state `' + curState + '` for Touchable responder `' + responderID + '`'); } if (nextState === States.ERROR) { throw new Error('Touchable cannot transition from `' + curState + '` to `' + signal + '` for responder `' + responderID + '`'); } if (curState !== nextState) { this._performSideEffectsForTransition(curState, nextState, signal, e); this.state.touchable.touchState = nextState; } }, _cancelLongPressDelayTimeout: function _cancelLongPressDelayTimeout() { this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.longPressDelayTimeout = null; }, _isHighlight: function _isHighlight(state) { return state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN; }, _savePressInLocation: function _savePressInLocation(e) { var touch = TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; this.pressInLocation = { pageX: pageX, pageY: pageY, get locationX() { return touch && touch.locationX; }, get locationY() { return touch && touch.locationY; } }; }, _getDistanceBetweenPoints: function _getDistanceBetweenPoints(aX, aY, bX, bY) { var deltaX = aX - bX; var deltaY = aY - bY; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); }, /** * Will perform a transition between touchable states, and identify any * highlighting or unhighlighting that must be performed for this particular * transition. * * @param {States} curState Current Touchable state. * @param {States} nextState Next Touchable state. * @param {Signal} signal Signal that triggered the transition. * @param {Event} e Native event. * @sideeffects */ _performSideEffectsForTransition: function _performSideEffectsForTransition(curState, nextState, signal, e) { var curIsHighlight = this._isHighlight(curState); var newIsHighlight = this._isHighlight(nextState); var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE; if (isFinalSignal) { this._cancelLongPressDelayTimeout(); } if (!IsActive[curState] && IsActive[nextState]) { this._remeasureMetricsOnActivation(); } if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) { this.touchableHandleLongPress && this.touchableHandleLongPress(e); } if (newIsHighlight && !curIsHighlight) { this._startHighlight(e); } else if (!newIsHighlight && curIsHighlight) { this._endHighlight(e); } if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) { var hasLongPressHandler = !!this.props.onLongPress; var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && ( // We *are* long pressing.. !hasLongPressHandler || // But either has no long handler !this.touchableLongPressCancelsPress()); // or we're told to ignore it. var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress; if (shouldInvokePress && this.touchableHandlePress) { if (!newIsHighlight && !curIsHighlight) { // we never highlighted because of delay, but we should highlight now this._startHighlight(e); this._endHighlight(e); } this.touchableHandlePress(e); } } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.touchableDelayTimeout = null; }, _startHighlight: function _startHighlight(e) { this._savePressInLocation(e); this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e); }, _endHighlight: function _endHighlight(e) { var _this2 = this; if (this.touchableHandleActivePressOut) { if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) { this.pressOutDelayTimeout = setTimeout(function () { _this2.touchableHandleActivePressOut(e); }, this.touchableGetPressOutDelayMS()); } else { this.touchableHandleActivePressOut(e); } } }, // HACK (part 2): basic support for touchable interactions using a keyboard (including // delays and longPress) touchableHandleKeyEvent: function touchableHandleKeyEvent(e) { var ENTER = 13; var SPACE = 32; var type = e.type, which = e.which; if (which === ENTER || which === SPACE) { if (type === 'keydown') { if (!this._isTouchableKeyboardActive) { if (!this.state.touchable.touchState || this.state.touchable.touchState === States.NOT_RESPONDER) { this.touchableHandleResponderGrant(e); this._isTouchableKeyboardActive = true; } } } else if (type === 'keyup') { if (this._isTouchableKeyboardActive) { if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) { this.touchableHandleResponderRelease(e); this._isTouchableKeyboardActive = false; } } } e.stopPropagation(); // prevent the default behaviour unless the Touchable functions as a link // and Enter is pressed if (!(which === ENTER && AccessibilityUtil.propsToAriaRole(this.props) === 'link')) { e.preventDefault(); } } } }; var Touchable = { Mixin: TouchableMixin, TOUCH_TARGET_DEBUG: false, // Highlights all touchable targets. Toggle with Inspector. /** * Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android). */ renderDebugView: function renderDebugView(_ref) { var color = _ref.color, hitSlop = _ref.hitSlop; if (process.env.NODE_ENV !== 'production') { if (!Touchable.TOUCH_TARGET_DEBUG) { return null; } var debugHitSlopStyle = {}; hitSlop = hitSlop || { top: 0, bottom: 0, left: 0, right: 0 }; for (var key in hitSlop) { debugHitSlopStyle[key] = -hitSlop[key]; } var hexColor = '#' + ('00000000' + normalizeColor(color).toString(16)).substr(-8); return React.createElement(View, { pointerEvents: "none", style: _objectSpread({ position: 'absolute', borderColor: hexColor.slice(0, -2) + '55', // More opaque borderWidth: 1, borderStyle: 'dashed', backgroundColor: hexColor.slice(0, -2) + '0F' }, debugHitSlopStyle) }); } } }; export default Touchable;
ajax/libs/primereact/7.2.0/chart/chart.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/utils'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Chart = /*#__PURE__*/function (_Component) { _inherits(Chart, _Component); var _super = _createSuper(Chart); function Chart() { _classCallCheck(this, Chart); return _super.apply(this, arguments); } _createClass(Chart, [{ key: "initChart", value: function initChart() { var _this = this; import('chart.js/auto').then(function (module) { if (_this.chart) { _this.chart.destroy(); _this.chart = null; } if (module && module["default"]) { _this.chart = new module["default"](_this.canvas, { type: _this.props.type, data: _this.props.data, options: _this.props.options, plugins: _this.props.plugins }); } }); } }, { key: "getCanvas", value: function getCanvas() { return this.canvas; } }, { key: "getChart", value: function getChart() { return this.chart; } }, { key: "getBase64Image", value: function getBase64Image() { return this.chart.toBase64Image(); } }, { key: "generateLegend", value: function generateLegend() { if (this.chart) { this.chart.generateLegend(); } } }, { key: "refresh", value: function refresh() { if (this.chart) { this.chart.update(); } } }, { key: "reinit", value: function reinit() { this.initChart(); } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps) { if (nextProps.data === this.props.data && nextProps.options === this.props.options && nextProps.type === this.props.type) { return false; } return true; } }, { key: "componentDidMount", value: function componentDidMount() { this.initChart(); } }, { key: "componentDidUpdate", value: function componentDidUpdate() { this.reinit(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.chart) { this.chart.destroy(); this.chart = null; } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-chart', this.props.className), style = Object.assign({ width: this.props.width, height: this.props.height }, this.props.style); return /*#__PURE__*/React.createElement("div", { id: this.props.id, style: style, className: className }, /*#__PURE__*/React.createElement("canvas", { ref: function ref(el) { _this2.canvas = el; }, width: this.props.width, height: this.props.height })); } }]); return Chart; }(Component); _defineProperty(Chart, "defaultProps", { id: null, type: null, data: null, options: null, plugins: null, width: null, height: null, style: null, className: null }); export { Chart };
ajax/libs/material-ui/4.9.2/es/test-utils/createRender.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import { render as enzymeRender } from 'enzyme'; import React from 'react'; import { RenderContext } from './RenderMode'; /** * Generate a render to string function. * @deprecated to remvoe in v5 */ export default function createRender(options1 = {}) { const { render = enzymeRender } = options1, other1 = _objectWithoutPropertiesLoose(options1, ["render"]); const renderWithContext = function renderWithContext(node, options2 = {}) { return render(React.createElement(RenderContext, null, node), _extends({}, other1, {}, options2)); }; return renderWithContext; }
ajax/libs/material-ui/5.0.0-alpha.16/styles/ThemeProvider.js
cdnjs/cdnjs
import React from 'react'; import PropTypes from 'prop-types'; import { ThemeProvider as MuiThemeProvider } from '@material-ui/styles'; import { exactProp } from '@material-ui/utils'; import { ThemeContext as StyledEngineThemeContext } from '@material-ui/styled-engine'; import useTheme from './useTheme'; function InnerThemeProvider(props) { const theme = useTheme(); return /*#__PURE__*/React.createElement(StyledEngineThemeContext.Provider, { value: typeof theme === 'object' ? theme : {} }, props.children); } process.env.NODE_ENV !== "production" ? InnerThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node } : void 0; /** * This component makes the `theme` available down the React tree. * It should preferably be used at **the root of your component tree**. */ function ThemeProvider(props) { const { children, theme: localTheme } = props; return /*#__PURE__*/React.createElement(MuiThemeProvider, { theme: localTheme }, /*#__PURE__*/React.createElement(InnerThemeProvider, null, children)); } process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node, /** * A theme object. You can provide a function to extend the outer theme. */ theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0; } export default ThemeProvider;
ajax/libs/react-native-web/0.14.8/exports/ScrollView/index.js
cdnjs/cdnjs
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import createReactClass from 'create-react-class'; import dismissKeyboard from '../../modules/dismissKeyboard'; import invariant from 'fbjs/lib/invariant'; import ScrollResponder from '../../modules/ScrollResponder'; import ScrollViewBase from './ScrollViewBase'; import StyleSheet from '../StyleSheet'; import View from '../View'; import React from 'react'; var emptyObject = {}; /* eslint-disable react/prefer-es6-class */ var ScrollView = createReactClass({ displayName: "ScrollView", mixins: [ScrollResponder.Mixin], getInitialState: function getInitialState() { return this.scrollResponderMixinGetInitialState(); }, flashScrollIndicators: function flashScrollIndicators() { this.scrollResponderFlashScrollIndicators(); }, setNativeProps: function setNativeProps(props) { if (this._scrollNodeRef) { this._scrollNodeRef.setNativeProps(props); } }, /** * Returns a reference to the underlying scroll responder, which supports * operations like `scrollTo`. All ScrollView-like components should * implement this method so that they can be composed while providing access * to the underlying scroll responder's methods. */ getScrollResponder: function getScrollResponder() { return this; }, getScrollableNode: function getScrollableNode() { return this._scrollNodeRef; }, getInnerViewNode: function getInnerViewNode() { return this._innerViewRef; }, /** * Scrolls to a given x, y offset, either immediately or with a smooth animation. * Syntax: * * scrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true}) * * Note: The weird argument signature is due to the fact that, for historical reasons, * the function also accepts separate arguments as as alternative to the options object. * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED. */ scrollTo: function scrollTo(y, x, animated) { if (typeof y === 'number') { console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.'); } else { var _ref = y || emptyObject; x = _ref.x; y = _ref.y; animated = _ref.animated; } this.getScrollResponder().scrollResponderScrollTo({ x: x || 0, y: y || 0, animated: animated !== false }); }, /** * If this is a vertical ScrollView scrolls to the bottom. * If this is a horizontal ScrollView scrolls to the right. * * Use `scrollToEnd({ animated: true })` for smooth animated scrolling, * `scrollToEnd({ animated: false })` for immediate scrolling. * If no options are passed, `animated` defaults to true. */ scrollToEnd: function scrollToEnd(options) { // Default to true var animated = (options && options.animated) !== false; var horizontal = this.props.horizontal; var scrollResponder = this.getScrollResponder(); var scrollResponderNode = scrollResponder.scrollResponderGetScrollableNode(); var x = horizontal ? scrollResponderNode.scrollWidth : 0; var y = horizontal ? 0 : scrollResponderNode.scrollHeight; scrollResponder.scrollResponderScrollTo({ x: x, y: y, animated: animated }); }, render: function render() { var _this$props = this.props, contentContainerStyle = _this$props.contentContainerStyle, horizontal = _this$props.horizontal, onContentSizeChange = _this$props.onContentSizeChange, refreshControl = _this$props.refreshControl, stickyHeaderIndices = _this$props.stickyHeaderIndices, pagingEnabled = _this$props.pagingEnabled, keyboardDismissMode = _this$props.keyboardDismissMode, onScroll = _this$props.onScroll, other = _objectWithoutPropertiesLoose(_this$props, ["contentContainerStyle", "horizontal", "onContentSizeChange", "refreshControl", "stickyHeaderIndices", "pagingEnabled", "keyboardDismissMode", "onScroll"]); if (process.env.NODE_ENV !== 'production' && this.props.style) { var style = StyleSheet.flatten(this.props.style); var childLayoutProps = ['alignItems', 'justifyContent'].filter(function (prop) { return style && style[prop] !== undefined; }); invariant(childLayoutProps.length === 0, "ScrollView child layout (" + JSON.stringify(childLayoutProps) + ") " + 'must be applied through the contentContainerStyle prop.'); } var contentSizeChangeProps = {}; if (onContentSizeChange) { contentSizeChangeProps = { onLayout: this._handleContentOnLayout }; } var hasStickyHeaderIndices = !horizontal && Array.isArray(stickyHeaderIndices); var children = hasStickyHeaderIndices || pagingEnabled ? React.Children.map(this.props.children, function (child, i) { var isSticky = hasStickyHeaderIndices && stickyHeaderIndices.indexOf(i) > -1; if (child != null && (isSticky || pagingEnabled)) { return React.createElement(View, { style: StyleSheet.compose(isSticky && styles.stickyHeader, pagingEnabled && styles.pagingEnabledChild) }, child); } else { return child; } }) : this.props.children; var contentContainer = React.createElement(View, _extends({}, contentSizeChangeProps, { children: children, collapsable: false, ref: this._setInnerViewRef, style: StyleSheet.compose(horizontal && styles.contentContainerHorizontal, contentContainerStyle) })); var baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical; var pagingEnabledStyle = horizontal ? styles.pagingEnabledHorizontal : styles.pagingEnabledVertical; var props = _objectSpread({}, other, { style: [baseStyle, pagingEnabled && pagingEnabledStyle, this.props.style], onTouchStart: this.scrollResponderHandleTouchStart, onTouchMove: this.scrollResponderHandleTouchMove, onTouchEnd: this.scrollResponderHandleTouchEnd, onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag, onScrollEndDrag: this.scrollResponderHandleScrollEndDrag, onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin, onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd, onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder, onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture, onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder, onScroll: this._handleScroll, onResponderGrant: this.scrollResponderHandleResponderGrant, onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest, onResponderTerminate: this.scrollResponderHandleTerminate, onResponderRelease: this.scrollResponderHandleResponderRelease, onResponderReject: this.scrollResponderHandleResponderReject }); var ScrollViewClass = ScrollViewBase; invariant(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined'); if (refreshControl) { return React.cloneElement(refreshControl, { style: props.style }, React.createElement(ScrollViewClass, _extends({}, props, { ref: this._setScrollNodeRef, style: baseStyle }), contentContainer)); } return React.createElement(ScrollViewClass, _extends({}, props, { ref: this._setScrollNodeRef }), contentContainer); }, _handleContentOnLayout: function _handleContentOnLayout(e) { var _e$nativeEvent$layout = e.nativeEvent.layout, width = _e$nativeEvent$layout.width, height = _e$nativeEvent$layout.height; this.props.onContentSizeChange(width, height); }, _handleScroll: function _handleScroll(e) { if (process.env.NODE_ENV !== 'production') { if (this.props.onScroll && this.props.scrollEventThrottle == null) { console.log('You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + "cause frame drops, use a bigger number if you don't need as " + 'much precision.'); } } if (this.props.keyboardDismissMode === 'on-drag') { dismissKeyboard(); } this.scrollResponderHandleScroll(e); }, _setInnerViewRef: function _setInnerViewRef(component) { this._innerViewRef = component; }, _setScrollNodeRef: function _setScrollNodeRef(component) { this._scrollNodeRef = component; } }); var commonStyle = { flexGrow: 1, flexShrink: 1, // Enable hardware compositing in modern browsers. // Creates a new layer with its own backing surface that can significantly // improve scroll performance. transform: [{ translateZ: 0 }], // iOS native scrolling WebkitOverflowScrolling: 'touch' }; var styles = StyleSheet.create({ baseVertical: _objectSpread({}, commonStyle, { flexDirection: 'column', overflowX: 'hidden', overflowY: 'auto' }), baseHorizontal: _objectSpread({}, commonStyle, { flexDirection: 'row', overflowX: 'auto', overflowY: 'hidden' }), contentContainerHorizontal: { flexDirection: 'row' }, stickyHeader: { position: 'sticky', top: 0, zIndex: 10 }, pagingEnabledHorizontal: { scrollSnapType: 'x mandatory' }, pagingEnabledVertical: { scrollSnapType: 'y mandatory' }, pagingEnabledChild: { scrollSnapAlign: 'start' } }); export default ScrollView;
ajax/libs/react-native-web/0.11.4/vendor/react-native/SwipeableFlatList/index.js
cdnjs/cdnjs
/** * Copyright (c) 2015-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. * * @providesModule SwipeableFlatList * * @format */ 'use strict'; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } import PropTypes from 'prop-types'; import React from 'react'; import SwipeableRow from '../SwipeableRow'; import FlatList from '../FlatList'; /** * A container component that renders multiple SwipeableRow's in a FlatList * implementation. This is designed to be a drop-in replacement for the * standard React Native `FlatList`, so use it as if it were a FlatList, but * with extra props, i.e. * * <SwipeableListView renderRow={..} renderQuickActions={..} {..FlatList props} /> * * SwipeableRow can be used independently of this component, but the main * benefit of using this component is * * - It ensures that at most 1 row is swiped open (auto closes others) * - It can bounce the 1st row of the list so users know it's swipeable * - Increase performance on iOS by locking list swiping when row swiping is occurring * - More to come */ var SwipeableFlatList = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(SwipeableFlatList, _React$Component); function SwipeableFlatList(props, context) { var _this; _this = _React$Component.call(this, props, context) || this; _this._flatListRef = null; _this._shouldBounceFirstRowOnMount = false; _this._onScroll = function (e) { // Close any opens rows on ListView scroll if (_this.state.openRowKey) { _this.setState({ openRowKey: null }); } _this.props.onScroll && _this.props.onScroll(e); }; _this._renderItem = function (info) { var slideoutView = _this.props.renderQuickActions(info); var key = _this.props.keyExtractor(info.item, info.index); // If renderQuickActions is unspecified or returns falsey, don't allow swipe if (!slideoutView) { return _this.props.renderItem(info); } var shouldBounceOnMount = false; if (_this._shouldBounceFirstRowOnMount) { _this._shouldBounceFirstRowOnMount = false; shouldBounceOnMount = true; } return React.createElement(SwipeableRow, { slideoutView: slideoutView, isOpen: key === _this.state.openRowKey, maxSwipeDistance: _this._getMaxSwipeDistance(info), onOpen: function onOpen() { return _this._onOpen(key); }, onClose: function onClose() { return _this._onClose(key); }, shouldBounceOnMount: shouldBounceOnMount, onSwipeEnd: _this._setListViewScrollable, onSwipeStart: _this._setListViewNotScrollable }, _this.props.renderItem(info)); }; _this._setListViewScrollable = function () { _this._setListViewScrollableTo(true); }; _this._setListViewNotScrollable = function () { _this._setListViewScrollableTo(false); }; _this.state = { openRowKey: null }; _this._shouldBounceFirstRowOnMount = _this.props.bounceFirstRowOnMount; return _this; } var _proto = SwipeableFlatList.prototype; _proto.render = function render() { var _this2 = this; return React.createElement(FlatList, _extends({}, this.props, { ref: function ref(_ref) { _this2._flatListRef = _ref; }, onScroll: this._onScroll, renderItem: this._renderItem })); }; // This enables rows having variable width slideoutView. _proto._getMaxSwipeDistance = function _getMaxSwipeDistance(info) { if (typeof this.props.maxSwipeDistance === 'function') { return this.props.maxSwipeDistance(info); } return this.props.maxSwipeDistance; }; _proto._setListViewScrollableTo = function _setListViewScrollableTo(value) { if (this._flatListRef) { this._flatListRef.setNativeProps({ scrollEnabled: value }); } }; _proto._onOpen = function _onOpen(key) { this.setState({ openRowKey: key }); }; _proto._onClose = function _onClose(key) { this.setState({ openRowKey: null }); }; return SwipeableFlatList; }(React.Component); SwipeableFlatList.defaultProps = _objectSpread({}, FlatList.defaultProps, { bounceFirstRowOnMount: true, renderQuickActions: function renderQuickActions() { return null; } }); SwipeableFlatList.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, FlatList.propTypes, { /** * To alert the user that swiping is possible, the first row can bounce * on component mount. */ bounceFirstRowOnMount: PropTypes.bool.isRequired, // Maximum distance to open to after a swipe maxSwipeDistance: PropTypes.oneOfType([PropTypes.number, PropTypes.func]).isRequired, // Callback method to render the view that will be unveiled on swipe renderQuickActions: PropTypes.func.isRequired }) : {}; export default SwipeableFlatList;
ajax/libs/material-ui/4.9.3/es/TableRow/TableRow.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Tablelvl2Context from '../Table/Tablelvl2Context'; import { fade } from '../styles/colorManipulator'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { color: 'inherit', display: 'table-row', verticalAlign: 'middle', // We disable the focus ring for mouse, touch and keyboard users. outline: 0, '&$hover:hover': { backgroundColor: theme.palette.action.hover }, '&$selected,&$selected:hover': { backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.selectedOpacity) } }, /* Pseudo-class applied to the root element if `selected={true}`. */ selected: {}, /* Pseudo-class applied to the root element if `hover={true}`. */ hover: {}, /* Styles applied to the root element if table variant="head". */ head: {}, /* Styles applied to the root element if table variant="footer". */ footer: {} }); /** * Will automatically set dynamic row height * based on the material table element parent (head, body, etc). */ const TableRow = React.forwardRef(function TableRow(props, ref) { const { classes, className, component: Component = 'tr', hover = false, selected = false } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "component", "hover", "selected"]); const tablelvl2 = React.useContext(Tablelvl2Context); return React.createElement(Component, _extends({ ref: ref, className: clsx(classes.root, className, tablelvl2 && { 'head': classes.head, 'footer': classes.footer }[tablelvl2.variant], hover && classes.hover, selected && classes.selected) }, other)); }); process.env.NODE_ENV !== "production" ? TableRow.propTypes = { /** * Should be valid <tr> children such as `TableCell`. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, the table row will shade on hover. */ hover: PropTypes.bool, /** * If `true`, the table row will have the selected shading. */ selected: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiTableRow' })(TableRow);
ajax/libs/primereact/7.1.0/treetable/treetable.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { localeOption, FilterService } from 'primereact/api'; import { DomHandler as DomHandler$1, classNames, ObjectUtils } from 'primereact/utils'; import { Paginator } from 'primereact/paginator'; import { InputText } from 'primereact/inputtext'; import { OverlayService } from 'primereact/overlayservice'; import { Ripple } from 'primereact/ripple'; function _arrayLikeToArray$5(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$5(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$5(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$5(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$5(o, minLen); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$5(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createForOfIteratorHelper$4(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$4(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$4(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen); } function _arrayLikeToArray$4(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTableHeader = /*#__PURE__*/function (_Component) { _inherits(TreeTableHeader, _Component); var _super = _createSuper$6(TreeTableHeader); function TreeTableHeader(props) { var _this; _classCallCheck(this, TreeTableHeader); _this = _super.call(this, props); _this.state = { badgeVisible: false }; _this.onFilterInput = _this.onFilterInput.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTableHeader, [{ key: "onHeaderClick", value: function onHeaderClick(event, column) { if (column.props.sortable) { var targetNode = event.target; if (DomHandler$1.hasClass(targetNode, 'p-sortable-column') || DomHandler$1.hasClass(targetNode, 'p-column-title') || DomHandler$1.hasClass(targetNode, 'p-sortable-column-icon') || DomHandler$1.hasClass(targetNode.parentElement, 'p-sortable-column-icon')) { this.props.onSort({ originalEvent: event, sortField: column.props.sortField || column.props.field, sortFunction: column.props.sortFunction, sortable: column.props.sortable }); DomHandler$1.clearSelection(); } } } }, { key: "onHeaderMouseDown", value: function onHeaderMouseDown(event, column) { if (this.props.reorderableColumns && column.props.reorderable) { if (event.target.nodeName !== 'INPUT') event.currentTarget.draggable = true;else if (event.target.nodeName === 'INPUT') event.currentTarget.draggable = false; } } }, { key: "onHeaderKeyDown", value: function onHeaderKeyDown(event, column) { if (event.key === 'Enter') { this.onHeaderClick(event, column); event.preventDefault(); } } }, { key: "getMultiSortMetaDataIndex", value: function getMultiSortMetaDataIndex(column) { if (this.props.multiSortMeta) { for (var i = 0; i < this.props.multiSortMeta.length; i++) { if (this.props.multiSortMeta[i].field === column.props.field) { return i; } } } return -1; } }, { key: "onResizerMouseDown", value: function onResizerMouseDown(event, column) { if (this.props.resizableColumns && this.props.onResizeStart) { this.props.onResizeStart({ originalEvent: event, columnEl: event.target.parentElement, column: column }); } } }, { key: "onDragStart", value: function onDragStart(event, column) { if (this.props.onDragStart) { this.props.onDragStart({ originalEvent: event, column: column }); } } }, { key: "onDragOver", value: function onDragOver(event, column) { if (this.props.onDragOver) { this.props.onDragOver({ originalEvent: event, column: column }); } } }, { key: "onDragLeave", value: function onDragLeave(event, column) { if (this.props.onDragLeave) { this.props.onDragLeave({ originalEvent: event, column: column }); } } }, { key: "onDrop", value: function onDrop(event, column) { if (this.props.onDrop) { this.props.onDrop({ originalEvent: event, column: column }); } } }, { key: "onFilterInput", value: function onFilterInput(e, column) { var _this2 = this; if (column.props.filter && this.props.onFilter) { if (this.filterTimeout) { clearTimeout(this.filterTimeout); } var filterValue = e.target.value; this.filterTimeout = setTimeout(function () { _this2.props.onFilter({ value: filterValue, field: column.props.field, matchMode: column.props.filterMatchMode || 'startsWith' }); _this2.filterTimeout = null; }, this.props.filterDelay); } } }, { key: "hasColumnFilter", value: function hasColumnFilter(columns) { if (columns) { var _iterator = _createForOfIteratorHelper$4(columns), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var col = _step.value; if (col.props.filter) { return true; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return false; } }, { key: "renderSortIcon", value: function renderSortIcon(column, sorted, sortOrder) { if (column.props.sortable) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-amount-down' : 'pi-sort-amount-up-alt' : 'pi-sort-alt'; var sortIconClassName = classNames('p-sortable-column-icon', 'pi pi-fw', sortIcon); return /*#__PURE__*/React.createElement("span", { className: sortIconClassName }); } else { return null; } } }, { key: "renderResizer", value: function renderResizer(column) { var _this3 = this; if (this.props.resizableColumns) { return /*#__PURE__*/React.createElement("span", { className: "p-column-resizer p-clickable", onMouseDown: function onMouseDown(e) { return _this3.onResizerMouseDown(e, column); } }); } else { return null; } } }, { key: "getAriaSort", value: function getAriaSort(column, sorted, sortOrder) { if (column.props.sortable) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-down' : 'pi-sort-up' : 'pi-sort'; if (sortIcon === 'pi-sort-down') return 'descending';else if (sortIcon === 'pi-sort-up') return 'ascending';else return 'none'; } else { return null; } } }, { key: "renderSortBadge", value: function renderSortBadge(sortMetaDataIndex) { if (sortMetaDataIndex !== -1 && this.state.badgeVisible) { return /*#__PURE__*/React.createElement("span", { className: "p-sortable-column-badge" }, sortMetaDataIndex + 1); } return null; } }, { key: "renderHeaderCell", value: function renderHeaderCell(column, options) { var _this4 = this; var filterElement; if (column.props.filter && options.renderFilter) { filterElement = column.props.filterElement || /*#__PURE__*/React.createElement(InputText, { onInput: function onInput(e) { return _this4.onFilterInput(e, column); }, type: this.props.filterType, defaultValue: this.props.filters && this.props.filters[column.props.field] ? this.props.filters[column.props.field].value : null, className: "p-column-filter", placeholder: column.props.filterPlaceholder, maxLength: column.props.filterMaxLength }); } if (options.filterOnly) { return /*#__PURE__*/React.createElement("th", { key: column.props.columnKey || column.props.field || options.index, className: classNames('p-filter-column', column.props.filterHeaderClassName), style: column.props.filterHeaderStyle || column.props.style, rowSpan: column.props.rowSpan, colSpan: column.props.colSpan }, filterElement); } else { var sortMetaDataIndex = this.getMultiSortMetaDataIndex(column); var multiSortMetaData = sortMetaDataIndex !== -1 ? this.props.multiSortMeta[sortMetaDataIndex] : null; var singleSorted = column.props.field === this.props.sortField; var multipleSorted = multiSortMetaData !== null; var sorted = column.props.sortable && (singleSorted || multipleSorted); var sortOrder = 0; if (singleSorted) sortOrder = this.props.sortOrder;else if (multipleSorted) sortOrder = multiSortMetaData.order; var sortIconElement = this.renderSortIcon(column, sorted, sortOrder); var ariaSortData = this.getAriaSort(column, sorted, sortOrder); var sortBadge = this.renderSortBadge(sortMetaDataIndex); var className = classNames(column.props.headerClassName || column.props.className, { 'p-sortable-column': column.props.sortable, 'p-highlight': sorted, 'p-resizable-column': this.props.resizableColumns }); var resizer = this.renderResizer(column); return /*#__PURE__*/React.createElement("th", { key: column.columnKey || column.field || options.index, className: className, style: column.props.headerStyle || column.props.style, tabIndex: column.props.sortable ? this.props.tabIndex : null, onClick: function onClick(e) { return _this4.onHeaderClick(e, column); }, onMouseDown: function onMouseDown(e) { return _this4.onHeaderMouseDown(e, column); }, onKeyDown: function onKeyDown(e) { return _this4.onHeaderKeyDown(e, column); }, rowSpan: column.props.rowSpan, colSpan: column.props.colSpan, "aria-sort": ariaSortData, onDragStart: function onDragStart(e) { return _this4.onDragStart(e, column); }, onDragOver: function onDragOver(e) { return _this4.onDragOver(e, column); }, onDragLeave: function onDragLeave(e) { return _this4.onDragLeave(e, column); }, onDrop: function onDrop(e) { return _this4.onDrop(e, column); } }, resizer, /*#__PURE__*/React.createElement("span", { className: "p-column-title" }, column.props.header), sortIconElement, sortBadge, filterElement); } } }, { key: "renderHeaderRow", value: function renderHeaderRow(row, index) { var _this5 = this; var rowColumns = React.Children.toArray(row.props.children); var rowHeaderCells = rowColumns.map(function (col, i) { return _this5.renderHeaderCell(col, { index: i, filterOnly: false, renderFilter: true }); }); return /*#__PURE__*/React.createElement("tr", { key: index }, rowHeaderCells); } }, { key: "renderColumnGroup", value: function renderColumnGroup() { var _this6 = this; var rows = React.Children.toArray(this.props.columnGroup.props.children); return rows.map(function (row, i) { return _this6.renderHeaderRow(row, i); }); } }, { key: "renderColumns", value: function renderColumns(columns) { var _this7 = this; if (columns) { if (this.hasColumnFilter(columns)) { return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("tr", null, columns.map(function (col, i) { return _this7.renderHeaderCell(col, { index: i, filterOnly: false, renderFilter: false }); })), /*#__PURE__*/React.createElement("tr", null, columns.map(function (col, i) { return _this7.renderHeaderCell(col, { index: i, filterOnly: true, renderFilter: true }); }))); } else { return /*#__PURE__*/React.createElement("tr", null, columns.map(function (col, i) { return _this7.renderHeaderCell(col, { index: i, filterOnly: false, renderFilter: false }); })); } } else { return null; } } }, { key: "render", value: function render() { var content = this.props.columnGroup ? this.renderColumnGroup() : this.renderColumns(this.props.columns); return /*#__PURE__*/React.createElement("thead", { className: "p-treetable-thead" }, content); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { return { badgeVisible: nextProps.multiSortMeta && nextProps.multiSortMeta.length > 1 }; } }]); return TreeTableHeader; }(Component); function _createForOfIteratorHelper$3(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$3(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$3(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen); } function _arrayLikeToArray$3(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var DomHandler = /*#__PURE__*/function () { function DomHandler() { _classCallCheck(this, DomHandler); } _createClass(DomHandler, null, [{ key: "innerWidth", value: function innerWidth(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width += parseFloat(style.paddingLeft) + parseFloat(style.paddingRight); return width; } return 0; } }, { key: "width", value: function width(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight); return width; } return 0; } }, { key: "getWindowScrollTop", value: function getWindowScrollTop() { var doc = document.documentElement; return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); } }, { key: "getWindowScrollLeft", value: function getWindowScrollLeft() { var doc = document.documentElement; return (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); } }, { key: "getOuterWidth", value: function getOuterWidth(el, margin) { if (el) { var width = el.offsetWidth || el.getBoundingClientRect().width; if (margin) { var style = getComputedStyle(el); width += parseFloat(style.marginLeft) + parseFloat(style.marginRight); } return width; } return 0; } }, { key: "getOuterHeight", value: function getOuterHeight(el, margin) { if (el) { var height = el.offsetHeight || el.getBoundingClientRect().height; if (margin) { var style = getComputedStyle(el); height += parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } return 0; } }, { key: "getClientHeight", value: function getClientHeight(el, margin) { if (el) { var height = el.clientHeight; if (margin) { var style = getComputedStyle(el); height += parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } return 0; } }, { key: "getClientWidth", value: function getClientWidth(el, margin) { if (el) { var width = el.clientWidth; if (margin) { var style = getComputedStyle(el); width += parseFloat(style.marginLeft) + parseFloat(style.marginRight); } return width; } return 0; } }, { key: "getViewport", value: function getViewport() { var win = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], w = win.innerWidth || e.clientWidth || g.clientWidth, h = win.innerHeight || e.clientHeight || g.clientHeight; return { width: w, height: h }; } }, { key: "getOffset", value: function getOffset(el) { if (el) { var rect = el.getBoundingClientRect(); return { top: rect.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0), left: rect.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0) }; } return { top: 'auto', left: 'auto' }; } }, { key: "index", value: function index(element) { if (element) { var children = element.parentNode.childNodes; var num = 0; for (var i = 0; i < children.length; i++) { if (children[i] === element) return num; if (children[i].nodeType === 1) num++; } } return -1; } }, { key: "addMultipleClasses", value: function addMultipleClasses(element, className) { if (element && className) { if (element.classList) { var styles = className.split(' '); for (var i = 0; i < styles.length; i++) { element.classList.add(styles[i]); } } else { var _styles = className.split(' '); for (var _i = 0; _i < _styles.length; _i++) { element.className += ' ' + _styles[_i]; } } } } }, { key: "removeMultipleClasses", value: function removeMultipleClasses(element, className) { if (element && className) { if (element.classList) { var styles = className.split(' '); for (var i = 0; i < styles.length; i++) { element.classList.remove(styles[i]); } } else { var _styles2 = className.split(' '); for (var _i2 = 0; _i2 < _styles2.length; _i2++) { element.className = element.className.replace(new RegExp('(^|\\b)' + _styles2[_i2].split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } } } } }, { key: "addClass", value: function addClass(element, className) { if (element && className) { if (element.classList) element.classList.add(className);else element.className += ' ' + className; } } }, { key: "removeClass", value: function removeClass(element, className) { if (element && className) { if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } } }, { key: "hasClass", value: function hasClass(element, className) { if (element) { if (element.classList) return element.classList.contains(className);else return new RegExp('(^| )' + className + '( |$)', 'gi').test(element.className); } } }, { key: "find", value: function find(element, selector) { return element ? Array.from(element.querySelectorAll(selector)) : []; } }, { key: "findSingle", value: function findSingle(element, selector) { if (element) { return element.querySelector(selector); } return null; } }, { key: "getHeight", value: function getHeight(el) { if (el) { var height = el.offsetHeight; var style = getComputedStyle(el); height -= parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth); return height; } return 0; } }, { key: "getWidth", value: function getWidth(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth); return width; } return 0; } }, { key: "alignOverlay", value: function alignOverlay(overlay, target, appendTo) { var calculateMinWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; if (overlay && target) { if (appendTo === 'self') { this.relativePosition(overlay, target); } else { calculateMinWidth && (overlay.style.minWidth = DomHandler.getOuterWidth(target) + 'px'); this.absolutePosition(overlay, target); } } } }, { key: "absolutePosition", value: function absolutePosition(element, target) { if (element) { var elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : this.getHiddenElementDimensions(element); var elementOuterHeight = elementDimensions.height; var elementOuterWidth = elementDimensions.width; var targetOuterHeight = target.offsetHeight; var targetOuterWidth = target.offsetWidth; var targetOffset = target.getBoundingClientRect(); var windowScrollTop = this.getWindowScrollTop(); var windowScrollLeft = this.getWindowScrollLeft(); var viewport = this.getViewport(); var top, left; if (targetOffset.top + targetOuterHeight + elementOuterHeight > viewport.height) { top = targetOffset.top + windowScrollTop - elementOuterHeight; if (top < 0) { top = windowScrollTop; } element.style.transformOrigin = 'bottom'; } else { top = targetOuterHeight + targetOffset.top + windowScrollTop; element.style.transformOrigin = 'top'; } if (targetOffset.left + targetOuterWidth + elementOuterWidth > viewport.width) left = Math.max(0, targetOffset.left + windowScrollLeft + targetOuterWidth - elementOuterWidth);else left = targetOffset.left + windowScrollLeft; element.style.top = top + 'px'; element.style.left = left + 'px'; } } }, { key: "relativePosition", value: function relativePosition(element, target) { if (element) { var elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : this.getHiddenElementDimensions(element); var targetHeight = target.offsetHeight; var targetOffset = target.getBoundingClientRect(); var viewport = this.getViewport(); var top, left; if (targetOffset.top + targetHeight + elementDimensions.height > viewport.height) { top = -1 * elementDimensions.height; if (targetOffset.top + top < 0) { top = -1 * targetOffset.top; } element.style.transformOrigin = 'bottom'; } else { top = targetHeight; element.style.transformOrigin = 'top'; } if (elementDimensions.width > viewport.width) { // element wider then viewport and cannot fit on screen (align at left side of viewport) left = targetOffset.left * -1; } else if (targetOffset.left + elementDimensions.width > viewport.width) { // element wider then viewport but can be fit on screen (align at right side of viewport) left = (targetOffset.left + elementDimensions.width - viewport.width) * -1; } else { // element fits on screen (align with target) left = 0; } element.style.top = top + 'px'; element.style.left = left + 'px'; } } }, { key: "flipfitCollision", value: function flipfitCollision(element, target) { var _this = this; var my = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'left top'; var at = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'left bottom'; var callback = arguments.length > 4 ? arguments[4] : undefined; var targetOffset = target.getBoundingClientRect(); var viewport = this.getViewport(); var myArr = my.split(' '); var atArr = at.split(' '); var getPositionValue = function getPositionValue(arr, isOffset) { return isOffset ? +arr.substring(arr.search(/(\+|-)/g)) || 0 : arr.substring(0, arr.search(/(\+|-)/g)) || arr; }; var position = { my: { x: getPositionValue(myArr[0]), y: getPositionValue(myArr[1] || myArr[0]), offsetX: getPositionValue(myArr[0], true), offsetY: getPositionValue(myArr[1] || myArr[0], true) }, at: { x: getPositionValue(atArr[0]), y: getPositionValue(atArr[1] || atArr[0]), offsetX: getPositionValue(atArr[0], true), offsetY: getPositionValue(atArr[1] || atArr[0], true) } }; var myOffset = { left: function left() { var totalOffset = position.my.offsetX + position.at.offsetX; return totalOffset + targetOffset.left + (position.my.x === 'left' ? 0 : -1 * (position.my.x === 'center' ? _this.getOuterWidth(element) / 2 : _this.getOuterWidth(element))); }, top: function top() { var totalOffset = position.my.offsetY + position.at.offsetY; return totalOffset + targetOffset.top + (position.my.y === 'top' ? 0 : -1 * (position.my.y === 'center' ? _this.getOuterHeight(element) / 2 : _this.getOuterHeight(element))); } }; var alignWithAt = { count: { x: 0, y: 0 }, left: function left() { var left = myOffset.left(); var scrollLeft = DomHandler.getWindowScrollLeft(); element.style.left = left + scrollLeft + 'px'; if (this.count.x === 2) { element.style.left = scrollLeft + 'px'; this.count.x = 0; } else if (left < 0) { this.count.x++; position.my.x = 'left'; position.at.x = 'right'; position.my.offsetX *= -1; position.at.offsetX *= -1; this.right(); } }, right: function right() { var left = myOffset.left() + DomHandler.getOuterWidth(target); var scrollLeft = DomHandler.getWindowScrollLeft(); element.style.left = left + scrollLeft + 'px'; if (this.count.x === 2) { element.style.left = viewport.width - DomHandler.getOuterWidth(element) + scrollLeft + 'px'; this.count.x = 0; } else if (left + DomHandler.getOuterWidth(element) > viewport.width) { this.count.x++; position.my.x = 'right'; position.at.x = 'left'; position.my.offsetX *= -1; position.at.offsetX *= -1; this.left(); } }, top: function top() { var top = myOffset.top(); var scrollTop = DomHandler.getWindowScrollTop(); element.style.top = top + scrollTop + 'px'; if (this.count.y === 2) { element.style.left = scrollTop + 'px'; this.count.y = 0; } else if (top < 0) { this.count.y++; position.my.y = 'top'; position.at.y = 'bottom'; position.my.offsetY *= -1; position.at.offsetY *= -1; this.bottom(); } }, bottom: function bottom() { var top = myOffset.top() + DomHandler.getOuterHeight(target); var scrollTop = DomHandler.getWindowScrollTop(); element.style.top = top + scrollTop + 'px'; if (this.count.y === 2) { element.style.left = viewport.height - DomHandler.getOuterHeight(element) + scrollTop + 'px'; this.count.y = 0; } else if (top + DomHandler.getOuterHeight(target) > viewport.height) { this.count.y++; position.my.y = 'bottom'; position.at.y = 'top'; position.my.offsetY *= -1; position.at.offsetY *= -1; this.top(); } }, center: function center(axis) { if (axis === 'y') { var top = myOffset.top() + DomHandler.getOuterHeight(target) / 2; element.style.top = top + DomHandler.getWindowScrollTop() + 'px'; if (top < 0) { this.bottom(); } else if (top + DomHandler.getOuterHeight(target) > viewport.height) { this.top(); } } else { var left = myOffset.left() + DomHandler.getOuterWidth(target) / 2; element.style.left = left + DomHandler.getWindowScrollLeft() + 'px'; if (left < 0) { this.left(); } else if (left + DomHandler.getOuterWidth(element) > viewport.width) { this.right(); } } } }; alignWithAt[position.at.x]('x'); alignWithAt[position.at.y]('y'); if (this.isFunction(callback)) { callback(position); } } }, { key: "findCollisionPosition", value: function findCollisionPosition(position) { if (position) { var isAxisY = position === 'top' || position === 'bottom'; var myXPosition = position === 'left' ? 'right' : 'left'; var myYPosition = position === 'top' ? 'bottom' : 'top'; if (isAxisY) { return { axis: 'y', my: "center ".concat(myYPosition), at: "center ".concat(position) }; } return { axis: 'x', my: "".concat(myXPosition, " center"), at: "".concat(position, " center") }; } } }, { key: "getParents", value: function getParents(element) { var parents = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return element['parentNode'] === null ? parents : this.getParents(element.parentNode, parents.concat([element.parentNode])); } }, { key: "getScrollableParents", value: function getScrollableParents(element) { var scrollableParents = []; if (element) { var parents = this.getParents(element); var overflowRegex = /(auto|scroll)/; var overflowCheck = function overflowCheck(node) { var styleDeclaration = node ? getComputedStyle(node) : null; return styleDeclaration && (overflowRegex.test(styleDeclaration.getPropertyValue('overflow')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowX')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowY'))); }; var _iterator = _createForOfIteratorHelper$3(parents), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var parent = _step.value; var scrollSelectors = parent.nodeType === 1 && parent.dataset['scrollselectors']; if (scrollSelectors) { var selectors = scrollSelectors.split(','); var _iterator2 = _createForOfIteratorHelper$3(selectors), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var selector = _step2.value; var el = this.findSingle(parent, selector); if (el && overflowCheck(el)) { scrollableParents.push(el); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } if (parent.nodeType !== 9 && overflowCheck(parent)) { scrollableParents.push(parent); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return scrollableParents; } }, { key: "getHiddenElementOuterHeight", value: function getHiddenElementOuterHeight(element) { if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; var elementHeight = element.offsetHeight; element.style.display = 'none'; element.style.visibility = 'visible'; return elementHeight; } return 0; } }, { key: "getHiddenElementOuterWidth", value: function getHiddenElementOuterWidth(element) { if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; var elementWidth = element.offsetWidth; element.style.display = 'none'; element.style.visibility = 'visible'; return elementWidth; } return 0; } }, { key: "getHiddenElementDimensions", value: function getHiddenElementDimensions(element) { var dimensions = {}; if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; dimensions.width = element.offsetWidth; dimensions.height = element.offsetHeight; element.style.display = 'none'; element.style.visibility = 'visible'; } return dimensions; } }, { key: "fadeIn", value: function fadeIn(element, duration) { if (element) { element.style.opacity = 0; var last = +new Date(); var opacity = 0; var tick = function tick() { opacity = +element.style.opacity + (new Date().getTime() - last) / duration; element.style.opacity = opacity; last = +new Date(); if (+opacity < 1) { window.requestAnimationFrame && requestAnimationFrame(tick) || setTimeout(tick, 16); } }; tick(); } } }, { key: "fadeOut", value: function fadeOut(element, duration) { if (element) { var opacity = 1, interval = 50, gap = interval / duration; var fading = setInterval(function () { opacity -= gap; if (opacity <= 0) { opacity = 0; clearInterval(fading); } element.style.opacity = opacity; }, interval); } } }, { key: "getUserAgent", value: function getUserAgent() { return navigator.userAgent; } }, { key: "isIOS", value: function isIOS() { return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window['MSStream']; } }, { key: "isAndroid", value: function isAndroid() { return /(android)/i.test(navigator.userAgent); } }, { key: "isTouchDevice", value: function isTouchDevice() { return 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; } }, { key: "isFunction", value: function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } }, { key: "appendChild", value: function appendChild(element, target) { if (this.isElement(target)) target.appendChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.appendChild(element);else throw new Error('Cannot append ' + target + ' to ' + element); } }, { key: "removeChild", value: function removeChild(element, target) { if (this.isElement(target)) target.removeChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.removeChild(element);else throw new Error('Cannot remove ' + element + ' from ' + target); } }, { key: "isElement", value: function isElement(obj) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? obj instanceof HTMLElement : obj && _typeof(obj) === "object" && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === "string"; } }, { key: "scrollInView", value: function scrollInView(container, item) { var borderTopValue = getComputedStyle(container).getPropertyValue('borderTopWidth'); var borderTop = borderTopValue ? parseFloat(borderTopValue) : 0; var paddingTopValue = getComputedStyle(container).getPropertyValue('paddingTop'); var paddingTop = paddingTopValue ? parseFloat(paddingTopValue) : 0; var containerRect = container.getBoundingClientRect(); var itemRect = item.getBoundingClientRect(); var offset = itemRect.top + document.body.scrollTop - (containerRect.top + document.body.scrollTop) - borderTop - paddingTop; var scroll = container.scrollTop; var elementHeight = container.clientHeight; var itemHeight = this.getOuterHeight(item); if (offset < 0) { container.scrollTop = scroll + offset; } else if (offset + itemHeight > elementHeight) { container.scrollTop = scroll + offset - elementHeight + itemHeight; } } }, { key: "clearSelection", value: function clearSelection() { if (window.getSelection) { if (window.getSelection().empty) { window.getSelection().empty(); } else if (window.getSelection().removeAllRanges && window.getSelection().rangeCount > 0 && window.getSelection().getRangeAt(0).getClientRects().length > 0) { window.getSelection().removeAllRanges(); } } else if (document['selection'] && document['selection'].empty) { try { document['selection'].empty(); } catch (error) {//ignore IE bug } } } }, { key: "calculateScrollbarWidth", value: function calculateScrollbarWidth(el) { if (el) { var style = getComputedStyle(el); return el.offsetWidth - el.clientWidth - parseFloat(style.borderLeftWidth) - parseFloat(style.borderRightWidth); } else { if (this.calculatedScrollbarWidth != null) return this.calculatedScrollbarWidth; var scrollDiv = document.createElement("div"); scrollDiv.className = "p-scrollbar-measure"; document.body.appendChild(scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); this.calculatedScrollbarWidth = scrollbarWidth; return scrollbarWidth; } } }, { key: "getBrowser", value: function getBrowser() { if (!this.browser) { var matched = this.resolveUserAgent(); this.browser = {}; if (matched.browser) { this.browser[matched.browser] = true; this.browser['version'] = matched.version; } if (this.browser['chrome']) { this.browser['webkit'] = true; } else if (this.browser['webkit']) { this.browser['safari'] = true; } } return this.browser; } }, { key: "resolveUserAgent", value: function resolveUserAgent() { var ua = navigator.userAgent.toLowerCase(); var match = /(chrome)[ ]([\w.]+)/.exec(ua) || /(webkit)[ ]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ ]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[1] || "", version: match[2] || "0" }; } }, { key: "isVisible", value: function isVisible(element) { return element && element.offsetParent != null; } }, { key: "isExist", value: function isExist(element) { return element !== null && typeof element !== 'undefined' && element.nodeName && element.parentNode; } }, { key: "hasDOM", value: function hasDOM() { return !!(typeof window !== 'undefined' && window.document && window.document.createElement); } }, { key: "getFocusableElements", value: function getFocusableElements(element) { var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var focusableElements = DomHandler.find(element, "button:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])".concat(selector, ",\n [href][clientHeight][clientWidth]:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n input:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n select:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n textarea:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n [tabIndex]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n [contenteditable]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector)); var visibleFocusableElements = []; var _iterator3 = _createForOfIteratorHelper$3(focusableElements), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var focusableElement = _step3.value; if (getComputedStyle(focusableElement).display !== "none" && getComputedStyle(focusableElement).visibility !== "hidden") visibleFocusableElements.push(focusableElement); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return visibleFocusableElements; } }, { key: "getFirstFocusableElement", value: function getFirstFocusableElement(element, selector) { var focusableElements = DomHandler.getFocusableElements(element, selector); return focusableElements.length > 0 ? focusableElements[0] : null; } }, { key: "getLastFocusableElement", value: function getLastFocusableElement(element, selector) { var focusableElements = DomHandler.getFocusableElements(element, selector); return focusableElements.length > 0 ? focusableElements[focusableElements.length - 1] : null; } }, { key: "getCursorOffset", value: function getCursorOffset(el, prevText, nextText, currentText) { if (el) { var style = getComputedStyle(el); var ghostDiv = document.createElement('div'); ghostDiv.style.position = 'absolute'; ghostDiv.style.top = '0px'; ghostDiv.style.left = '0px'; ghostDiv.style.visibility = 'hidden'; ghostDiv.style.pointerEvents = 'none'; ghostDiv.style.overflow = style.overflow; ghostDiv.style.width = style.width; ghostDiv.style.height = style.height; ghostDiv.style.padding = style.padding; ghostDiv.style.border = style.border; ghostDiv.style.overflowWrap = style.overflowWrap; ghostDiv.style.whiteSpace = style.whiteSpace; ghostDiv.style.lineHeight = style.lineHeight; ghostDiv.innerHTML = prevText.replace(/\r\n|\r|\n/g, '<br />'); var ghostSpan = document.createElement('span'); ghostSpan.textContent = currentText; ghostDiv.appendChild(ghostSpan); var text = document.createTextNode(nextText); ghostDiv.appendChild(text); document.body.appendChild(ghostDiv); var offsetLeft = ghostSpan.offsetLeft, offsetTop = ghostSpan.offsetTop, clientHeight = ghostSpan.clientHeight; document.body.removeChild(ghostDiv); return { left: Math.abs(offsetLeft - el.scrollLeft), top: Math.abs(offsetTop - el.scrollTop) + clientHeight }; } return { top: 'auto', left: 'auto' }; } }, { key: "invokeElementMethod", value: function invokeElementMethod(element, methodName, args) { element[methodName].apply(element, args); } }, { key: "isClickable", value: function isClickable(element) { var targetNode = element.nodeName; var parentNode = element.parentElement && element.parentElement.nodeName; return targetNode === 'INPUT' || targetNode === 'TEXTAREA' || targetNode === 'BUTTON' || targetNode === 'A' || parentNode === 'INPUT' || parentNode === 'TEXTAREA' || parentNode === 'BUTTON' || parentNode === 'A' || this.hasClass(element, 'p-button') || this.hasClass(element.parentElement, 'p-button') || this.hasClass(element.parentElement, 'p-checkbox') || this.hasClass(element.parentElement, 'p-radiobutton'); } }, { key: "applyStyle", value: function applyStyle(element, style) { if (typeof style === 'string') { element.style.cssText = this.style; } else { for (var prop in this.style) { element.style[prop] = style[prop]; } } } }, { key: "exportCSV", value: function exportCSV(csv, filename) { var blob = new Blob([csv], { type: 'application/csv;charset=utf-8;' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob(blob, filename + '.csv'); } else { var link = document.createElement("a"); if (link.download !== undefined) { link.setAttribute('href', URL.createObjectURL(blob)); link.setAttribute('download', filename + '.csv'); link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } else { csv = 'data:text/csv;charset=utf-8,' + csv; window.open(encodeURI(csv)); } } } /** * Anytime an inline style is created check environment variable 'process.env.REACT_APP_CSS_NONCE' * to set a CSP NONCE. * * @see https://github.com/primefaces/primereact/issues/2423 * @return HtmlStyleElement */ }, { key: "createInlineStyle", value: function createInlineStyle() { var styleElement = document.createElement('style'); var nonce = process.env.REACT_APP_CSS_NONCE; if (nonce) { styleElement.setAttribute('nonce', nonce); } document.head.appendChild(styleElement); return styleElement; } /** * Remove a style element from the head and attempt to prevent DOM Exception on fast refresh. * * @see https://github.com/primefaces/primereact/issues/2469 * @param {HtmlStyleElement} styleElement the element to remove from head */ }, { key: "removeInlineStyle", value: function removeInlineStyle(styleElement) { if (this.isExist(styleElement)) { try { document.head.removeChild(styleElement); } catch (error) {// style element may have already been removed in a fast refresh } styleElement = null; } return styleElement; } }]); return DomHandler; }(); function _extends() { _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; }; return _extends.apply(this, arguments); } function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTableBodyCell = /*#__PURE__*/function (_Component) { _inherits(TreeTableBodyCell, _Component); var _super = _createSuper$5(TreeTableBodyCell); function TreeTableBodyCell(props) { var _this; _classCallCheck(this, TreeTableBodyCell); _this = _super.call(this, props); if (_this.props.editor) { _this.state = {}; } _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onEditorFocus = _this.onEditorFocus.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTableBodyCell, [{ key: "onClick", value: function onClick() { var _this2 = this; if (this.props.editor && !this.state.editing && (this.props.selectOnEdit || !this.props.selectOnEdit && this.props.selected)) { this.selfClick = true; this.setState({ editing: true }, function () { _this2.bindDocumentEditListener(); _this2.overlayEventListener = function (e) { if (!_this2.isOutsideClicked(e.target)) { _this2.selfClick = true; } }; OverlayService.on('overlay-click', _this2.overlayEventListener); }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.which === 13 || event.which === 9) { this.switchCellToViewMode(event); } } }, { key: "bindDocumentEditListener", value: function bindDocumentEditListener() { var _this3 = this; if (!this.documentEditListener) { this.documentEditListener = function (e) { if (!_this3.selfClick && _this3.isOutsideClicked(e.target)) { _this3.switchCellToViewMode(e); } _this3.selfClick = false; }; document.addEventListener('click', this.documentEditListener); } } }, { key: "isOutsideClicked", value: function isOutsideClicked(target) { return this.container && !(this.container.isSameNode(target) || this.container.contains(target)); } }, { key: "unbindDocumentEditListener", value: function unbindDocumentEditListener() { if (this.documentEditListener) { document.removeEventListener('click', this.documentEditListener); this.documentEditListener = null; this.selfClick = false; } } }, { key: "closeCell", value: function closeCell() { var _this4 = this; /* When using the 'tab' key, the focus event of the next cell is not called in IE. */ setTimeout(function () { _this4.setState({ editing: false }, function () { _this4.unbindDocumentEditListener(); OverlayService.off('overlay-click', _this4.overlayEventListener); _this4.overlayEventListener = null; }); }, 1); } }, { key: "onEditorFocus", value: function onEditorFocus(event) { this.onClick(event); } }, { key: "switchCellToViewMode", value: function switchCellToViewMode(event) { if (this.props.cellEditValidator) { var valid = this.props.cellEditValidator({ originalEvent: event, columnProps: this.props }); if (valid) { this.closeCell(); } } else { this.closeCell(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate() { var _this5 = this; if (this.container && this.props.editor) { clearTimeout(this.tabindexTimeout); if (this.state && this.state.editing) { var focusable = DomHandler$1.findSingle(this.container, 'input'); if (focusable && document.activeElement !== focusable && !focusable.hasAttribute('data-isCellEditing')) { focusable.setAttribute('data-isCellEditing', true); focusable.focus(); } this.keyHelper.tabIndex = -1; } else { this.tabindexTimeout = setTimeout(function () { if (_this5.keyHelper) { _this5.keyHelper.setAttribute('tabindex', 0); } }, 50); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentEditListener(); if (this.overlayEventListener) { OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } } }, { key: "render", value: function render() { var _this6 = this; var className = classNames(this.props.bodyClassName || this.props.className, { 'p-editable-column': this.props.editor, 'p-cell-editing': this.props.editor ? this.state.editing : false }); var style = this.props.bodyStyle || this.props.style; var content; if (this.state && this.state.editing) { if (this.props.editor) content = ObjectUtils.getJSXElement(this.props.editor, { node: this.props.node, rowData: this.props.node.data, value: ObjectUtils.resolveFieldData(this.props.node.data, this.props.field), field: this.props.field, rowIndex: this.props.rowIndex, props: this.props });else throw new Error("Editor is not found on column."); } else { if (this.props.body) content = ObjectUtils.getJSXElement(this.props.body, this.props.node, { field: this.props.field, rowIndex: this.props.rowIndex, props: this.props });else content = ObjectUtils.resolveFieldData(this.props.node.data, this.props.field); } /* eslint-disable */ var editorKeyHelper = this.props.editor && /*#__PURE__*/React.createElement("a", { tabIndex: 0, ref: function ref(el) { _this6.keyHelper = el; }, className: "p-cell-editor-key-helper p-hidden-accessible", onFocus: this.onEditorFocus }, /*#__PURE__*/React.createElement("span", null)); /* eslint-enable */ return /*#__PURE__*/React.createElement("td", { ref: function ref(el) { return _this6.container = el; }, className: className, style: style, onClick: this.onClick, onKeyDown: this.onKeyDown }, this.props.children, editorKeyHelper, content); } }]); return TreeTableBodyCell; }(Component); function _createForOfIteratorHelper$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); } function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTableRow = /*#__PURE__*/function (_Component) { _inherits(TreeTableRow, _Component); var _super = _createSuper$4(TreeTableRow); function TreeTableRow(props) { var _this; _classCallCheck(this, TreeTableRow); _this = _super.call(this, props); _this.onTogglerClick = _this.onTogglerClick.bind(_assertThisInitialized(_this)); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.propagateUp = _this.propagateUp.bind(_assertThisInitialized(_this)); _this.onCheckboxChange = _this.onCheckboxChange.bind(_assertThisInitialized(_this)); _this.onCheckboxFocus = _this.onCheckboxFocus.bind(_assertThisInitialized(_this)); _this.onCheckboxBlur = _this.onCheckboxBlur.bind(_assertThisInitialized(_this)); _this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTableRow, [{ key: "isLeaf", value: function isLeaf() { return this.props.node.leaf === false ? false : !(this.props.node.children && this.props.node.children.length); } }, { key: "onTogglerClick", value: function onTogglerClick(event) { if (this.isExpanded()) this.collapse(event);else this.expand(event); event.preventDefault(); event.stopPropagation(); } }, { key: "expand", value: function expand(event) { var expandedKeys = this.props.expandedKeys ? _objectSpread$2({}, this.props.expandedKeys) : {}; expandedKeys[this.props.node.key] = true; this.props.onToggle({ originalEvent: event, value: expandedKeys }); this.invokeToggleEvents(event, true); } }, { key: "collapse", value: function collapse(event) { var expandedKeys = _objectSpread$2({}, this.props.expandedKeys); delete expandedKeys[this.props.node.key]; this.props.onToggle({ originalEvent: event, value: expandedKeys }); this.invokeToggleEvents(event, false); } }, { key: "invokeToggleEvents", value: function invokeToggleEvents(event, expanded) { if (expanded) { if (this.props.onExpand) { this.props.onExpand({ originalEvent: event, node: this.props.node }); } } else { if (this.props.onCollapse) { this.props.onCollapse({ originalEvent: event, node: this.props.node }); } } } }, { key: "onClick", value: function onClick(event) { if (this.props.onRowClick) { this.props.onRowClick(event, this.props.node); } this.nodeTouched = false; } }, { key: "onTouchEnd", value: function onTouchEnd() { this.nodeTouched = true; } }, { key: "onCheckboxChange", value: function onCheckboxChange(event) { var checked = this.isChecked(); var selectionKeys = this.props.selectionKeys ? _objectSpread$2({}, this.props.selectionKeys) : {}; if (checked) { if (this.props.propagateSelectionDown) this.propagateDown(this.props.node, false, selectionKeys);else delete selectionKeys[this.props.node.key]; if (this.props.propagateSelectionUp && this.props.onPropagateUp) { this.props.onPropagateUp({ originalEvent: event, check: false, selectionKeys: selectionKeys }); } if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { if (this.props.propagateSelectionDown) this.propagateDown(this.props.node, true, selectionKeys);else selectionKeys[this.props.node.key] = { checked: true }; if (this.props.propagateSelectionUp && this.props.onPropagateUp) { this.props.onPropagateUp({ originalEvent: event, check: true, selectionKeys: selectionKeys }); } if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: event, value: selectionKeys }); } DomHandler$1.clearSelection(); } }, { key: "onCheckboxFocus", value: function onCheckboxFocus() { DomHandler$1.addClass(this.checkboxBox, 'p-focus'); } }, { key: "onCheckboxBlur", value: function onCheckboxBlur() { DomHandler$1.removeClass(this.checkboxBox, 'p-focus'); } }, { key: "propagateUp", value: function propagateUp(event) { var check = event.check; var selectionKeys = event.selectionKeys; var checkedChildCount = 0; var childPartialSelected = false; var _iterator = _createForOfIteratorHelper$2(this.props.node.children), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var child = _step.value; if (selectionKeys[child.key] && selectionKeys[child.key].checked) checkedChildCount++;else if (selectionKeys[child.key] && selectionKeys[child.key].partialChecked) childPartialSelected = true; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (check && checkedChildCount === this.props.node.children.length) { selectionKeys[this.props.node.key] = { checked: true, partialChecked: false }; } else { if (!check) { delete selectionKeys[this.props.node.key]; } if (childPartialSelected || checkedChildCount > 0 && checkedChildCount !== this.props.node.children.length) selectionKeys[this.props.node.key] = { checked: false, partialChecked: true };else selectionKeys[this.props.node.key] = { checked: false, partialChecked: false }; } if (this.props.propagateSelectionUp && this.props.onPropagateUp) { this.props.onPropagateUp(event); } } }, { key: "propagateDown", value: function propagateDown(node, check, selectionKeys) { if (check) selectionKeys[node.key] = { checked: true, partialChecked: false };else delete selectionKeys[node.key]; if (node.children && node.children.length) { for (var i = 0; i < node.children.length; i++) { this.propagateDown(node.children[i], check, selectionKeys); } } } }, { key: "onRightClick", value: function onRightClick(event) { DomHandler$1.clearSelection(); if (this.props.onContextMenuSelectionChange) { this.props.onContextMenuSelectionChange({ originalEvent: event, value: this.props.node.key }); } if (this.props.onContextMenu) { this.props.onContextMenu({ originalEvent: event, node: this.props.node }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.target === this.container) { var rowElement = event.currentTarget; switch (event.which) { //down arrow case 40: var nextRow = rowElement.nextElementSibling; if (nextRow) { nextRow.focus(); } event.preventDefault(); break; //up arrow case 38: var previousRow = rowElement.previousElementSibling; if (previousRow) { previousRow.focus(); } event.preventDefault(); break; //right arrow case 39: if (!this.isExpanded()) { this.expand(event); } event.preventDefault(); break; //left arrow case 37: if (this.isExpanded()) { this.collapse(event); } event.preventDefault(); break; //enter case 13: this.onClick(event); event.preventDefault(); break; } } } }, { key: "isExpanded", value: function isExpanded() { return this.props.expandedKeys ? this.props.expandedKeys[this.props.node.key] !== undefined : false; } }, { key: "isSelected", value: function isSelected() { if ((this.props.selectionMode === 'single' || this.props.selectionMode === 'multiple') && this.props.selectionKeys) return this.props.selectionMode === 'single' ? this.props.selectionKeys === this.props.node.key : this.props.selectionKeys[this.props.node.key] !== undefined;else return false; } }, { key: "isChecked", value: function isChecked() { return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].checked : false; } }, { key: "isPartialChecked", value: function isPartialChecked() { return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].partialChecked : false; } }, { key: "renderToggler", value: function renderToggler() { var expanded = this.isExpanded(); var iconClassName = classNames('"p-treetable-toggler-icon pi pi-fw', { 'pi-chevron-right': !expanded, 'pi-chevron-down': expanded }); var style = { marginLeft: this.props.level * 16 + 'px', visibility: this.props.node.leaf === false || this.props.node.children && this.props.node.children.length ? 'visible' : 'hidden' }; return /*#__PURE__*/React.createElement("button", { type: "button", className: "p-treetable-toggler p-link p-unselectable-text", onClick: this.onTogglerClick, tabIndex: -1, style: style }, /*#__PURE__*/React.createElement("i", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } }, { key: "renderCheckbox", value: function renderCheckbox() { var _this2 = this; if (this.props.selectionMode === 'checkbox' && this.props.node.selectable !== false) { var checked = this.isChecked(); var partialChecked = this.isPartialChecked(); var className = classNames('p-checkbox-box', { 'p-highlight': checked, 'p-indeterminate': partialChecked }); var icon = classNames('p-checkbox-icon p-c', { 'pi pi-check': checked, 'pi pi-minus': partialChecked }); return /*#__PURE__*/React.createElement("div", { className: "p-checkbox p-treetable-checkbox p-component", onClick: this.onCheckboxChange, role: "checkbox", "aria-checked": checked }, /*#__PURE__*/React.createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React.createElement("input", { type: "checkbox", onFocus: this.onCheckboxFocus, onBlur: this.onCheckboxBlur })), /*#__PURE__*/React.createElement("div", { className: className, ref: function ref(el) { return _this2.checkboxBox = el; } }, /*#__PURE__*/React.createElement("span", { className: icon }))); } else { return null; } } }, { key: "renderCell", value: function renderCell(column) { var toggler, checkbox; if (column.props.expander) { toggler = this.renderToggler(); checkbox = this.renderCheckbox(); } return /*#__PURE__*/React.createElement(TreeTableBodyCell, _extends({ key: column.props.columnKey || column.props.field }, column.props, { selectOnEdit: this.props.selectOnEdit, selected: this.isSelected(), node: this.props.node, rowIndex: this.props.rowIndex }), toggler, checkbox); } }, { key: "renderChildren", value: function renderChildren() { var _this3 = this; if (this.isExpanded() && this.props.node.children) { return this.props.node.children.map(function (childNode, index) { return /*#__PURE__*/React.createElement(TreeTableRow, { key: childNode.key || JSON.stringify(childNode.data), level: _this3.props.level + 1, rowIndex: _this3.props.rowIndex + '_' + index, node: childNode, columns: _this3.props.columns, expandedKeys: _this3.props.expandedKeys, selectOnEdit: _this3.props.selectOnEdit, onToggle: _this3.props.onToggle, onExpand: _this3.props.onExpand, onCollapse: _this3.props.onCollapse, selectionMode: _this3.props.selectionMode, selectionKeys: _this3.props.selectionKeys, onSelectionChange: _this3.props.onSelectionChange, metaKeySelection: _this3.props.metaKeySelection, onRowClick: _this3.props.onRowClick, onSelect: _this3.props.onSelect, onUnselect: _this3.props.onUnselect, propagateSelectionUp: _this3.props.propagateSelectionUp, propagateSelectionDown: _this3.props.propagateSelectionDown, onPropagateUp: _this3.propagateUp, rowClassName: _this3.props.rowClassName, contextMenuSelectionKey: _this3.props.contextMenuSelectionKey, onContextMenuSelectionChange: _this3.props.onContextMenuSelectionChange, onContextMenu: _this3.props.onContextMenu }); }); } else { return null; } } }, { key: "render", value: function render() { var _this4 = this; var cells = this.props.columns.map(function (col) { return _this4.renderCell(col); }); var children = this.renderChildren(); var className = { 'p-highlight': this.isSelected(), 'p-highlight-contextmenu': this.props.contextMenuSelectionKey && this.props.contextMenuSelectionKey === this.props.node.key }; if (this.props.rowClassName) { var rowClassName = this.props.rowClassName(this.props.node); className = _objectSpread$2(_objectSpread$2({}, className), rowClassName); } className = classNames(className, this.props.node.className); return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("tr", { ref: function ref(el) { return _this4.container = el; }, tabIndex: 0, className: className, style: this.props.node.style, onClick: this.onClick, onTouchEnd: this.onTouchEnd, onContextMenu: this.onRightClick, onKeyDown: this.onKeyDown }, cells), children); } }]); return TreeTableRow; }(Component); _defineProperty(TreeTableRow, "defaultProps", { node: null, level: null, columns: null, expandedKeys: null, contextMenuSelectionKey: null, selectionMode: null, selectionKeys: null, metaKeySelection: true, propagateSelectionUp: true, propagateSelectionDown: true, rowClassName: null, onExpand: null, onCollapse: null, onToggle: null, onRowClick: null, onSelect: null, onUnselect: null, onSelectionChange: null, onPropagateUp: null, onContextMenuSelectionChange: null, onContextMenu: null }); function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTableBody = /*#__PURE__*/function (_Component) { _inherits(TreeTableBody, _Component); var _super = _createSuper$3(TreeTableBody); function TreeTableBody(props) { var _this; _classCallCheck(this, TreeTableBody); _this = _super.call(this, props); _this.onRowClick = _this.onRowClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTableBody, [{ key: "createRow", value: function createRow(node, index) { return /*#__PURE__*/React.createElement(TreeTableRow, { key: node.key || JSON.stringify(node.data), level: 0, rowIndex: index, selectOnEdit: this.props.selectOnEdit, node: node, columns: this.props.columns, expandedKeys: this.props.expandedKeys, onToggle: this.props.onToggle, onExpand: this.props.onExpand, onCollapse: this.props.onCollapse, selectionMode: this.props.selectionMode, selectionKeys: this.props.selectionKeys, onSelectionChange: this.props.onSelectionChange, metaKeySelection: this.props.metaKeySelection, onRowClick: this.onRowClick, onSelect: this.props.onSelect, onUnselect: this.props.onUnselect, propagateSelectionUp: this.props.propagateSelectionUp, propagateSelectionDown: this.props.propagateSelectionDown, rowClassName: this.props.rowClassName, contextMenuSelectionKey: this.props.contextMenuSelectionKey, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, onContextMenu: this.props.onContextMenu }); } }, { key: "flattenizeTree", value: function flattenizeTree(nodes) { var rows = []; nodes = nodes || this.props.value; var _iterator = _createForOfIteratorHelper$1(nodes), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var node = _step.value; rows.push(node.key); if (this.isExpandedKey(node.key)) { rows = rows.concat(this.flattenizeTree(node.children)); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return rows; } }, { key: "isExpandedKey", value: function isExpandedKey(key) { return this.props.expandedKeys && !!this.props.expandedKeys[key]; } }, { key: "onRowClick", value: function onRowClick(event, node) { var _this2 = this; if (this.props.onRowClick) { this.props.onRowClick({ originalEvent: event, node: node }); } var targetNode = event.target.nodeName; if (targetNode === 'INPUT' || targetNode === 'BUTTON' || targetNode === 'A' || DomHandler.hasClass(event.target, 'p-clickable') || DomHandler.hasClass(event.target, 'p-treetable-toggler') || DomHandler.hasClass(event.target.parentElement, 'p-treetable-toggler')) { return; } if ((this.isSingleSelectionMode() || this.isMultipleSelectionMode()) && node.selectable !== false) { var selectionKeys; var selected = this.isSelected(node); var metaSelection = this.nodeTouched ? false : this.props.metaKeySelection; var flatKeys = this.flattenizeTree(); var rowIndex = flatKeys.findIndex(function (key) { return key === node.key; }); if (this.isMultipleSelectionMode() && event.shiftKey) { DomHandler.clearSelection(); // find first selected row var anchorRowIndex = flatKeys.findIndex(function (key) { return _this2.props.selectionKeys[key]; }); var rangeStart = Math.min(rowIndex, anchorRowIndex); var rangeEnd = Math.max(rowIndex, anchorRowIndex); selectionKeys = _objectSpread$1({}, this.props.selectionKeys); for (var i = rangeStart; i <= rangeEnd; i++) { var rowKey = flatKeys[i]; selectionKeys[rowKey] = true; } } else { this.anchorRowIndex = rowIndex; if (metaSelection) { var metaKey = event.metaKey || event.ctrlKey; if (selected && metaKey) { if (this.isSingleSelectionMode()) { selectionKeys = null; } else { selectionKeys = _objectSpread$1({}, this.props.selectionKeys); delete selectionKeys[node.key]; } if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: node }); } } else { if (this.isSingleSelectionMode()) { selectionKeys = node.key; } else if (this.isMultipleSelectionMode()) { selectionKeys = !metaKey ? {} : this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[node.key] = true; } if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: node }); } } } else { if (this.isSingleSelectionMode()) { if (selected) { selectionKeys = null; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: node }); } } else { selectionKeys = node.key; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: node }); } } } else { if (selected) { selectionKeys = _objectSpread$1({}, this.props.selectionKeys); delete selectionKeys[node.key]; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: node }); } } else { selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[node.key] = true; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: node }); } } } } } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: event, value: selectionKeys }); } } } }, { key: "isSingleSelectionMode", value: function isSingleSelectionMode() { return this.props.selectionMode && this.props.selectionMode === 'single'; } }, { key: "isMultipleSelectionMode", value: function isMultipleSelectionMode() { return this.props.selectionMode && this.props.selectionMode === 'multiple'; } }, { key: "isSelected", value: function isSelected(node) { if ((this.props.selectionMode === 'single' || this.props.selectionMode === 'multiple') && this.props.selectionKeys) return this.props.selectionMode === 'single' ? this.props.selectionKeys === node.key : this.props.selectionKeys[node.key] !== undefined;else return false; } }, { key: "renderRows", value: function renderRows() { var _this3 = this; if (this.props.paginator && !this.props.lazy) { var rpp = this.props.rows || 0; var startIndex = this.props.first || 0; var endIndex = startIndex + rpp; var rows = []; for (var i = startIndex; i < endIndex; i++) { var rowData = this.props.value[i]; if (rowData) rows.push(this.createRow(this.props.value[i]));else break; } return rows; } else { return this.props.value.map(function (node, index) { return _this3.createRow(node, index); }); } } }, { key: "renderEmptyMessage", value: function renderEmptyMessage() { if (this.props.loading) { return null; } else { var colSpan = this.props.columns ? this.props.columns.length : null; var content = this.props.emptyMessage || localeOption('emptyMessage'); return /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("td", { className: "p-treetable-emptymessage", colSpan: colSpan }, content)); } } }, { key: "render", value: function render() { var content = this.props.value && this.props.value.length ? this.renderRows() : this.renderEmptyMessage(); return /*#__PURE__*/React.createElement("tbody", { className: "p-treetable-tbody" }, content); } }]); return TreeTableBody; }(Component); _defineProperty(TreeTableBody, "defaultProps", { value: null, columns: null, expandedKeys: null, contextMenuSelectionKey: null, paginator: false, first: null, rows: null, selectionMode: null, selectionKeys: null, metaKeySelection: true, propagateSelectionUp: true, propagateSelectionDown: true, lazy: false, rowClassName: null, emptyMessage: null, loading: false, onExpand: null, onCollapse: null, onToggle: null, onRowClick: null, onSelect: null, onUnselect: null, onSelectionChange: null, onContextMenuSelectionChange: null, onContextMenu: null }); function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTableFooter = /*#__PURE__*/function (_Component) { _inherits(TreeTableFooter, _Component); var _super = _createSuper$2(TreeTableFooter); function TreeTableFooter() { _classCallCheck(this, TreeTableFooter); return _super.apply(this, arguments); } _createClass(TreeTableFooter, [{ key: "renderFooterCell", value: function renderFooterCell(column, index) { return /*#__PURE__*/React.createElement("td", { key: column.field || index, className: column.props.footerClassName || column.props.className, style: column.props.footerStyle || column.props.style, rowSpan: column.props.rowSpan, colSpan: column.props.colSpan }, column.props.footer); } }, { key: "renderFooterRow", value: function renderFooterRow(row, index) { var _this = this; var rowColumns = React.Children.toArray(row.props.children); var rowFooterCells = rowColumns.map(function (col, index) { return _this.renderFooterCell(col, index); }); return /*#__PURE__*/React.createElement("tr", { key: index }, rowFooterCells); } }, { key: "renderColumnGroup", value: function renderColumnGroup() { var _this2 = this; var rows = React.Children.toArray(this.props.columnGroup.props.children); return rows.map(function (row, i) { return _this2.renderFooterRow(row, i); }); } }, { key: "renderColumns", value: function renderColumns(columns) { var _this3 = this; if (columns) { var headerCells = columns.map(function (col, index) { return _this3.renderFooterCell(col, index); }); return /*#__PURE__*/React.createElement("tr", null, headerCells); } else { return null; } } }, { key: "hasFooter", value: function hasFooter() { if (this.props.columnGroup) { return true; } else { for (var i = 0; i < this.props.columns.length; i++) { if (this.props.columns[i].props.footer) { return true; } } } return false; } }, { key: "render", value: function render() { var content = this.props.columnGroup ? this.renderColumnGroup() : this.renderColumns(this.props.columns); if (this.hasFooter()) { return /*#__PURE__*/React.createElement("tfoot", { className: "p-treetable-tfoot" }, content); } else { return null; } } }]); return TreeTableFooter; }(Component); _defineProperty(TreeTableFooter, "defaultProps", { columns: null, columnGroup: null }); function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTableScrollableView = /*#__PURE__*/function (_Component) { _inherits(TreeTableScrollableView, _Component); var _super = _createSuper$1(TreeTableScrollableView); function TreeTableScrollableView(props) { var _this; _classCallCheck(this, TreeTableScrollableView); _this = _super.call(this, props); _this.onHeaderScroll = _this.onHeaderScroll.bind(_assertThisInitialized(_this)); _this.onBodyScroll = _this.onBodyScroll.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTableScrollableView, [{ key: "componentDidMount", value: function componentDidMount() { this.setScrollHeight(); if (!this.props.frozen) { var scrollBarWidth = DomHandler$1.calculateScrollbarWidth(); this.scrollHeaderBox.style.marginRight = scrollBarWidth + 'px'; if (this.scrollFooterBox) { this.scrollFooterBox.style.marginRight = scrollBarWidth + 'px'; } } else { this.scrollBody.style.paddingBottom = DomHandler$1.calculateScrollbarWidth() + 'px'; } } }, { key: "componentDidUpdate", value: function componentDidUpdate() { this.setScrollHeight(); } }, { key: "setScrollHeight", value: function setScrollHeight() { if (this.props.scrollHeight) { if (this.props.scrollHeight.indexOf('%') !== -1) { var datatableContainer = this.findDataTableContainer(this.container); this.scrollBody.style.visibility = 'hidden'; this.scrollBody.style.height = '100px'; //temporary height to calculate static height var containerHeight = DomHandler$1.getOuterHeight(datatableContainer); var relativeHeight = DomHandler$1.getOuterHeight(datatableContainer.parentElement) * parseInt(this.props.scrollHeight, 10) / 100; var staticHeight = containerHeight - 100; //total height of headers, footers, paginators var scrollBodyHeight = relativeHeight - staticHeight; this.scrollBody.style.height = 'auto'; this.scrollBody.style.maxHeight = scrollBodyHeight + 'px'; this.scrollBody.style.visibility = 'visible'; } else { this.scrollBody.style.maxHeight = this.props.scrollHeight; } } } }, { key: "findDataTableContainer", value: function findDataTableContainer(element) { if (element) { var el = element; while (el && !DomHandler$1.hasClass(el, 'p-treetable')) { el = el.parentElement; } return el; } else { return null; } } }, { key: "onHeaderScroll", value: function onHeaderScroll() { this.scrollHeader.scrollLeft = 0; } }, { key: "onBodyScroll", value: function onBodyScroll() { var frozenView = this.container.previousElementSibling; var frozenScrollBody; if (frozenView) { frozenScrollBody = DomHandler$1.findSingle(frozenView, '.p-treetable-scrollable-body'); } this.scrollHeaderBox.style.marginLeft = -1 * this.scrollBody.scrollLeft + 'px'; if (this.scrollFooterBox) { this.scrollFooterBox.style.marginLeft = -1 * this.scrollBody.scrollLeft + 'px'; } if (frozenScrollBody) { frozenScrollBody.scrollTop = this.scrollBody.scrollTop; } } }, { key: "calculateRowHeight", value: function calculateRowHeight() { var row = DomHandler$1.findSingle(this.scrollTable, 'tr:not(.p-treetable-emptymessage-row)'); if (row) { this.rowHeight = DomHandler$1.getOuterHeight(row); } } }, { key: "renderColGroup", value: function renderColGroup() { if (this.props.columns && this.props.columns.length) { return /*#__PURE__*/React.createElement("colgroup", { className: "p-treetable-scrollable-colgroup" }, this.props.columns.map(function (col, i) { return /*#__PURE__*/React.createElement("col", { key: col.field + '_' + i }); })); } else { return null; } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-treetable-scrollable-view', { 'p-treetable-frozen-view': this.props.frozen, 'p-treetable-unfrozen-view': !this.props.frozen && this.props.frozenWidth }); var width = this.props.frozen ? this.props.frozenWidth : 'calc(100% - ' + this.props.frozenWidth + ')'; var left = this.props.frozen ? null : this.props.frozenWidth; var colGroup = this.renderColGroup(); var scrollableBodyStyle = !this.props.frozen && this.props.scrollHeight ? { overflowY: 'scroll' } : null; return /*#__PURE__*/React.createElement("div", { className: className, style: { width: width, left: left }, ref: function ref(el) { _this2.container = el; } }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-header", ref: function ref(el) { _this2.scrollHeader = el; }, onScroll: this.onHeaderScroll }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-header-box", ref: function ref(el) { _this2.scrollHeaderBox = el; } }, /*#__PURE__*/React.createElement("table", { className: "p-treetable-scrollable-header-table" }, colGroup, this.props.header))), /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-body", ref: function ref(el) { _this2.scrollBody = el; }, style: scrollableBodyStyle, onScroll: this.onBodyScroll }, /*#__PURE__*/React.createElement("table", { ref: function ref(el) { _this2.scrollTable = el; }, style: { top: '0' }, className: "p-treetable-scrollable-body-table" }, colGroup, this.props.body)), /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-footer", ref: function ref(el) { _this2.scrollFooter = el; } }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-footer-box", ref: function ref(el) { _this2.scrollFooterBox = el; } }, /*#__PURE__*/React.createElement("table", { className: "p-treetable-scrollable-footer-table" }, colGroup, this.props.footer)))); } }]); return TreeTableScrollableView; }(Component); _defineProperty(TreeTableScrollableView, "defaultProps", { header: null, body: null, footer: null, columns: null, frozen: null, frozenWidth: null, frozenBody: null }); function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTable = /*#__PURE__*/function (_Component) { _inherits(TreeTable, _Component); var _super = _createSuper(TreeTable); function TreeTable(props) { var _this; _classCallCheck(this, TreeTable); _this = _super.call(this, props); var state = {}; if (!_this.props.onToggle) { _this.state = { expandedKeys: _this.props.expandedKeys }; } if (!_this.props.onPage) { state.first = props.first; state.rows = props.rows; } if (!_this.props.onSort) { state.sortField = props.sortField; state.sortOrder = props.sortOrder; state.multiSortMeta = props.multiSortMeta; } if (!_this.props.onFilter) { state.filters = props.filters; } if (Object.keys(state).length) { _this.state = state; } _this.onToggle = _this.onToggle.bind(_assertThisInitialized(_this)); _this.onPageChange = _this.onPageChange.bind(_assertThisInitialized(_this)); _this.onSort = _this.onSort.bind(_assertThisInitialized(_this)); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onColumnResizeStart = _this.onColumnResizeStart.bind(_assertThisInitialized(_this)); _this.onColumnDragStart = _this.onColumnDragStart.bind(_assertThisInitialized(_this)); _this.onColumnDragOver = _this.onColumnDragOver.bind(_assertThisInitialized(_this)); _this.onColumnDragLeave = _this.onColumnDragLeave.bind(_assertThisInitialized(_this)); _this.onColumnDrop = _this.onColumnDrop.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTable, [{ key: "onToggle", value: function onToggle(event) { if (this.props.onToggle) { this.props.onToggle(event); } else { this.setState({ expandedKeys: event.value }); } } }, { key: "onPageChange", value: function onPageChange(event) { if (this.props.onPage) this.props.onPage(event);else this.setState({ first: event.first, rows: event.rows }); } }, { key: "onSort", value: function onSort(event) { var sortField = event.sortField; var sortOrder = this.props.defaultSortOrder; var multiSortMeta; var eventMeta; this.columnSortable = event.sortable; this.columnSortFunction = event.sortFunction; this.columnField = event.sortField; if (this.props.sortMode === 'multiple') { var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey; multiSortMeta = this.getMultiSortMeta(); if (multiSortMeta && multiSortMeta instanceof Array) { var sortMeta = multiSortMeta.find(function (sortMeta) { return sortMeta.field === sortField; }); sortOrder = sortMeta ? this.getCalculatedSortOrder(sortMeta.order) : sortOrder; } var newMetaData = { field: sortField, order: sortOrder }; if (sortOrder) { if (!multiSortMeta || !metaKey) { multiSortMeta = []; } this.addSortMeta(newMetaData, multiSortMeta); } else if (this.props.removableSort && multiSortMeta) { this.removeSortMeta(newMetaData, multiSortMeta); } eventMeta = { multiSortMeta: multiSortMeta }; } else { sortOrder = this.getSortField() === sortField ? this.getCalculatedSortOrder(this.getSortOrder()) : sortOrder; if (this.props.removableSort) { sortField = sortOrder ? sortField : null; } eventMeta = { sortField: sortField, sortOrder: sortOrder }; } if (this.props.onSort) { this.props.onSort(eventMeta); } else { eventMeta.first = 0; this.setState(eventMeta); } } }, { key: "getCalculatedSortOrder", value: function getCalculatedSortOrder(currentOrder) { return this.props.removableSort ? this.props.defaultSortOrder === currentOrder ? currentOrder * -1 : 0 : currentOrder * -1; } }, { key: "addSortMeta", value: function addSortMeta(meta, multiSortMeta) { var index = -1; for (var i = 0; i < multiSortMeta.length; i++) { if (multiSortMeta[i].field === meta.field) { index = i; break; } } if (index >= 0) multiSortMeta[index] = meta;else multiSortMeta.push(meta); } }, { key: "removeSortMeta", value: function removeSortMeta(meta, multiSortMeta) { var index = -1; for (var i = 0; i < multiSortMeta.length; i++) { if (multiSortMeta[i].field === meta.field) { index = i; break; } } if (index >= 0) { multiSortMeta.splice(index, 1); } multiSortMeta = multiSortMeta.length > 0 ? multiSortMeta : null; } }, { key: "sortSingle", value: function sortSingle(data) { return this.sortNodes(data); } }, { key: "sortNodes", value: function sortNodes(data) { var _this2 = this; var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortable === 'custom' && this.columnSortFunction) { value = this.columnSortFunction({ field: this.getSortField(), order: this.getSortOrder() }); } else { value.sort(function (node1, node2) { var sortField = _this2.getSortField(); var value1 = ObjectUtils.resolveFieldData(node1.data, sortField); var value2 = ObjectUtils.resolveFieldData(node2.data, sortField); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return _this2.getSortOrder() * result; }); for (var i = 0; i < value.length; i++) { if (value[i].children && value[i].children.length) { value[i].children = this.sortNodes(value[i].children); } } } return value; } }, { key: "sortMultiple", value: function sortMultiple(data) { var multiSortMeta = this.getMultiSortMeta(); if (multiSortMeta) return this.sortMultipleNodes(data, multiSortMeta);else return data; } }, { key: "sortMultipleNodes", value: function sortMultipleNodes(data, multiSortMeta) { var _this3 = this; var value = _toConsumableArray(data); value.sort(function (node1, node2) { return _this3.multisortField(node1, node2, multiSortMeta, 0); }); for (var i = 0; i < value.length; i++) { if (value[i].children && value[i].children.length) { value[i].children = this.sortMultipleNodes(value[i].children, multiSortMeta); } } return value; } }, { key: "multisortField", value: function multisortField(node1, node2, multiSortMeta, index) { var value1 = ObjectUtils.resolveFieldData(node1.data, multiSortMeta[index].field); var value2 = ObjectUtils.resolveFieldData(node2.data, multiSortMeta[index].field); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else { if (value1 === value2) { return multiSortMeta.length - 1 > index ? this.multisortField(node1, node2, multiSortMeta, index + 1) : 0; } else { if ((typeof value1 === 'string' || value1 instanceof String) && (typeof value2 === 'string' || value2 instanceof String)) return multiSortMeta[index].order * value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : 1; } } return multiSortMeta[index].order * result; } }, { key: "filter", value: function filter(value, field, mode) { this.onFilter({ value: value, field: field, matchMode: mode }); } }, { key: "onFilter", value: function onFilter(event) { var currentFilters = this.getFilters(); var newFilters = currentFilters ? _objectSpread({}, currentFilters) : {}; if (!this.isFilterBlank(event.value)) newFilters[event.field] = { value: event.value, matchMode: event.matchMode };else if (newFilters[event.field]) delete newFilters[event.field]; if (this.props.onFilter) { this.props.onFilter({ filters: newFilters }); } else { this.setState({ first: 0, filters: newFilters }); } } }, { key: "hasFilter", value: function hasFilter() { var filters = this.getFilters(); return filters && Object.keys(filters).length > 0; } }, { key: "isFilterBlank", value: function isFilterBlank(filter) { if (filter !== null && filter !== undefined) { if (typeof filter === 'string' && filter.trim().length === 0 || filter instanceof Array && filter.length === 0) return true;else return false; } return true; } }, { key: "onColumnResizeStart", value: function onColumnResizeStart(event) { var containerLeft = DomHandler$1.getOffset(this.container).left; this.resizeColumn = event.columnEl; this.resizeColumnProps = event.column; this.columnResizing = true; this.lastResizerHelperX = event.originalEvent.pageX - containerLeft + this.container.scrollLeft; this.bindColumnResizeEvents(); } }, { key: "onColumnResize", value: function onColumnResize(event) { var containerLeft = DomHandler$1.getOffset(this.container).left; DomHandler$1.addClass(this.container, 'p-unselectable-text'); this.resizerHelper.style.height = this.container.offsetHeight + 'px'; this.resizerHelper.style.top = 0 + 'px'; this.resizerHelper.style.left = event.pageX - containerLeft + this.container.scrollLeft + 'px'; this.resizerHelper.style.display = 'block'; } }, { key: "onColumnResizeEnd", value: function onColumnResizeEnd(event) { var delta = this.resizerHelper.offsetLeft - this.lastResizerHelperX; var columnWidth = this.resizeColumn.offsetWidth; var newColumnWidth = columnWidth + delta; var minWidth = this.resizeColumn.style.minWidth || 15; if (columnWidth + delta > parseInt(minWidth, 10)) { if (this.props.columnResizeMode === 'fit') { var nextColumn = this.resizeColumn.nextElementSibling; var nextColumnWidth = nextColumn.offsetWidth - delta; if (newColumnWidth > 15 && nextColumnWidth > 15) { if (this.props.scrollable) { var scrollableView = this.findParentScrollableView(this.resizeColumn); var scrollableBodyTable = DomHandler$1.findSingle(scrollableView, 'table.p-treetable-scrollable-body-table'); var scrollableHeaderTable = DomHandler$1.findSingle(scrollableView, 'table.p-treetable-scrollable-header-table'); var scrollableFooterTable = DomHandler$1.findSingle(scrollableView, 'table.p-treetable-scrollable-footer-table'); var resizeColumnIndex = DomHandler$1.index(this.resizeColumn); this.resizeColGroup(scrollableHeaderTable, resizeColumnIndex, newColumnWidth, nextColumnWidth); this.resizeColGroup(scrollableBodyTable, resizeColumnIndex, newColumnWidth, nextColumnWidth); this.resizeColGroup(scrollableFooterTable, resizeColumnIndex, newColumnWidth, nextColumnWidth); } else { this.resizeColumn.style.width = newColumnWidth + 'px'; if (nextColumn) { nextColumn.style.width = nextColumnWidth + 'px'; } } } } else if (this.props.columnResizeMode === 'expand') { if (this.props.scrollable) { var _scrollableView = this.findParentScrollableView(this.resizeColumn); var _scrollableBodyTable = DomHandler$1.findSingle(_scrollableView, 'table.p-treetable-scrollable-body-table'); var _scrollableHeaderTable = DomHandler$1.findSingle(_scrollableView, 'table.p-treetable-scrollable-header-table'); var _scrollableFooterTable = DomHandler$1.findSingle(_scrollableView, 'table.p-treetable-scrollable-footer-table'); _scrollableBodyTable.style.width = _scrollableBodyTable.offsetWidth + delta + 'px'; _scrollableHeaderTable.style.width = _scrollableHeaderTable.offsetWidth + delta + 'px'; if (_scrollableFooterTable) { _scrollableFooterTable.style.width = _scrollableHeaderTable.offsetWidth + delta + 'px'; } var _resizeColumnIndex = DomHandler$1.index(this.resizeColumn); this.resizeColGroup(_scrollableHeaderTable, _resizeColumnIndex, newColumnWidth, null); this.resizeColGroup(_scrollableBodyTable, _resizeColumnIndex, newColumnWidth, null); this.resizeColGroup(_scrollableFooterTable, _resizeColumnIndex, newColumnWidth, null); } else { this.table.style.width = this.table.offsetWidth + delta + 'px'; this.resizeColumn.style.width = newColumnWidth + 'px'; } } if (this.props.onColumnResizeEnd) { this.props.onColumnResizeEnd({ element: this.resizeColumn, column: this.resizeColumnProps, delta: delta }); } } this.resizerHelper.style.display = 'none'; this.resizeColumn = null; this.resizeColumnProps = null; DomHandler$1.removeClass(this.container, 'p-unselectable-text'); this.unbindColumnResizeEvents(); } }, { key: "findParentScrollableView", value: function findParentScrollableView(column) { if (column) { var parent = column.parentElement; while (parent && !DomHandler$1.hasClass(parent, 'p-treetable-scrollable-view')) { parent = parent.parentElement; } return parent; } else { return null; } } }, { key: "resizeColGroup", value: function resizeColGroup(table, resizeColumnIndex, newColumnWidth, nextColumnWidth) { if (table) { var colGroup = table.children[0].nodeName === 'COLGROUP' ? table.children[0] : null; if (colGroup) { var col = colGroup.children[resizeColumnIndex]; var nextCol = col.nextElementSibling; col.style.width = newColumnWidth + 'px'; if (nextCol && nextColumnWidth) { nextCol.style.width = nextColumnWidth + 'px'; } } else { throw new Error("Scrollable tables require a colgroup to support resizable columns"); } } } }, { key: "bindColumnResizeEvents", value: function bindColumnResizeEvents() { var _this4 = this; this.documentColumnResizeListener = document.addEventListener('mousemove', function (event) { if (_this4.columnResizing) { _this4.onColumnResize(event); } }); this.documentColumnResizeEndListener = document.addEventListener('mouseup', function (event) { if (_this4.columnResizing) { _this4.columnResizing = false; _this4.onColumnResizeEnd(event); } }); } }, { key: "unbindColumnResizeEvents", value: function unbindColumnResizeEvents() { document.removeEventListener('document', this.documentColumnResizeListener); document.removeEventListener('document', this.documentColumnResizeEndListener); } }, { key: "onColumnDragStart", value: function onColumnDragStart(e) { var event = e.originalEvent, column = e.column; if (this.columnResizing) { event.preventDefault(); return; } this.iconWidth = DomHandler$1.getHiddenElementOuterWidth(this.reorderIndicatorUp); this.iconHeight = DomHandler$1.getHiddenElementOuterHeight(this.reorderIndicatorUp); this.draggedColumnEl = this.findParentHeader(event.currentTarget); this.draggedColumn = column; event.dataTransfer.setData('text', 'b'); // Firefox requires this to make dragging possible } }, { key: "onColumnDragOver", value: function onColumnDragOver(e) { var event = e.originalEvent; var dropHeader = this.findParentHeader(event.currentTarget); if (this.props.reorderableColumns && this.draggedColumnEl && dropHeader) { event.preventDefault(); var containerOffset = DomHandler$1.getOffset(this.container); var dropHeaderOffset = DomHandler$1.getOffset(dropHeader); if (this.draggedColumnEl !== dropHeader) { var targetLeft = dropHeaderOffset.left - containerOffset.left; //let targetTop = containerOffset.top - dropHeaderOffset.top; var columnCenter = dropHeaderOffset.left + dropHeader.offsetWidth / 2; this.reorderIndicatorUp.style.top = dropHeaderOffset.top - containerOffset.top - (this.iconHeight - 1) + 'px'; this.reorderIndicatorDown.style.top = dropHeaderOffset.top - containerOffset.top + dropHeader.offsetHeight + 'px'; if (event.pageX > columnCenter) { this.reorderIndicatorUp.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.iconWidth / 2) + 'px'; this.reorderIndicatorDown.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.iconWidth / 2) + 'px'; this.dropPosition = 1; } else { this.reorderIndicatorUp.style.left = targetLeft - Math.ceil(this.iconWidth / 2) + 'px'; this.reorderIndicatorDown.style.left = targetLeft - Math.ceil(this.iconWidth / 2) + 'px'; this.dropPosition = -1; } this.reorderIndicatorUp.style.display = 'block'; this.reorderIndicatorDown.style.display = 'block'; } } } }, { key: "onColumnDragLeave", value: function onColumnDragLeave(e) { var event = e.originalEvent; if (this.props.reorderableColumns && this.draggedColumnEl) { event.preventDefault(); this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; } } }, { key: "onColumnDrop", value: function onColumnDrop(e) { var _this5 = this; var event = e.originalEvent, column = e.column; event.preventDefault(); if (this.draggedColumnEl) { var dragIndex = DomHandler$1.index(this.draggedColumnEl); var dropIndex = DomHandler$1.index(this.findParentHeader(event.currentTarget)); var allowDrop = dragIndex !== dropIndex; if (allowDrop && (dropIndex - dragIndex === 1 && this.dropPosition === -1 || dragIndex - dropIndex === 1 && this.dropPosition === 1)) { allowDrop = false; } if (allowDrop) { var columns = this.state.columnOrder ? this.getColumns() : React.Children.toArray(this.props.children); var isSameColumn = function isSameColumn(col1, col2) { return col1.props.columnKey || col2.props.columnKey ? ObjectUtils.equals(col1, col2, 'props.columnKey') : ObjectUtils.equals(col1, col2, 'props.field'); }; var dragColIndex = columns.findIndex(function (child) { return isSameColumn(child, _this5.draggedColumn); }); var dropColIndex = columns.findIndex(function (child) { return isSameColumn(child, column); }); if (dropColIndex < dragColIndex && this.dropPosition === 1) { dropColIndex++; } if (dropColIndex > dragColIndex && this.dropPosition === -1) { dropColIndex--; } ObjectUtils.reorderArray(columns, dragColIndex, dropColIndex); var columnOrder = []; var _iterator = _createForOfIteratorHelper(columns), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _column = _step.value; columnOrder.push(_column.props.columnKey || _column.props.field); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this.setState({ columnOrder: columnOrder }); if (this.props.onColReorder) { this.props.onColReorder({ dragIndex: dragColIndex, dropIndex: dropColIndex, columns: columns }); } } this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; this.draggedColumnEl.draggable = false; this.draggedColumnEl = null; this.dropPosition = null; } } }, { key: "findParentHeader", value: function findParentHeader(element) { if (element.nodeName === 'TH') { return element; } else { var parent = element.parentElement; while (parent.nodeName !== 'TH') { parent = parent.parentElement; if (!parent) break; } return parent; } } }, { key: "getExpandedKeys", value: function getExpandedKeys() { return this.props.onToggle ? this.props.expandedKeys : this.state.expandedKeys; } }, { key: "getFirst", value: function getFirst() { return this.props.onPage ? this.props.first : this.state.first; } }, { key: "getRows", value: function getRows() { return this.props.onPage ? this.props.rows : this.state.rows; } }, { key: "getSortField", value: function getSortField() { return this.props.onSort ? this.props.sortField : this.state.sortField; } }, { key: "getSortOrder", value: function getSortOrder() { return this.props.onSort ? this.props.sortOrder : this.state.sortOrder; } }, { key: "getMultiSortMeta", value: function getMultiSortMeta() { return this.props.onSort ? this.props.multiSortMeta : this.state.multiSortMeta; } }, { key: "getFilters", value: function getFilters() { return this.props.onFilter ? this.props.filters : this.state.filters; } }, { key: "findColumnByKey", value: function findColumnByKey(columns, key) { if (columns && columns.length) { for (var i = 0; i < columns.length; i++) { var child = columns[i]; if (child.props.columnKey === key || child.props.field === key) { return child; } } } return null; } }, { key: "getColumns", value: function getColumns() { var columns = React.Children.toArray(this.props.children); if (columns && columns.length) { if (this.props.reorderableColumns && this.state.columnOrder) { var orderedColumns = []; var _iterator2 = _createForOfIteratorHelper(this.state.columnOrder), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var columnKey = _step2.value; var column = this.findColumnByKey(columns, columnKey); if (column) { orderedColumns.push(column); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return [].concat(orderedColumns, _toConsumableArray(columns.filter(function (item) { return orderedColumns.indexOf(item) < 0; }))); } else { return columns; } } return null; } }, { key: "getTotalRecords", value: function getTotalRecords(data) { return this.props.lazy ? this.props.totalRecords : data ? data.length : 0; } }, { key: "isSingleSelectionMode", value: function isSingleSelectionMode() { return this.props.selectionMode && this.props.selectionMode === 'single'; } }, { key: "isMultipleSelectionMode", value: function isMultipleSelectionMode() { return this.props.selectionMode && this.props.selectionMode === 'multiple'; } }, { key: "isRowSelectionMode", value: function isRowSelectionMode() { return this.isSingleSelectionMode() || this.isMultipleSelectionMode(); } }, { key: "getFrozenColumns", value: function getFrozenColumns(columns) { var frozenColumns = null; var _iterator3 = _createForOfIteratorHelper(columns), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var col = _step3.value; if (col.props.frozen) { frozenColumns = frozenColumns || []; frozenColumns.push(col); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return frozenColumns; } }, { key: "getScrollableColumns", value: function getScrollableColumns(columns) { var scrollableColumns = null; var _iterator4 = _createForOfIteratorHelper(columns), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var col = _step4.value; if (!col.props.frozen) { scrollableColumns = scrollableColumns || []; scrollableColumns.push(col); } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return scrollableColumns; } }, { key: "filterLocal", value: function filterLocal(value) { var filteredNodes = []; var filters = this.getFilters(); var columns = React.Children.toArray(this.props.children); var isStrictMode = this.props.filterMode === 'strict'; var _iterator5 = _createForOfIteratorHelper(value), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var node = _step5.value; var copyNode = _objectSpread({}, node); var localMatch = true; var globalMatch = false; for (var j = 0; j < columns.length; j++) { var col = columns[j]; var filterMeta = filters ? filters[col.props.field] : null; var filterField = col.props.field; var filterValue = void 0, filterConstraint = void 0, paramsWithoutNode = void 0, options = void 0; //local if (filterMeta) { var filterMatchMode = filterMeta.matchMode || col.props.filterMatchMode || 'startsWith'; filterValue = filterMeta.value; filterConstraint = filterMatchMode === 'custom' ? col.props.filterFunction : FilterService.filters[filterMatchMode]; options = { rowData: node, filters: filters, props: this.props, column: { filterMeta: filterMeta, filterField: filterField, props: col.props } }; paramsWithoutNode = { filterField: filterField, filterValue: filterValue, filterConstraint: filterConstraint, isStrictMode: isStrictMode, options: options }; if (isStrictMode && !(this.findFilteredNodes(copyNode, paramsWithoutNode) || this.isFilterMatched(copyNode, paramsWithoutNode)) || !isStrictMode && !(this.isFilterMatched(copyNode, paramsWithoutNode) || this.findFilteredNodes(copyNode, paramsWithoutNode))) { localMatch = false; } if (!localMatch) { break; } } //global if (this.props.globalFilter && !globalMatch) { var copyNodeForGlobal = _objectSpread({}, copyNode); filterValue = this.props.globalFilter; filterConstraint = FilterService.filters['contains']; paramsWithoutNode = { filterField: filterField, filterValue: filterValue, filterConstraint: filterConstraint, isStrictMode: isStrictMode }; if (isStrictMode && (this.findFilteredNodes(copyNodeForGlobal, paramsWithoutNode) || this.isFilterMatched(copyNodeForGlobal, paramsWithoutNode)) || !isStrictMode && (this.isFilterMatched(copyNodeForGlobal, paramsWithoutNode) || this.findFilteredNodes(copyNodeForGlobal, paramsWithoutNode))) { globalMatch = true; copyNode = copyNodeForGlobal; } } } var matches = localMatch; if (this.props.globalFilter) { matches = localMatch && globalMatch; } if (matches) { filteredNodes.push(copyNode); } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return filteredNodes; } }, { key: "findFilteredNodes", value: function findFilteredNodes(node, paramsWithoutNode) { if (node) { var matched = false; if (node.children) { var childNodes = _toConsumableArray(node.children); node.children = []; var _iterator6 = _createForOfIteratorHelper(childNodes), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var childNode = _step6.value; var copyChildNode = _objectSpread({}, childNode); if (this.isFilterMatched(copyChildNode, paramsWithoutNode)) { matched = true; node.children.push(copyChildNode); } } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } } if (matched) { return true; } } } }, { key: "isFilterMatched", value: function isFilterMatched(node, _ref) { var filterField = _ref.filterField, filterValue = _ref.filterValue, filterConstraint = _ref.filterConstraint, isStrictMode = _ref.isStrictMode, options = _ref.options; var matched = false; var dataFieldValue = ObjectUtils.resolveFieldData(node.data, filterField); if (filterConstraint(dataFieldValue, filterValue, this.props.filterLocale, options)) { matched = true; } if (!matched || isStrictMode && !this.isNodeLeaf(node)) { matched = this.findFilteredNodes(node, { filterField: filterField, filterValue: filterValue, filterConstraint: filterConstraint, isStrictMode: isStrictMode }) || matched; } return matched; } }, { key: "isNodeLeaf", value: function isNodeLeaf(node) { return node.leaf === false ? false : !(node.children && node.children.length); } }, { key: "processValue", value: function processValue() { var data = this.props.value; if (!this.props.lazy) { if (data && data.length) { if (this.getSortField() || this.getMultiSortMeta()) { if (this.props.sortMode === 'single') data = this.sortSingle(data);else if (this.props.sortMode === 'multiple') data = this.sortMultiple(data); } var localFilters = this.getFilters(); if (localFilters || this.props.globalFilter) { data = this.filterLocal(data, localFilters); } } } return data; } }, { key: "createTableHeader", value: function createTableHeader(columns, columnGroup) { return /*#__PURE__*/React.createElement(TreeTableHeader, { columns: columns, columnGroup: columnGroup, tabIndex: this.props.tabIndex, onSort: this.onSort, sortField: this.getSortField(), sortOrder: this.getSortOrder(), multiSortMeta: this.getMultiSortMeta(), resizableColumns: this.props.resizableColumns, onResizeStart: this.onColumnResizeStart, reorderableColumns: this.props.reorderableColumns, onDragStart: this.onColumnDragStart, onDragOver: this.onColumnDragOver, onDragLeave: this.onColumnDragLeave, onDrop: this.onColumnDrop, onFilter: this.onFilter, filters: this.getFilters(), filterDelay: this.props.filterDelay }); } }, { key: "createTableFooter", value: function createTableFooter(columns, columnGroup) { return /*#__PURE__*/React.createElement(TreeTableFooter, { columns: columns, columnGroup: columnGroup }); } }, { key: "createTableBody", value: function createTableBody(value, columns) { return /*#__PURE__*/React.createElement(TreeTableBody, { value: value, columns: columns, expandedKeys: this.getExpandedKeys(), selectOnEdit: this.props.selectOnEdit, onToggle: this.onToggle, onExpand: this.props.onExpand, onCollapse: this.props.onCollapse, paginator: this.props.paginator, first: this.getFirst(), rows: this.getRows(), selectionMode: this.props.selectionMode, selectionKeys: this.props.selectionKeys, onSelectionChange: this.props.onSelectionChange, metaKeySelection: this.props.metaKeySelection, onRowClick: this.props.onRowClick, onSelect: this.props.onSelect, onUnselect: this.props.onUnselect, propagateSelectionUp: this.props.propagateSelectionUp, propagateSelectionDown: this.props.propagateSelectionDown, lazy: this.props.lazy, rowClassName: this.props.rowClassName, emptyMessage: this.props.emptyMessage, loading: this.props.loading, contextMenuSelectionKey: this.props.contextMenuSelectionKey, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, onContextMenu: this.props.onContextMenu }); } }, { key: "createPaginator", value: function createPaginator(position, totalRecords) { var className = classNames('p-paginator-' + position, this.props.paginatorClassName); return /*#__PURE__*/React.createElement(Paginator, { first: this.getFirst(), rows: this.getRows(), pageLinkSize: this.props.pageLinkSize, className: className, onPageChange: this.onPageChange, template: this.props.paginatorTemplate, totalRecords: totalRecords, rowsPerPageOptions: this.props.rowsPerPageOptions, currentPageReportTemplate: this.props.currentPageReportTemplate, leftContent: this.props.paginatorLeft, rightContent: this.props.paginatorRight, alwaysShow: this.props.alwaysShowPaginator, dropdownAppendTo: this.props.paginatorDropdownAppendTo }); } }, { key: "createScrollableView", value: function createScrollableView(value, columns, frozen, headerColumnGroup, footerColumnGroup) { var header = this.createTableHeader(columns, headerColumnGroup); var footer = this.createTableFooter(columns, footerColumnGroup); var body = this.createTableBody(value, columns); return /*#__PURE__*/React.createElement(TreeTableScrollableView, { columns: columns, header: header, body: body, footer: footer, scrollHeight: this.props.scrollHeight, frozen: frozen, frozenWidth: this.props.frozenWidth }); } }, { key: "renderScrollableTable", value: function renderScrollableTable(value) { var columns = this.getColumns(); var frozenColumns = this.getFrozenColumns(columns); var scrollableColumns = frozenColumns ? this.getScrollableColumns(columns) : columns; var frozenView, scrollableView; if (frozenColumns) { frozenView = this.createScrollableView(value, frozenColumns, true, this.props.frozenHeaderColumnGroup, this.props.frozenFooterColumnGroup); } scrollableView = this.createScrollableView(value, scrollableColumns, false, this.props.headerColumnGroup, this.props.footerColumnGroup); return /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-wrapper" }, frozenView, scrollableView); } }, { key: "renderRegularTable", value: function renderRegularTable(value) { var _this6 = this; var columns = this.getColumns(); var header = this.createTableHeader(columns, this.props.headerColumnGroup); var footer = this.createTableFooter(columns, this.props.footerColumnGroup); var body = this.createTableBody(value, columns); return /*#__PURE__*/React.createElement("div", { className: "p-treetable-wrapper" }, /*#__PURE__*/React.createElement("table", { style: this.props.tableStyle, className: this.props.tableClassName, ref: function ref(el) { return _this6.table = el; } }, header, footer, body)); } }, { key: "renderTable", value: function renderTable(value) { if (this.props.scrollable) return this.renderScrollableTable(value);else return this.renderRegularTable(value); } }, { key: "renderLoader", value: function renderLoader() { if (this.props.loading) { var iconClassName = classNames('p-treetable-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-treetable-loading" }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: iconClassName }))); } return null; } }, { key: "render", value: function render() { var _this7 = this; var value = this.processValue(); var className = classNames('p-treetable p-component', { 'p-treetable-hoverable-rows': this.isRowSelectionMode(), 'p-treetable-resizable': this.props.resizableColumns, 'p-treetable-resizable-fit': this.props.resizableColumns && this.props.columnResizeMode === 'fit', 'p-treetable-auto-layout': this.props.autoLayout, 'p-treetable-striped': this.props.stripedRows, 'p-treetable-gridlines': this.props.showGridlines }, this.props.className); var table = this.renderTable(value); var totalRecords = this.getTotalRecords(value); var headerFacet = this.props.header && /*#__PURE__*/React.createElement("div", { className: "p-treetable-header" }, this.props.header); var footerFacet = this.props.footer && /*#__PURE__*/React.createElement("div", { className: "p-treetable-footer" }, this.props.footer); var paginatorTop = this.props.paginator && this.props.paginatorPosition !== 'bottom' && this.createPaginator('top', totalRecords); var paginatorBottom = this.props.paginator && this.props.paginatorPosition !== 'top' && this.createPaginator('bottom', totalRecords); var loader = this.renderLoader(); var resizeHelper = this.props.resizableColumns && /*#__PURE__*/React.createElement("div", { ref: function ref(el) { _this7.resizerHelper = el; }, className: "p-column-resizer-helper", style: { display: 'none' } }); var reorderIndicatorUp = this.props.reorderableColumns && /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this7.reorderIndicatorUp = el; }, className: "pi pi-arrow-down p-datatable-reorder-indicator-up", style: { position: 'absolute', display: 'none' } }); var reorderIndicatorDown = this.props.reorderableColumns && /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this7.reorderIndicatorDown = el; }, className: "pi pi-arrow-up p-datatable-reorder-indicator-down", style: { position: 'absolute', display: 'none' } }); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style, ref: function ref(el) { return _this7.container = el; }, "data-scrollselectors": ".p-treetable-scrollable-body" }, loader, headerFacet, paginatorTop, table, paginatorBottom, footerFacet, resizeHelper, reorderIndicatorUp, reorderIndicatorDown); } }]); return TreeTable; }(Component); _defineProperty(TreeTable, "defaultProps", { id: null, value: null, header: null, footer: null, style: null, className: null, tableStyle: null, tableClassName: null, expandedKeys: null, paginator: false, paginatorPosition: 'bottom', alwaysShowPaginator: true, paginatorClassName: null, paginatorTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', paginatorLeft: null, paginatorRight: null, paginatorDropdownAppendTo: null, pageLinkSize: 5, rowsPerPageOptions: null, currentPageReportTemplate: '({currentPage} of {totalPages})', first: null, rows: null, totalRecords: null, lazy: false, sortField: null, sortOrder: null, multiSortMeta: null, sortMode: 'single', defaultSortOrder: 1, removableSort: false, selectionMode: null, selectionKeys: null, contextMenuSelectionKey: null, metaKeySelection: true, selectOnEdit: true, propagateSelectionUp: true, propagateSelectionDown: true, autoLayout: false, rowClassName: null, loading: false, loadingIcon: 'pi pi-spinner', tabIndex: 0, scrollable: false, scrollHeight: null, reorderableColumns: false, headerColumnGroup: null, footerColumnGroup: null, frozenHeaderColumnGroup: null, frozenFooterColumnGroup: null, frozenWidth: null, resizableColumns: false, columnResizeMode: 'fit', emptyMessage: null, filters: null, globalFilter: null, filterMode: 'lenient', filterDelay: 300, filterLocale: undefined, showGridlines: false, stripedRows: false, onFilter: null, onExpand: null, onCollapse: null, onToggle: null, onPage: null, onSort: null, onSelect: null, onUnselect: null, onRowClick: null, onSelectionChange: null, onContextMenuSelectionChange: null, onColumnResizeEnd: null, onColReorder: null, onContextMenu: null }); export { TreeTable };
ajax/libs/boardgame-io/0.47.9/esm/react.js
cdnjs/cdnjs
import 'nanoid/non-secure'; import './Debug-67a310b2.js'; import 'redux'; import './turn-order-0d61594c.js'; import 'immer'; import 'lodash.isplainobject'; import './reducer-77828ca8.js'; import 'rfc6902'; import './initialize-68f0dc41.js'; import './transport-0079de87.js'; import { C as Client$1 } from './client-472fc509.js'; import 'flatted'; import { M as MCTSBot } from './ai-f28cab02.js'; import { L as LobbyClient } from './client-99609c4d.js'; import React from 'react'; import PropTypes from 'prop-types'; import Cookies from 'react-cookies'; import './base-13e38c3e.js'; import { S as SocketIO, L as Local } from './socketio-b981ab77.js'; import './master-cf52dceb.js'; import 'socket.io-client'; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Client * * boardgame.io React client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} debug - Enables the Debug UI. * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET, * UNDO and REDO. */ function Client(opts) { var _a; let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting..."); loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _a = class WrappedBoard extends React.Component { constructor(props) { super(props); if (debug === undefined) { debug = props.debug; } this.client = Client$1({ game, debug, numPlayers, multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, enhancer, }); } componentDidMount() { this.unsubscribe = this.client.subscribe(() => this.forceUpdate()); this.client.start(); } componentWillUnmount() { this.client.stop(); this.unsubscribe(); } componentDidUpdate(prevProps) { if (this.props.matchID != prevProps.matchID) { this.client.updateMatchID(this.props.matchID); } if (this.props.playerID != prevProps.playerID) { this.client.updatePlayerID(this.props.playerID); } if (this.props.credentials != prevProps.credentials) { this.client.updateCredentials(this.props.credentials); } } render() { const state = this.client.getState(); if (state === null) { return React.createElement(loading); } let _board = null; if (board) { _board = React.createElement(board, { ...state, ...this.props, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, matchID: this.client.matchID, playerID: this.client.playerID, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, log: this.client.log, matchData: this.client.matchData, sendChatMessage: this.client.sendChatMessage, chatMessages: this.client.chatMessages, }); } return React.createElement("div", { className: "bgio-client" }, _board); } }, _a.propTypes = { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string, // Enable / disable the Debug UI. debug: PropTypes.any, }, _a.defaultProps = { matchID: 'default', playerID: null, credentials: null, debug: true, }, _a; } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class _LobbyConnectionImpl { constructor({ server, gameComponents, playerName, playerCredentials, }) { this.client = new LobbyClient({ server }); this.gameComponents = gameComponents; this.playerName = playerName || 'Visitor'; this.playerCredentials = playerCredentials; this.matches = []; } async refresh() { try { this.matches = []; const games = await this.client.listGames(); for (const game of games) { if (!this._getGameComponents(game)) continue; const { matches } = await this.client.listMatches(game); this.matches.push(...matches); } } catch (error) { throw new Error('failed to retrieve list of matches (' + error + ')'); } } _getMatchInstance(matchID) { for (const inst of this.matches) { if (inst['matchID'] === matchID) return inst; } } _getGameComponents(gameName) { for (const comp of this.gameComponents) { if (comp.game.name === gameName) return comp; } } _findPlayer(playerName) { for (const inst of this.matches) { if (inst.players.some((player) => player.name === playerName)) return inst; } } async join(gameName, matchID, playerID) { try { let inst = this._findPlayer(this.playerName); if (inst) { throw new Error('player has already joined ' + inst.matchID); } inst = this._getMatchInstance(matchID); if (!inst) { throw new Error('game instance ' + matchID + ' not found'); } const json = await this.client.joinMatch(gameName, matchID, { playerID, playerName: this.playerName, }); inst.players[Number.parseInt(playerID)].name = this.playerName; this.playerCredentials = json.playerCredentials; } catch (error) { throw new Error('failed to join match ' + matchID + ' (' + error + ')'); } } async leave(gameName, matchID) { try { const inst = this._getMatchInstance(matchID); if (!inst) throw new Error('match instance not found'); for (const player of inst.players) { if (player.name === this.playerName) { await this.client.leaveMatch(gameName, matchID, { playerID: player.id.toString(), credentials: this.playerCredentials, }); delete player.name; delete this.playerCredentials; return; } } throw new Error('player not found in match'); } catch (error) { throw new Error('failed to leave match ' + matchID + ' (' + error + ')'); } } async disconnect() { const inst = this._findPlayer(this.playerName); if (inst) { await this.leave(inst.gameName, inst.matchID); } this.matches = []; this.playerName = 'Visitor'; } async create(gameName, numPlayers) { try { const comp = this._getGameComponents(gameName); if (!comp) throw new Error('game not found'); if (numPlayers < comp.game.minPlayers || numPlayers > comp.game.maxPlayers) throw new Error('invalid number of players ' + numPlayers); await this.client.createMatch(gameName, { numPlayers }); } catch (error) { throw new Error('failed to create match for ' + gameName + ' (' + error + ')'); } } } /** * LobbyConnection * * Lobby model. * * @param {string} server - '<host>:<port>' of the server. * @param {Array} gameComponents - A map of Board and Game objects for the supported games. * @param {string} playerName - The name of the player. * @param {string} playerCredentials - The credentials currently used by the player, if any. * * Returns: * A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances. */ function LobbyConnection(opts) { return new _LobbyConnectionImpl(opts); } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyLoginForm extends React.Component { constructor() { super(...arguments); this.state = { playerName: this.props.playerName, nameErrorMsg: '', }; this.onClickEnter = () => { if (this.state.playerName === '') return; this.props.onEnter(this.state.playerName); }; this.onKeyPress = (event) => { if (event.key === 'Enter') { this.onClickEnter(); } }; this.onChangePlayerName = (event) => { const name = event.target.value.trim(); this.setState({ playerName: name, nameErrorMsg: name.length > 0 ? '' : 'empty player name', }); }; } render() { return (React.createElement("div", null, React.createElement("p", { className: "phase-title" }, "Choose a player name:"), React.createElement("input", { type: "text", value: this.state.playerName, onChange: this.onChangePlayerName, onKeyPress: this.onKeyPress }), React.createElement("span", { className: "buttons" }, React.createElement("button", { className: "buttons", onClick: this.onClickEnter }, "Enter")), React.createElement("br", null), React.createElement("span", { className: "error-msg" }, this.state.nameErrorMsg, React.createElement("br", null)))); } } LobbyLoginForm.defaultProps = { playerName: '', }; /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyMatchInstance extends React.Component { constructor() { super(...arguments); this._createSeat = (player) => { return player.name || '[free]'; }; this._createButtonJoin = (inst, seatId) => (React.createElement("button", { key: 'button-join-' + inst.matchID, onClick: () => this.props.onClickJoin(inst.gameName, inst.matchID, '' + seatId) }, "Join")); this._createButtonLeave = (inst) => (React.createElement("button", { key: 'button-leave-' + inst.matchID, onClick: () => this.props.onClickLeave(inst.gameName, inst.matchID) }, "Leave")); this._createButtonPlay = (inst, seatId) => (React.createElement("button", { key: 'button-play-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, playerID: '' + seatId, numPlayers: inst.players.length, }) }, "Play")); this._createButtonSpectate = (inst) => (React.createElement("button", { key: 'button-spectate-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, numPlayers: inst.players.length, }) }, "Spectate")); this._createInstanceButtons = (inst) => { const playerSeat = inst.players.find((player) => player.name === this.props.playerName); const freeSeat = inst.players.find((player) => !player.name); if (playerSeat && freeSeat) { // already seated: waiting for match to start return this._createButtonLeave(inst); } if (freeSeat) { // at least 1 seat is available return this._createButtonJoin(inst, freeSeat.id); } // match is full if (playerSeat) { return (React.createElement("div", null, [ this._createButtonPlay(inst, playerSeat.id), this._createButtonLeave(inst), ])); } // allow spectating return this._createButtonSpectate(inst); }; } render() { const match = this.props.match; let status = 'OPEN'; if (!match.players.some((player) => !player.name)) { status = 'RUNNING'; } return (React.createElement("tr", { key: 'line-' + match.matchID }, React.createElement("td", { key: 'cell-name-' + match.matchID }, match.gameName), React.createElement("td", { key: 'cell-status-' + match.matchID }, status), React.createElement("td", { key: 'cell-seats-' + match.matchID }, match.players.map((player) => this._createSeat(player)).join(', ')), React.createElement("td", { key: 'cell-buttons-' + match.matchID }, this._createInstanceButtons(match)))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyCreateMatchForm extends React.Component { constructor(props) { super(props); this.state = { selectedGame: 0, numPlayers: 2, }; this._createGameNameOption = (game, idx) => { return (React.createElement("option", { key: 'name-option-' + idx, value: idx }, game.game.name)); }; this._createNumPlayersOption = (idx) => { return (React.createElement("option", { key: 'num-option-' + idx, value: idx }, idx)); }; this._createNumPlayersRange = (game) => { return Array.from({ length: game.maxPlayers + 1 }) .map((_, i) => i) .slice(game.minPlayers); }; this.onChangeNumPlayers = (event) => { this.setState({ numPlayers: Number.parseInt(event.target.value), }); }; this.onChangeSelectedGame = (event) => { const idx = Number.parseInt(event.target.value); this.setState({ selectedGame: idx, numPlayers: this.props.games[idx].game.minPlayers, }); }; this.onClickCreate = () => { this.props.createMatch(this.props.games[this.state.selectedGame].game.name, this.state.numPlayers); }; /* fix min and max number of players */ for (const game of props.games) { const matchDetails = game.game; if (!matchDetails.minPlayers) { matchDetails.minPlayers = 1; } if (!matchDetails.maxPlayers) { matchDetails.maxPlayers = 4; } console.assert(matchDetails.maxPlayers >= matchDetails.minPlayers); } this.state = { selectedGame: 0, numPlayers: props.games[0].game.minPlayers, }; } render() { return (React.createElement("div", null, React.createElement("select", { value: this.state.selectedGame, onChange: (evt) => this.onChangeSelectedGame(evt) }, this.props.games.map((game, index) => this._createGameNameOption(game, index))), React.createElement("span", null, "Players:"), React.createElement("select", { value: this.state.numPlayers, onChange: this.onChangeNumPlayers }, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map((number) => this._createNumPlayersOption(number))), React.createElement("span", { className: "buttons" }, React.createElement("button", { onClick: this.onClickCreate }, "Create")))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ var LobbyPhases; (function (LobbyPhases) { LobbyPhases["ENTER"] = "enter"; LobbyPhases["PLAY"] = "play"; LobbyPhases["LIST"] = "list"; })(LobbyPhases || (LobbyPhases = {})); /** * Lobby * * React lobby component. * * @param {Array} gameComponents - An array of Board and Game objects for the supported games. * @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000'). * If not set, defaults to the server that served the page. * @param {string} gameServer - Address of the game server (for example 'localhost:8001'). * If not set, defaults to the server that served the page. * @param {function} clientFactory - Function that is used to create the game clients. * @param {number} refreshInterval - Interval between server updates (default: 2000ms). * @param {bool} debug - Enable debug information (default: false). * * Returns: * A React component that provides a UI to create, list, join, leave, play or * spectate matches (game instances). */ class Lobby extends React.Component { constructor(props) { super(props); this.state = { phase: LobbyPhases.ENTER, playerName: 'Visitor', runningMatch: null, errorMsg: '', credentialStore: {}, }; this._createConnection = (props) => { const name = this.state.playerName; this.connection = LobbyConnection({ server: props.lobbyServer, gameComponents: props.gameComponents, playerName: name, playerCredentials: this.state.credentialStore[name], }); }; this._updateCredentials = (playerName, credentials) => { this.setState((prevState) => { // clone store or componentDidUpdate will not be triggered const store = Object.assign({}, prevState.credentialStore); store[playerName] = credentials; return { credentialStore: store }; }); }; this._updateConnection = async () => { await this.connection.refresh(); this.forceUpdate(); }; this._enterLobby = (playerName) => { this.setState({ playerName, phase: LobbyPhases.LIST }); }; this._exitLobby = async () => { await this.connection.disconnect(); this.setState({ phase: LobbyPhases.ENTER, errorMsg: '' }); }; this._createMatch = async (gameName, numPlayers) => { try { await this.connection.create(gameName, numPlayers); await this.connection.refresh(); // rerender this.setState({}); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._joinMatch = async (gameName, matchID, playerID) => { try { await this.connection.join(gameName, matchID, playerID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._leaveMatch = async (gameName, matchID) => { try { await this.connection.leave(gameName, matchID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._startMatch = (gameName, matchOpts) => { const gameCode = this.connection._getGameComponents(gameName); if (!gameCode) { this.setState({ errorMsg: 'game ' + gameName + ' not supported', }); return; } let multiplayer = undefined; if (matchOpts.numPlayers > 1) { multiplayer = this.props.gameServer ? SocketIO({ server: this.props.gameServer }) : SocketIO(); } if (matchOpts.numPlayers == 1) { const maxPlayers = gameCode.game.maxPlayers; const bots = {}; for (let i = 1; i < maxPlayers; i++) { bots[i + ''] = MCTSBot; } multiplayer = Local({ bots }); } const app = this.props.clientFactory({ game: gameCode.game, board: gameCode.board, debug: this.props.debug, multiplayer, }); const match = { app: app, matchID: matchOpts.matchID, playerID: matchOpts.numPlayers > 1 ? matchOpts.playerID : '0', credentials: this.connection.playerCredentials, }; this.setState({ phase: LobbyPhases.PLAY, runningMatch: match }); }; this._exitMatch = () => { this.setState({ phase: LobbyPhases.LIST, runningMatch: null }); }; this._getPhaseVisibility = (phase) => { return this.state.phase !== phase ? 'hidden' : 'phase'; }; this.renderMatches = (matches, playerName) => { return matches.map((match) => { const { matchID, gameName, players } = match; return (React.createElement(LobbyMatchInstance, { key: 'instance-' + matchID, match: { matchID, gameName, players: Object.values(players) }, playerName: playerName, onClickJoin: this._joinMatch, onClickLeave: this._leaveMatch, onClickPlay: this._startMatch })); }); }; this._createConnection(this.props); setInterval(this._updateConnection, this.props.refreshInterval); } componentDidMount() { const cookie = Cookies.load('lobbyState') || {}; if (cookie.phase && cookie.phase === LobbyPhases.PLAY) { cookie.phase = LobbyPhases.LIST; } this.setState({ phase: cookie.phase || LobbyPhases.ENTER, playerName: cookie.playerName || 'Visitor', credentialStore: cookie.credentialStore || {}, }); } componentDidUpdate(prevProps, prevState) { const name = this.state.playerName; const creds = this.state.credentialStore[name]; if (prevState.phase !== this.state.phase || prevState.credentialStore[name] !== creds || prevState.playerName !== name) { this._createConnection(this.props); this._updateConnection(); const cookie = { phase: this.state.phase, playerName: name, credentialStore: this.state.credentialStore, }; Cookies.save('lobbyState', cookie, { path: '/' }); } } render() { const { gameComponents, renderer } = this.props; const { errorMsg, playerName, phase, runningMatch } = this.state; if (renderer) { return renderer({ errorMsg, gameComponents, matches: this.connection.matches, phase, playerName, runningMatch, handleEnterLobby: this._enterLobby, handleExitLobby: this._exitLobby, handleCreateMatch: this._createMatch, handleJoinMatch: this._joinMatch, handleLeaveMatch: this._leaveMatch, handleExitMatch: this._exitMatch, handleRefreshMatches: this._updateConnection, handleStartMatch: this._startMatch, }); } return (React.createElement("div", { id: "lobby-view", style: { padding: 50 } }, React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.ENTER) }, React.createElement(LobbyLoginForm, { key: playerName, playerName: playerName, onEnter: this._enterLobby })), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.LIST) }, React.createElement("p", null, "Welcome, ", playerName), React.createElement("div", { className: "phase-title", id: "match-creation" }, React.createElement("span", null, "Create a match:"), React.createElement(LobbyCreateMatchForm, { games: gameComponents, createMatch: this._createMatch })), React.createElement("p", { className: "phase-title" }, "Join a match:"), React.createElement("div", { id: "instances" }, React.createElement("table", null, React.createElement("tbody", null, this.renderMatches(this.connection.matches, playerName))), React.createElement("span", { className: "error-msg" }, errorMsg, React.createElement("br", null))), React.createElement("p", { className: "phase-title" }, "Matches that become empty are automatically deleted.")), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.PLAY) }, runningMatch && (React.createElement(runningMatch.app, { matchID: runningMatch.matchID, playerID: runningMatch.playerID, credentials: runningMatch.credentials })), React.createElement("div", { className: "buttons", id: "match-exit" }, React.createElement("button", { onClick: this._exitMatch }, "Exit match"))), React.createElement("div", { className: "buttons", id: "lobby-exit" }, React.createElement("button", { onClick: this._exitLobby }, "Exit lobby")))); } } Lobby.propTypes = { gameComponents: PropTypes.array.isRequired, lobbyServer: PropTypes.string, gameServer: PropTypes.string, debug: PropTypes.bool, clientFactory: PropTypes.func, refreshInterval: PropTypes.number, }; Lobby.defaultProps = { debug: false, clientFactory: Client, refreshInterval: 2000, }; export { Client, Lobby };
ajax/libs/primereact/7.1.0/blockui/blockui.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, ZIndexUtils, classNames, ObjectUtils } from 'primereact/utils'; import { Portal } from 'primereact/portal'; import PrimeReact from 'primereact/api'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var BlockUI = /*#__PURE__*/function (_Component) { _inherits(BlockUI, _Component); var _super = _createSuper(BlockUI); function BlockUI(props) { var _this; _classCallCheck(this, BlockUI); _this = _super.call(this, props); _this.state = { visible: props.blocked }; _this.block = _this.block.bind(_assertThisInitialized(_this)); _this.unblock = _this.unblock.bind(_assertThisInitialized(_this)); _this.onPortalMounted = _this.onPortalMounted.bind(_assertThisInitialized(_this)); return _this; } _createClass(BlockUI, [{ key: "block", value: function block() { this.setState({ visible: true }); } }, { key: "unblock", value: function unblock() { var _this2 = this; var callback = function callback() { _this2.setState({ visible: false }, function () { _this2.props.fullScreen && DomHandler.removeClass(document.body, 'p-overflow-hidden'); _this2.props.onUnblocked && _this2.props.onUnblocked(); }); }; if (this.mask) { DomHandler.addClass(this.mask, 'p-component-overlay-leave'); this.mask.addEventListener('animationend', function () { ZIndexUtils.clear(_this2.mask); callback(); }); } else { callback(); } } }, { key: "onPortalMounted", value: function onPortalMounted() { if (this.props.fullScreen) { DomHandler.addClass(document.body, 'p-overflow-hidden'); document.activeElement.blur(); } if (this.props.autoZIndex) { var key = this.props.fullScreen ? 'modal' : 'overlay'; ZIndexUtils.set(key, this.mask, PrimeReact.autoZIndex, this.props.baseZIndex || PrimeReact.zIndex[key]); } this.props.onBlocked && this.props.onBlocked(); } }, { key: "renderMask", value: function renderMask() { var _this3 = this; if (this.state.visible) { var className = classNames('p-blockui p-component-overlay p-component-overlay-enter', { 'p-blockui-document': this.props.fullScreen }, this.props.className); var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : null; var mask = /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this3.mask = el; }, className: className, style: this.props.style }, content); return /*#__PURE__*/React.createElement(Portal, { element: mask, appendTo: this.props.fullScreen ? document.body : 'self', onMounted: this.onPortalMounted }); } return null; } }, { key: "componentDidMount", value: function componentDidMount() { if (this.state.visible) { this.block(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (prevProps.blocked !== this.props.blocked) { this.props.blocked ? this.block() : this.unblock(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.props.fullScreen) { DomHandler.removeClass(document.body, 'p-overflow-hidden'); } ZIndexUtils.clear(this.mask); } }, { key: "render", value: function render() { var _this4 = this; var mask = this.renderMask(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this4.container = el; }, id: this.props.id, className: "p-blockui-container" }, this.props.children, mask); } }]); return BlockUI; }(Component); _defineProperty(BlockUI, "defaultProps", { id: null, blocked: false, fullScreen: false, baseZIndex: 0, autoZIndex: true, style: null, className: null, template: null, onBlocked: null, onUnblocked: null }); export { BlockUI };
ajax/libs/primereact/6.5.1/inplace/inplace.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/core'; import { Button } from 'primereact/button'; function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var InplaceDisplay = /*#__PURE__*/function (_Component) { _inherits(InplaceDisplay, _Component); var _super = _createSuper(InplaceDisplay); function InplaceDisplay() { _classCallCheck(this, InplaceDisplay); return _super.apply(this, arguments); } _createClass(InplaceDisplay, [{ key: "render", value: function render() { return this.props.children; } }]); return InplaceDisplay; }(Component); var InplaceContent = /*#__PURE__*/function (_Component2) { _inherits(InplaceContent, _Component2); var _super2 = _createSuper(InplaceContent); function InplaceContent() { _classCallCheck(this, InplaceContent); return _super2.apply(this, arguments); } _createClass(InplaceContent, [{ key: "render", value: function render() { return this.props.children; } }]); return InplaceContent; }(Component); var Inplace = /*#__PURE__*/function (_Component3) { _inherits(Inplace, _Component3); var _super3 = _createSuper(Inplace); function Inplace(props) { var _this; _classCallCheck(this, Inplace); _this = _super3.call(this, props); if (!_this.props.onToggle) { _this.state = { active: false }; } _this.open = _this.open.bind(_assertThisInitialized(_this)); _this.close = _this.close.bind(_assertThisInitialized(_this)); _this.onDisplayKeyDown = _this.onDisplayKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(Inplace, [{ key: "open", value: function open(event) { if (this.props.disabled) { return; } if (this.props.onOpen) { this.props.onOpen(event); } if (this.props.onToggle) { this.props.onToggle({ originalEvent: event, value: true }); } else { this.setState({ active: true }); } } }, { key: "close", value: function close(event) { if (this.props.onClose) { this.props.onClose(event); } if (this.props.onToggle) { this.props.onToggle({ originalEvent: event, value: false }); } else { this.setState({ active: false }); } } }, { key: "onDisplayKeyDown", value: function onDisplayKeyDown(event) { if (event.key === 'Enter') { this.open(event); event.preventDefault(); } } }, { key: "isActive", value: function isActive() { return this.props.onToggle ? this.props.active : this.state.active; } }, { key: "renderDisplay", value: function renderDisplay(content) { var className = classNames('p-inplace-display', { 'p-disabled': this.props.disabled }); return /*#__PURE__*/React.createElement("div", { className: className, onClick: this.open, onKeyDown: this.onDisplayKeyDown, tabIndex: this.props.tabIndex, "aria-label": this.props.ariaLabel }, content); } }, { key: "renderCloseButton", value: function renderCloseButton() { if (this.props.closable) { return /*#__PURE__*/React.createElement(Button, { type: "button", className: "p-inplace-content-close", icon: "pi pi-times", onClick: this.close }); } return null; } }, { key: "renderContent", value: function renderContent(content) { var closeButton = this.renderCloseButton(); return /*#__PURE__*/React.createElement("div", { className: "p-inplace-content" }, content, closeButton); } }, { key: "renderChildren", value: function renderChildren() { var _this2 = this; var active = this.isActive(); return React.Children.map(this.props.children, function (child, i) { if (active && child.type === InplaceContent) { return _this2.renderContent(child); } else if (!active && child.type === InplaceDisplay) { return _this2.renderDisplay(child); } }); } }, { key: "render", value: function render() { var className = classNames('p-inplace p-component', { 'p-inplace-closable': this.props.closable }, this.props.className); return /*#__PURE__*/React.createElement("div", { className: className }, this.renderChildren()); } }]); return Inplace; }(Component); _defineProperty(Inplace, "defaultProps", { style: null, className: null, active: false, closable: false, disabled: false, tabIndex: 0, ariaLabel: null, onOpen: null, onClose: null, onToggle: null }); export { Inplace, InplaceContent, InplaceDisplay };
ajax/libs/material-ui/4.9.2/es/Radio/Radio.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import SwitchBase from '../internal/SwitchBase'; import RadioButtonIcon from './RadioButtonIcon'; import { fade } from '../styles/colorManipulator'; import capitalize from '../utils/capitalize'; import createChainedFunction from '../utils/createChainedFunction'; import withStyles from '../styles/withStyles'; import useRadioGroup from '../RadioGroup/useRadioGroup'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { color: theme.palette.text.secondary }, /* Pseudo-class applied to the root element if `checked={true}`. */ checked: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `color="primary"`. */ colorPrimary: { '&$checked': { color: theme.palette.primary.main, '&:hover': { backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, '&$disabled': { color: theme.palette.action.disabled } }, /* Styles applied to the root element if `color="secondary"`. */ colorSecondary: { '&$checked': { color: theme.palette.secondary.main, '&:hover': { backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, '&$disabled': { color: theme.palette.action.disabled } } }); const defaultCheckedIcon = React.createElement(RadioButtonIcon, { checked: true }); const defaultIcon = React.createElement(RadioButtonIcon, null); const Radio = React.forwardRef(function Radio(props, ref) { const { checked: checkedProp, classes, color = 'secondary', name: nameProp, onChange: onChangeProp, size = 'medium' } = props, other = _objectWithoutPropertiesLoose(props, ["checked", "classes", "color", "name", "onChange", "size"]); const radioGroup = useRadioGroup(); let checked = checkedProp; const onChange = createChainedFunction(onChangeProp, radioGroup && radioGroup.onChange); let name = nameProp; if (radioGroup) { if (typeof checked === 'undefined') { checked = radioGroup.value === props.value; } if (typeof name === 'undefined') { name = radioGroup.name; } } return React.createElement(SwitchBase, _extends({ color: color, type: "radio", icon: React.cloneElement(defaultIcon, { fontSize: size === 'small' ? 'small' : 'default' }), checkedIcon: React.cloneElement(defaultCheckedIcon, { fontSize: size === 'small' ? 'small' : 'default' }), classes: { root: clsx(classes.root, classes[`color${capitalize(color)}`]), checked: classes.checked, disabled: classes.disabled }, name: name, checked: checked, onChange: onChange, ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Radio.propTypes = { /** * If `true`, the component is checked. */ checked: PropTypes.bool, /** * The icon to display when the component is checked. */ checkedIcon: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['primary', 'secondary', 'default']), /** * If `true`, the radio will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the ripple effect will be disabled. */ disableRipple: PropTypes.bool, /** * The icon to display when the component is unchecked. */ icon: PropTypes.node, /** * The id of the `input` element. */ id: PropTypes.string, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the state is changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). * You can pull out the new checked state by accessing `event.target.checked` (boolean). */ onChange: PropTypes.func, /** * If `true`, the `input` element will be required. */ required: PropTypes.bool, /** * The size of the radio. * `small` is equivalent to the dense radio styling. */ size: PropTypes.oneOf(['small', 'medium']), /** * The input component prop `type`. */ type: PropTypes.string, /** * The value of the component. The DOM API casts this to a string. */ value: PropTypes.any } : void 0; export default withStyles(styles, { name: 'MuiRadio' })(Radio);
ajax/libs/react-native-web/0.0.0-c240be407/exports/KeyboardAvoidingView/index.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import View from '../View'; import React from 'react'; var KeyboardAvoidingView = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(KeyboardAvoidingView, _React$Component); function KeyboardAvoidingView() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this; _this.frame = null; _this.onLayout = function (event) { _this.frame = event.nativeEvent.layout; }; return _this; } var _proto = KeyboardAvoidingView.prototype; _proto.relativeKeyboardHeight = function relativeKeyboardHeight(keyboardFrame) { var frame = this.frame; if (!frame || !keyboardFrame) { return 0; } var keyboardY = keyboardFrame.screenY - (this.props.keyboardVerticalOffset || 0); return Math.max(frame.y + frame.height - keyboardY, 0); }; _proto.onKeyboardChange = function onKeyboardChange(event) {}; _proto.render = function render() { var _this$props = this.props, behavior = _this$props.behavior, contentContainerStyle = _this$props.contentContainerStyle, keyboardVerticalOffset = _this$props.keyboardVerticalOffset, rest = _objectWithoutPropertiesLoose(_this$props, ["behavior", "contentContainerStyle", "keyboardVerticalOffset"]); return React.createElement(View, _extends({ onLayout: this.onLayout }, rest)); }; return KeyboardAvoidingView; }(React.Component); export default KeyboardAvoidingView;
ajax/libs/primereact/7.2.0/confirmpopup/confirmpopup.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { DomHandler, ConnectedOverlayScrollHandler, ZIndexUtils, ObjectUtils, IconUtils, classNames } from 'primereact/utils'; import { Button } from 'primereact/button'; import { CSSTransition } from 'primereact/csstransition'; import PrimeReact, { localeOption } from 'primereact/api'; import { OverlayService } from 'primereact/overlayservice'; import { Portal } from 'primereact/portal'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function confirmPopup(props) { var appendTo = props.appendTo || document.body; var confirmPopupWrapper = document.createDocumentFragment(); DomHandler.appendChild(confirmPopupWrapper, appendTo); props = _objectSpread(_objectSpread({}, props), { visible: props.visible === undefined ? true : props.visible }); var confirmPopupEl = /*#__PURE__*/React.createElement(ConfirmPopup, props); ReactDOM.render(confirmPopupEl, confirmPopupWrapper); var updateConfirmPopup = function updateConfirmPopup(newProps) { props = _objectSpread(_objectSpread({}, props), newProps); ReactDOM.render( /*#__PURE__*/React.cloneElement(confirmPopupEl, props), confirmPopupWrapper); }; return { _destroy: function _destroy() { ReactDOM.unmountComponentAtNode(confirmPopupWrapper); }, show: function show() { updateConfirmPopup({ visible: true, onHide: function onHide() { updateConfirmPopup({ visible: false }); // reset } }); }, hide: function hide() { updateConfirmPopup({ visible: false }); }, update: function update(newProps) { updateConfirmPopup(newProps); } }; } var ConfirmPopup = /*#__PURE__*/function (_Component) { _inherits(ConfirmPopup, _Component); var _super = _createSuper(ConfirmPopup); function ConfirmPopup(props) { var _this; _classCallCheck(this, ConfirmPopup); _this = _super.call(this, props); _this.state = { visible: false }; _this.reject = _this.reject.bind(_assertThisInitialized(_this)); _this.accept = _this.accept.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); _this.onCloseClick = _this.onCloseClick.bind(_assertThisInitialized(_this)); _this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this)); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExit = _this.onExit.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); _this.overlayRef = /*#__PURE__*/React.createRef(); _this.acceptBtnRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(ConfirmPopup, [{ key: "acceptLabel", value: function acceptLabel() { return this.props.acceptLabel || localeOption('accept'); } }, { key: "rejectLabel", value: function rejectLabel() { return this.props.rejectLabel || localeOption('reject'); } }, { key: "bindDocumentClickListener", value: function bindDocumentClickListener() { var _this2 = this; if (!this.documentClickListener && this.props.dismissable) { this.documentClickListener = function (event) { if (!_this2.isPanelClicked && _this2.isOutsideClicked(event.target)) { _this2.hide(); } _this2.isPanelClicked = false; }; document.addEventListener('click', this.documentClickListener); } } }, { key: "unbindDocumentClickListener", value: function unbindDocumentClickListener() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this3 = this; if (!this.scrollHandler) { this.scrollHandler = new ConnectedOverlayScrollHandler(this.props.target, function () { if (_this3.state.visible) { _this3.hide(); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindResizeListener", value: function bindResizeListener() { var _this4 = this; if (!this.resizeListener) { this.resizeListener = function () { if (_this4.state.visible && !DomHandler.isTouchDevice()) { _this4.hide(); } }; window.addEventListener('resize', this.resizeListener); } } }, { key: "unbindResizeListener", value: function unbindResizeListener() { if (this.resizeListener) { window.removeEventListener('resize', this.resizeListener); this.resizeListener = null; } } }, { key: "isOutsideClicked", value: function isOutsideClicked(target) { return this.overlayRef && this.overlayRef.current && !(this.overlayRef.current.isSameNode(target) || this.overlayRef.current.contains(target)); } }, { key: "onCloseClick", value: function onCloseClick(event) { this.hide(); event.preventDefault(); } }, { key: "onPanelClick", value: function onPanelClick(event) { this.isPanelClicked = true; OverlayService.emit('overlay-click', { originalEvent: event, target: this.props.target }); } }, { key: "accept", value: function accept() { if (this.props.accept) { this.props.accept(); } this.hide('accept'); } }, { key: "reject", value: function reject() { if (this.props.reject) { this.props.reject(); } this.hide('reject'); } }, { key: "show", value: function show() { var _this5 = this; this.setState({ visible: true }, function () { _this5.overlayEventListener = function (e) { if (!_this5.isOutsideClicked(e.target)) { _this5.isPanelClicked = true; } }; OverlayService.on('overlay-click', _this5.overlayEventListener); }); } }, { key: "hide", value: function hide(result) { var _this6 = this; this.setState({ visible: false }, function () { OverlayService.off('overlay-click', _this6.overlayEventListener); _this6.overlayEventListener = null; if (_this6.props.onHide) { _this6.props.onHide(result); } }); } }, { key: "onEnter", value: function onEnter() { ZIndexUtils.set('overlay', this.overlayRef.current, PrimeReact.autoZIndex, PrimeReact.zIndex['overlay']); this.align(); } }, { key: "onEntered", value: function onEntered() { this.bindDocumentClickListener(); this.bindScrollListener(); this.bindResizeListener(); if (this.acceptBtnRef && this.acceptBtnRef.current) { this.acceptBtnRef.current.focus(); } this.props.onShow && this.props.onShow(); } }, { key: "onExit", value: function onExit() { this.unbindDocumentClickListener(); this.unbindScrollListener(); this.unbindResizeListener(); } }, { key: "onExited", value: function onExited() { ZIndexUtils.clear(this.overlayRef.current); } }, { key: "align", value: function align() { if (this.props.target) { DomHandler.absolutePosition(this.overlayRef.current, this.props.target); var containerOffset = DomHandler.getOffset(this.overlayRef.current); var targetOffset = DomHandler.getOffset(this.props.target); var arrowLeft = 0; if (containerOffset.left < targetOffset.left) { arrowLeft = targetOffset.left - containerOffset.left; } this.overlayRef.current.style.setProperty('--overlayArrowLeft', "".concat(arrowLeft, "px")); if (containerOffset.top < targetOffset.top) { DomHandler.addClass(this.overlayRef.current, 'p-confirm-popup-flipped'); } } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.visible) { this.setState({ visible: true }); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.visible !== this.props.visible) { this.setState({ visible: this.props.visible }); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentClickListener(); this.unbindResizeListener(); if (this.scrollHandler) { this.scrollHandler.destroy(); this.scrollHandler = null; } if (this.overlayEventListener) { OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } ZIndexUtils.clear(this.overlayRef.current); } }, { key: "renderContent", value: function renderContent() { var message = ObjectUtils.getJSXElement(this.props.message, this.props); return /*#__PURE__*/React.createElement("div", { className: "p-confirm-popup-content" }, IconUtils.getJSXIcon(this.props.icon, { className: 'p-confirm-popup-icon' }, { props: this.props }), /*#__PURE__*/React.createElement("span", { className: "p-confirm-popup-message" }, message)); } }, { key: "renderFooter", value: function renderFooter() { var acceptClassName = classNames('p-confirm-popup-accept p-button-sm', this.props.acceptClassName); var rejectClassName = classNames('p-confirm-popup-reject p-button-sm', { 'p-button-text': !this.props.rejectClassName }, this.props.rejectClassName); var content = /*#__PURE__*/React.createElement("div", { className: "p-confirm-popup-footer" }, /*#__PURE__*/React.createElement(Button, { label: this.rejectLabel(), icon: this.props.rejectIcon, className: rejectClassName, onClick: this.reject }), /*#__PURE__*/React.createElement(Button, { ref: this.acceptBtnRef, label: this.acceptLabel(), icon: this.props.acceptIcon, className: acceptClassName, onClick: this.accept })); if (this.props.footer) { var defaultContentOptions = { accept: this.accept, reject: this.reject, className: 'p-confirm-popup-footer', acceptClassName: acceptClassName, rejectClassName: rejectClassName, acceptLabel: this.acceptLabel(), rejectLabel: this.rejectLabel(), element: content, props: this.props }; return ObjectUtils.getJSXElement(this.props.footer, defaultContentOptions); } return content; } }, { key: "renderElement", value: function renderElement() { var className = classNames('p-confirm-popup p-component', this.props.className); var content = this.renderContent(); var footer = this.renderFooter(); return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.overlayRef, classNames: "p-connected-overlay", "in": this.state.visible, timeout: { enter: 120, exit: 100 }, options: this.props.transitionOptions, unmountOnExit: true, onEnter: this.onEnter, onEntered: this.onEntered, onExit: this.onExit, onExited: this.onExited }, /*#__PURE__*/React.createElement("div", { ref: this.overlayRef, id: this.props.id, className: className, style: this.props.style, onClick: this.onPanelClick }, content, footer)); } }, { key: "render", value: function render() { var element = this.renderElement(); return /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: this.props.appendTo, visible: this.props.visible }); } }]); return ConfirmPopup; }(Component); _defineProperty(ConfirmPopup, "defaultProps", { target: null, visible: false, message: null, rejectLabel: null, acceptLabel: null, icon: null, rejectIcon: null, acceptIcon: null, rejectClassName: null, acceptClassName: null, className: null, style: null, appendTo: null, dismissable: true, footer: null, onShow: null, onHide: null, accept: null, reject: null, transitionOptions: null }); export { ConfirmPopup, confirmPopup };
ajax/libs/react-native-web/0.14.7/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AppContainer from './AppContainer'; import invariant from 'fbjs/lib/invariant'; import render, { hydrate } from '../render'; import styleResolver from '../StyleSheet/styleResolver'; import React from 'react'; export default function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? hydrate : render; invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn(React.createElement(AppContainer, { rootTag: rootTag, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)), rootTag, callback); } export function getApplication(RootComponent, initialProps, WrapperComponent) { var element = React.createElement(AppContainer, { rootTag: {}, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = styleResolver.getStyleSheet(); return React.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
ajax/libs/primereact/7.0.0-rc.1/image/image.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { ZIndexUtils, DomHandler, CSSTransition, classNames, ObjectUtils, Portal } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Image = /*#__PURE__*/function (_Component) { _inherits(Image, _Component); var _super = _createSuper(Image); function Image(props) { var _this; _classCallCheck(this, Image); _this = _super.call(this, props); _this.state = { maskVisible: false, previewVisible: false, rotate: 0, scale: 1 }; _this.onImageClick = _this.onImageClick.bind(_assertThisInitialized(_this)); _this.onMaskClick = _this.onMaskClick.bind(_assertThisInitialized(_this)); _this.rotateRight = _this.rotateRight.bind(_assertThisInitialized(_this)); _this.rotateLeft = _this.rotateLeft.bind(_assertThisInitialized(_this)); _this.zoomIn = _this.zoomIn.bind(_assertThisInitialized(_this)); _this.zoomOut = _this.zoomOut.bind(_assertThisInitialized(_this)); _this.onEntering = _this.onEntering.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onPreviewImageClick = _this.onPreviewImageClick.bind(_assertThisInitialized(_this)); _this.onExit = _this.onExit.bind(_assertThisInitialized(_this)); _this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); _this.previewRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Image, [{ key: "onImageClick", value: function onImageClick() { var _this2 = this; if (this.props.preview) { this.setState({ maskVisible: true }); setTimeout(function () { _this2.setState({ previewVisible: true }); }, 25); } } }, { key: "onPreviewImageClick", value: function onPreviewImageClick() { this.previewClick = true; } }, { key: "onMaskClick", value: function onMaskClick() { if (!this.previewClick) { this.setState({ previewVisible: false }); this.setState({ rotate: 0 }); this.setState({ scale: 1 }); } this.previewClick = false; } }, { key: "rotateRight", value: function rotateRight() { this.setState(function (prevState) { return { rotate: prevState.rotate + 90 }; }); this.previewClick = true; } }, { key: "rotateLeft", value: function rotateLeft() { this.setState(function (prevState) { return { rotate: prevState.rotate - 90 }; }); this.previewClick = true; } }, { key: "zoomIn", value: function zoomIn() { this.setState(function (prevState) { return { scale: prevState.scale + 0.1 }; }); this.previewClick = true; } }, { key: "zoomOut", value: function zoomOut() { this.setState(function (prevState) { return { scale: prevState.scale - 0.1 }; }); this.previewClick = true; } }, { key: "onEntering", value: function onEntering() { ZIndexUtils.set('modal', this.mask); } }, { key: "onEntered", value: function onEntered() { if (this.props.onShow) { this.props.onShow(); } } }, { key: "onExit", value: function onExit() { DomHandler.addClass(this.mask, 'p-component-overlay-leave'); } }, { key: "onExiting", value: function onExiting() { if (this.props.onHide) { this.props.onHide(); } } }, { key: "onExited", value: function onExited(el) { ZIndexUtils.clear(el); this.setState({ maskVisible: false }); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.mask) { ZIndexUtils.clear(this.container); } } }, { key: "renderElement", value: function renderElement() { var _this3 = this; var imagePreviewStyle = { transform: 'rotate(' + this.state.rotate + 'deg) scale(' + this.state.scale + ')' }; var zoomDisabled = this.state.scale <= 0.5 || this.state.scale >= 1.5; // const rotateClassName = 'p-image-preview-rotate-' + this.state.rotate; return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this3.mask = el; }, className: "p-image-mask p-component-overlay p-component-overlay-enter", onClick: this.onMaskClick }, /*#__PURE__*/React.createElement("div", { className: "p-image-toolbar" }, /*#__PURE__*/React.createElement("button", { className: "p-image-action p-link", onClick: this.rotateRight, type: "button" }, /*#__PURE__*/React.createElement("i", { className: "pi pi-refresh" })), /*#__PURE__*/React.createElement("button", { className: "p-image-action p-link", onClick: this.rotateLeft, type: "button" }, /*#__PURE__*/React.createElement("i", { className: "pi pi-undo" })), /*#__PURE__*/React.createElement("button", { className: "p-image-action p-link", onClick: this.zoomOut, type: "button", disabled: zoomDisabled }, /*#__PURE__*/React.createElement("i", { className: "pi pi-search-minus" })), /*#__PURE__*/React.createElement("button", { className: "p-image-action p-link", onClick: this.zoomIn, type: "button", disabled: zoomDisabled }, /*#__PURE__*/React.createElement("i", { className: "pi pi-search-plus" })), /*#__PURE__*/React.createElement("button", { className: "p-image-action p-link", type: "button", onClick: this.hidePreview }, /*#__PURE__*/React.createElement("i", { className: "pi pi-times" }))), /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.previewRef, classNames: "p-image-preview", in: this.state.previewVisible, timeout: { enter: 150, exit: 150 }, unmountOnExit: true, onEntering: this.onEntering, onEntered: this.onEntered, onExit: this.onExit, onExiting: this.onExiting, onExited: this.onExited }, /*#__PURE__*/React.createElement("div", { ref: this.previewRef }, /*#__PURE__*/React.createElement("img", { src: this.props.src, className: "p-image-preview", style: imagePreviewStyle, onClick: this.onPreviewImageClick, alt: this.props.alt })))); } }, { key: "render", value: function render() { var _this4 = this; var containerClassName = classNames('p-image p-component', this.props.className, { 'p-image-preview-container': this.props.preview }); var element = this.renderElement(); var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : /*#__PURE__*/React.createElement("i", { className: "p-image-preview-icon pi pi-eye" }); var _this$props = this.props, src = _this$props.src, alt = _this$props.alt, width = _this$props.width, height = _this$props.height; return /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this4.container = el; }, className: containerClassName, style: this.props.style }, /*#__PURE__*/React.createElement("img", { src: src, className: this.props.imageClassName, width: width, height: height, style: this.props.imageStyle, alt: alt }), this.props.preview && /*#__PURE__*/React.createElement("div", { className: "p-image-preview-indicator", onClick: this.onImageClick }, content), this.state.maskVisible && /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: document.body })); } }]); return Image; }(Component); _defineProperty(Image, "defaultProps", { preview: false, className: null, style: null, imageStyle: null, imageClassName: null, template: null, src: null, alt: null, width: null, height: null }); export { Image };
ajax/libs/material-ui/4.9.3/esm/Button/Button.js
cdnjs/cdnjs
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import { fade } from '../styles/colorManipulator'; import ButtonBase from '../ButtonBase'; import capitalize from '../utils/capitalize'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: _extends({}, theme.typography.button, { boxSizing: 'border-box', minWidth: 64, padding: '6px 16px', borderRadius: theme.shape.borderRadius, color: theme.palette.text.primary, transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], { duration: theme.transitions.duration.short }), '&:hover': { textDecoration: 'none', backgroundColor: fade(theme.palette.text.primary, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' }, '&$disabled': { backgroundColor: 'transparent' } }, '&$disabled': { color: theme.palette.action.disabled } }), /* Styles applied to the span element that wraps the children. */ label: { width: '100%', // Ensure the correct width for iOS Safari display: 'inherit', alignItems: 'inherit', justifyContent: 'inherit' }, /* Styles applied to the root element if `variant="text"`. */ text: { padding: '6px 8px' }, /* Styles applied to the root element if `variant="text"` and `color="primary"`. */ textPrimary: { color: theme.palette.primary.main, '&:hover': { backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="text"` and `color="secondary"`. */ textSecondary: { color: theme.palette.secondary.main, '&:hover': { backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="outlined"`. */ outlined: { padding: '5px 15px', border: "1px solid ".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'), '&$disabled': { border: "1px solid ".concat(theme.palette.action.disabledBackground) } }, /* Styles applied to the root element if `variant="outlined"` and `color="primary"`. */ outlinedPrimary: { color: theme.palette.primary.main, border: "1px solid ".concat(fade(theme.palette.primary.main, 0.5)), '&:hover': { border: "1px solid ".concat(theme.palette.primary.main), backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="outlined"` and `color="secondary"`. */ outlinedSecondary: { color: theme.palette.secondary.main, border: "1px solid ".concat(fade(theme.palette.secondary.main, 0.5)), '&:hover': { border: "1px solid ".concat(theme.palette.secondary.main), backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } }, '&$disabled': { border: "1px solid ".concat(theme.palette.action.disabled) } }, /* Styles applied to the root element if `variant="contained"`. */ contained: { color: theme.palette.getContrastText(theme.palette.grey[300]), backgroundColor: theme.palette.grey[300], boxShadow: theme.shadows[2], '&:hover': { backgroundColor: theme.palette.grey.A100, boxShadow: theme.shadows[4], // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { boxShadow: theme.shadows[2], backgroundColor: theme.palette.grey[300] }, '&$disabled': { backgroundColor: theme.palette.action.disabledBackground } }, '&$focusVisible': { boxShadow: theme.shadows[6] }, '&:active': { boxShadow: theme.shadows[8] }, '&$disabled': { color: theme.palette.action.disabled, boxShadow: theme.shadows[0], backgroundColor: theme.palette.action.disabledBackground } }, /* Styles applied to the root element if `variant="contained"` and `color="primary"`. */ containedPrimary: { color: theme.palette.primary.contrastText, backgroundColor: theme.palette.primary.main, '&:hover': { backgroundColor: theme.palette.primary.dark, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: theme.palette.primary.main } } }, /* Styles applied to the root element if `variant="contained"` and `color="secondary"`. */ containedSecondary: { color: theme.palette.secondary.contrastText, backgroundColor: theme.palette.secondary.main, '&:hover': { backgroundColor: theme.palette.secondary.dark, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: theme.palette.secondary.main } } }, /* Styles applied to the root element if `disableElevation={true}`. */ disableElevation: { boxShadow: 'none', '&:hover': { boxShadow: 'none' }, '&$focusVisible': { boxShadow: 'none' }, '&:active': { boxShadow: 'none' }, '&$disabled': { boxShadow: 'none' } }, /* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */ focusVisible: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `color="inherit"`. */ colorInherit: { color: 'inherit', borderColor: 'currentColor' }, /* Styles applied to the root element if `size="small"` and `variant="text"`. */ textSizeSmall: { padding: '4px 5px', fontSize: theme.typography.pxToRem(13) }, /* Styles applied to the root element if `size="large"` and `variant="text"`. */ textSizeLarge: { padding: '8px 11px', fontSize: theme.typography.pxToRem(15) }, /* Styles applied to the root element if `size="small"` and `variant="outlined"`. */ outlinedSizeSmall: { padding: '3px 9px', fontSize: theme.typography.pxToRem(13) }, /* Styles applied to the root element if `size="large"` and `variant="outlined"`. */ outlinedSizeLarge: { padding: '7px 21px', fontSize: theme.typography.pxToRem(15) }, /* Styles applied to the root element if `size="small"` and `variant="contained"`. */ containedSizeSmall: { padding: '4px 10px', fontSize: theme.typography.pxToRem(13) }, /* Styles applied to the root element if `size="large"` and `variant="contained"`. */ containedSizeLarge: { padding: '8px 22px', fontSize: theme.typography.pxToRem(15) }, /* Styles applied to the root element if `size="small"`. */ sizeSmall: {}, /* Styles applied to the root element if `size="large"`. */ sizeLarge: {}, /* Styles applied to the root element if `fullWidth={true}`. */ fullWidth: { width: '100%' }, /* Styles applied to the startIcon element if supplied. */ startIcon: { display: 'inherit', marginRight: 8, marginLeft: -4, '&$iconSizeSmall': { marginLeft: -2 } }, /* Styles applied to the endIcon element if supplied. */ endIcon: { display: 'inherit', marginRight: -4, marginLeft: 8, '&$iconSizeSmall': { marginRight: -2 } }, /* Styles applied to the icon element if supplied and `size="small"`. */ iconSizeSmall: { '& > *:first-child': { fontSize: 18 } }, /* Styles applied to the icon element if supplied and `size="medium"`. */ iconSizeMedium: { '& > *:first-child': { fontSize: 20 } }, /* Styles applied to the icon element if supplied and `size="large"`. */ iconSizeLarge: { '& > *:first-child': { fontSize: 22 } } }; }; var Button = React.forwardRef(function Button(props, ref) { var children = props.children, classes = props.classes, className = props.className, _props$color = props.color, color = _props$color === void 0 ? 'default' : _props$color, _props$component = props.component, component = _props$component === void 0 ? 'button' : _props$component, _props$disabled = props.disabled, disabled = _props$disabled === void 0 ? false : _props$disabled, _props$disableElevati = props.disableElevation, disableElevation = _props$disableElevati === void 0 ? false : _props$disableElevati, _props$disableFocusRi = props.disableFocusRipple, disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi, endIconProp = props.endIcon, focusVisibleClassName = props.focusVisibleClassName, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$size = props.size, size = _props$size === void 0 ? 'medium' : _props$size, startIconProp = props.startIcon, _props$type = props.type, type = _props$type === void 0 ? 'button' : _props$type, _props$variant = props.variant, variant = _props$variant === void 0 ? 'text' : _props$variant, other = _objectWithoutProperties(props, ["children", "classes", "className", "color", "component", "disabled", "disableElevation", "disableFocusRipple", "endIcon", "focusVisibleClassName", "fullWidth", "size", "startIcon", "type", "variant"]); var startIcon = startIconProp && React.createElement("span", { className: clsx(classes.startIcon, classes["iconSize".concat(capitalize(size))]) }, startIconProp); var endIcon = endIconProp && React.createElement("span", { className: clsx(classes.endIcon, classes["iconSize".concat(capitalize(size))]) }, endIconProp); return React.createElement(ButtonBase, _extends({ className: clsx(classes.root, classes[variant], className, color === 'inherit' ? classes.colorInherit : color !== 'default' && classes["".concat(variant).concat(capitalize(color))], size !== 'medium' && [classes["".concat(variant, "Size").concat(capitalize(size))], classes["size".concat(capitalize(size))]], disableElevation && classes.disableElevation, disabled && classes.disabled, fullWidth && classes.fullWidth), component: component, disabled: disabled, focusRipple: !disableFocusRipple, focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName), ref: ref, type: type }, other), React.createElement("span", { className: classes.label }, startIcon, children, endIcon)); }); process.env.NODE_ENV !== "production" ? Button.propTypes = { /** * The content of the button. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']), /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, the button will be disabled. */ disabled: PropTypes.bool, /** * If `true`, no elevation is used. */ disableElevation: PropTypes.bool, /** * If `true`, the keyboard focus ripple will be disabled. * `disableRipple` must also be true. */ disableFocusRipple: PropTypes.bool, /** * If `true`, the ripple effect will be disabled. * * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure * to highlight the element by applying separate styles with the `focusVisibleClassName`. */ disableRipple: PropTypes.bool, /** * Element placed after the children. */ endIcon: PropTypes.node, /** * @ignore */ focusVisibleClassName: PropTypes.string, /** * If `true`, the button will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The URL to link to when the button is clicked. * If defined, an `a` element will be used as the root node. */ href: PropTypes.string, /** * The size of the button. * `small` is equivalent to the dense button styling. */ size: PropTypes.oneOf(['small', 'medium', 'large']), /** * Element placed before the children. */ startIcon: PropTypes.node, /** * @ignore */ type: PropTypes.string, /** * The variant to use. */ variant: PropTypes.oneOf(['text', 'outlined', 'contained']) } : void 0; export default withStyles(styles, { name: 'MuiButton' })(Button);
ajax/libs/react-native-web/0.16.2/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
function _extends() { _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; }; return _extends.apply(this, arguments); } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AppContainer from './AppContainer'; import invariant from 'fbjs/lib/invariant'; import render, { hydrate } from '../render'; import styleResolver from '../StyleSheet/styleResolver'; import React from 'react'; export default function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? hydrate : render; invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn( /*#__PURE__*/React.createElement(AppContainer, { WrapperComponent: WrapperComponent, rootTag: rootTag }, /*#__PURE__*/React.createElement(RootComponent, initialProps)), rootTag, callback); } export function getApplication(RootComponent, initialProps, WrapperComponent) { var element = /*#__PURE__*/React.createElement(AppContainer, { WrapperComponent: WrapperComponent, rootTag: {} }, /*#__PURE__*/React.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = styleResolver.getStyleSheet(); return /*#__PURE__*/React.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
ajax/libs/primereact/6.5.0/captcha/captcha.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Captcha = /*#__PURE__*/function (_Component) { _inherits(Captcha, _Component); var _super = _createSuper(Captcha); function Captcha() { _classCallCheck(this, Captcha); return _super.apply(this, arguments); } _createClass(Captcha, [{ key: "init", value: function init() { var _this = this; this._instance = window.grecaptcha.render(this.targetEL, { 'sitekey': this.props.siteKey, 'theme': this.props.theme, 'type': this.props.type, 'size': this.props.size, 'tabindex': this.props.tabIndex, 'hl': this.props.language, 'callback': function callback(response) { _this.recaptchaCallback(response); }, 'expired-callback': function expiredCallback() { _this.recaptchaExpiredCallback(); } }); } }, { key: "reset", value: function reset() { if (this._instance === null) return; window.grecaptcha.reset(this._instance); } }, { key: "getResponse", value: function getResponse() { if (this._instance === null) return null; return window.grecaptcha.getResponse(this._instance); } }, { key: "recaptchaCallback", value: function recaptchaCallback(response) { if (this.props.onResponse) { this.props.onResponse({ response: response }); } } }, { key: "recaptchaExpiredCallback", value: function recaptchaExpiredCallback() { if (this.props.onExpire) { this.props.onExpire(); } } }, { key: "addRecaptchaScript", value: function addRecaptchaScript() { var _this2 = this; this.recaptchaScript = null; if (!window.grecaptcha) { var head = document.head || document.getElementsByTagName('head')[0]; this.recaptchaScript = document.createElement('script'); this.recaptchaScript.src = "https://www.google.com/recaptcha/api.js?render=explicit"; this.recaptchaScript.async = true; this.recaptchaScript.defer = true; this.recaptchaScript.onload = function () { if (!window.grecaptcha) { console.warn("Recaptcha is not loaded"); return; } window.grecaptcha.ready(function () { _this2.init(); }); }; head.appendChild(this.recaptchaScript); } } }, { key: "componentDidMount", value: function componentDidMount() { this.addRecaptchaScript(); if (window.grecaptcha) { this.init(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.recaptchaScript) { this.recaptchaScript.parentNode.removeChild(this.recaptchaScript); } } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/React.createElement("div", { id: this.props.id, ref: function ref(el) { return _this3.targetEL = el; } }); } }]); return Captcha; }(Component); _defineProperty(Captcha, "defaultProps", { id: null, siteKey: null, theme: "light", type: "image", size: "normal", tabIndex: 0, language: "en", onResponse: null, onExpire: null }); export { Captcha };
ajax/libs/material-ui/4.11.0/es/utils/createSvgIcon.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import SvgIcon from '../SvgIcon'; /** * Private module reserved for @material-ui/x packages. */ export default function createSvgIcon(path, displayName) { const Component = (props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({ ref: ref }, props), path); if (process.env.NODE_ENV !== 'production') { // Need to set `displayName` on the inner component for React.memo. // React prior to 16.14 ignores `displayName` on the wrapper. Component.displayName = `${displayName}Icon`; } Component.muiName = SvgIcon.muiName; return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component)); }
ajax/libs/react-native-web/0.11.4/exports/AppRegistry/AppContainer.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import { any, node } from 'prop-types'; import React, { Component } from 'react'; var AppContainer = /*#__PURE__*/ function (_Component) { _inheritsLoose(AppContainer, _Component); function AppContainer() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _Component.call.apply(_Component, [this].concat(args)) || this; _this.state = { mainKey: 1 }; return _this; } var _proto = AppContainer.prototype; _proto.getChildContext = function getChildContext() { return { rootTag: this.props.rootTag }; }; _proto.render = function render() { var _this$props = this.props, children = _this$props.children, WrapperComponent = _this$props.WrapperComponent; var innerView = React.createElement(View, { children: children, key: this.state.mainKey, pointerEvents: "box-none", style: styles.appContainer }); if (WrapperComponent) { innerView = React.createElement(WrapperComponent, null, innerView); } return React.createElement(View, { pointerEvents: "box-none", style: styles.appContainer }, innerView); }; return AppContainer; }(Component); AppContainer.childContextTypes = { rootTag: any }; export { AppContainer as default }; AppContainer.propTypes = process.env.NODE_ENV !== "production" ? { WrapperComponent: any, children: node, rootTag: any.isRequired } : {}; var styles = StyleSheet.create({ appContainer: { flex: 1 } });
ajax/libs/react-native-web/0.0.0-a55272399/exports/ScrollView/index.js
cdnjs/cdnjs
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 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 _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import createReactClass from 'create-react-class'; import dismissKeyboard from '../../modules/dismissKeyboard'; import invariant from 'fbjs/lib/invariant'; import ScrollResponder from '../../modules/ScrollResponder'; import ScrollViewBase from './ScrollViewBase'; import StyleSheet from '../StyleSheet'; import View from '../View'; import React from 'react'; var emptyObject = {}; /* eslint-disable react/prefer-es6-class */ var ScrollView = createReactClass({ displayName: "ScrollView", mixins: [ScrollResponder.Mixin], getInitialState: function getInitialState() { return this.scrollResponderMixinGetInitialState(); }, flashScrollIndicators: function flashScrollIndicators() { this.scrollResponderFlashScrollIndicators(); }, setNativeProps: function setNativeProps(props) { if (this._scrollNodeRef) { this._scrollNodeRef.setNativeProps(props); } }, /** * Returns a reference to the underlying scroll responder, which supports * operations like `scrollTo`. All ScrollView-like components should * implement this method so that they can be composed while providing access * to the underlying scroll responder's methods. */ getScrollResponder: function getScrollResponder() { return this; }, getScrollableNode: function getScrollableNode() { return this._scrollNodeRef; }, getInnerViewNode: function getInnerViewNode() { return this._innerViewRef; }, /** * Scrolls to a given x, y offset, either immediately or with a smooth animation. * Syntax: * * scrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true}) * * Note: The weird argument signature is due to the fact that, for historical reasons, * the function also accepts separate arguments as as alternative to the options object. * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED. */ scrollTo: function scrollTo(y, x, animated) { if (typeof y === 'number') { console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.'); } else { var _ref = y || emptyObject; x = _ref.x; y = _ref.y; animated = _ref.animated; } this.getScrollResponder().scrollResponderScrollTo({ x: x || 0, y: y || 0, animated: animated !== false }); }, /** * If this is a vertical ScrollView scrolls to the bottom. * If this is a horizontal ScrollView scrolls to the right. * * Use `scrollToEnd({ animated: true })` for smooth animated scrolling, * `scrollToEnd({ animated: false })` for immediate scrolling. * If no options are passed, `animated` defaults to true. */ scrollToEnd: function scrollToEnd(options) { // Default to true var animated = (options && options.animated) !== false; var horizontal = this.props.horizontal; var scrollResponder = this.getScrollResponder(); var scrollResponderNode = scrollResponder.scrollResponderGetScrollableNode(); var x = horizontal ? scrollResponderNode.scrollWidth : 0; var y = horizontal ? 0 : scrollResponderNode.scrollHeight; scrollResponder.scrollResponderScrollTo({ x: x, y: y, animated: animated }); }, render: function render() { var _this$props = this.props, contentContainerStyle = _this$props.contentContainerStyle, horizontal = _this$props.horizontal, onContentSizeChange = _this$props.onContentSizeChange, refreshControl = _this$props.refreshControl, stickyHeaderIndices = _this$props.stickyHeaderIndices, pagingEnabled = _this$props.pagingEnabled, keyboardDismissMode = _this$props.keyboardDismissMode, onScroll = _this$props.onScroll, other = _objectWithoutPropertiesLoose(_this$props, ["contentContainerStyle", "horizontal", "onContentSizeChange", "refreshControl", "stickyHeaderIndices", "pagingEnabled", "keyboardDismissMode", "onScroll"]); if (process.env.NODE_ENV !== 'production' && this.props.style) { var style = StyleSheet.flatten(this.props.style); var childLayoutProps = ['alignItems', 'justifyContent'].filter(function (prop) { return style && style[prop] !== undefined; }); invariant(childLayoutProps.length === 0, "ScrollView child layout (" + JSON.stringify(childLayoutProps) + ") " + 'must be applied through the contentContainerStyle prop.'); } var contentSizeChangeProps = {}; if (onContentSizeChange) { contentSizeChangeProps = { onLayout: this._handleContentOnLayout }; } var hasStickyHeaderIndices = !horizontal && Array.isArray(stickyHeaderIndices); var children = hasStickyHeaderIndices || pagingEnabled ? React.Children.map(this.props.children, function (child, i) { var isSticky = hasStickyHeaderIndices && stickyHeaderIndices.indexOf(i) > -1; if (child != null && (isSticky || pagingEnabled)) { return React.createElement(View, { style: StyleSheet.compose(isSticky && styles.stickyHeader, pagingEnabled && styles.pagingEnabledChild) }, child); } else { return child; } }) : this.props.children; var contentContainer = React.createElement(View, _extends({}, contentSizeChangeProps, { children: children, collapsable: false, ref: this._setInnerViewRef, style: StyleSheet.compose(horizontal && styles.contentContainerHorizontal, contentContainerStyle) })); var baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical; var pagingEnabledStyle = horizontal ? styles.pagingEnabledHorizontal : styles.pagingEnabledVertical; var props = _objectSpread({}, other, { style: [baseStyle, pagingEnabled && pagingEnabledStyle, this.props.style], onTouchStart: this.scrollResponderHandleTouchStart, onTouchMove: this.scrollResponderHandleTouchMove, onTouchEnd: this.scrollResponderHandleTouchEnd, onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag, onScrollEndDrag: this.scrollResponderHandleScrollEndDrag, onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin, onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd, onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder, onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture, onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder, onScroll: this._handleScroll, onResponderGrant: this.scrollResponderHandleResponderGrant, onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest, onResponderTerminate: this.scrollResponderHandleTerminate, onResponderRelease: this.scrollResponderHandleResponderRelease, onResponderReject: this.scrollResponderHandleResponderReject }); var ScrollViewClass = ScrollViewBase; invariant(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined'); if (refreshControl) { return React.cloneElement(refreshControl, { style: props.style }, React.createElement(ScrollViewClass, _extends({}, props, { ref: this._setScrollNodeRef, style: baseStyle }), contentContainer)); } return React.createElement(ScrollViewClass, _extends({}, props, { ref: this._setScrollNodeRef }), contentContainer); }, _handleContentOnLayout: function _handleContentOnLayout(e) { var _e$nativeEvent$layout = e.nativeEvent.layout, width = _e$nativeEvent$layout.width, height = _e$nativeEvent$layout.height; this.props.onContentSizeChange(width, height); }, _handleScroll: function _handleScroll(e) { if (process.env.NODE_ENV !== 'production') { if (this.props.onScroll && this.props.scrollEventThrottle == null) { console.log('You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + "cause frame drops, use a bigger number if you don't need as " + 'much precision.'); } } if (this.props.keyboardDismissMode === 'on-drag') { dismissKeyboard(); } this.scrollResponderHandleScroll(e); }, _setInnerViewRef: function _setInnerViewRef(component) { this._innerViewRef = component; }, _setScrollNodeRef: function _setScrollNodeRef(component) { this._scrollNodeRef = component; } }); var commonStyle = { flexGrow: 1, flexShrink: 1, // Enable hardware compositing in modern browsers. // Creates a new layer with its own backing surface that can significantly // improve scroll performance. transform: [{ translateZ: 0 }], // iOS native scrolling WebkitOverflowScrolling: 'touch' }; var styles = StyleSheet.create({ baseVertical: _objectSpread({}, commonStyle, { flexDirection: 'column', overflowX: 'hidden', overflowY: 'auto' }), baseHorizontal: _objectSpread({}, commonStyle, { flexDirection: 'row', overflowX: 'auto', overflowY: 'hidden' }), contentContainerHorizontal: { flexDirection: 'row' }, stickyHeader: { position: 'sticky', top: 0, zIndex: 10 }, pagingEnabledHorizontal: { scrollSnapType: 'x mandatory' }, pagingEnabledVertical: { scrollSnapType: 'y mandatory' }, pagingEnabledChild: { scrollSnapAlign: 'start' } }); export default ScrollView;
ajax/libs/primereact/6.5.0-rc.1/panelmenu/panelmenu.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { UniqueComponentId, classNames, ObjectUtils } from 'primereact/utils'; import { CSSTransition } from 'primereact/csstransition'; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } var propTypes = {exports: {}}; /** * 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$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; /** * 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 = ReactPropTypesSecret_1; function emptyFunction() {} function emptyFunctionWithReset() {} emptyFunctionWithReset.resetWarningCache = emptyFunction; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } var err = 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' ); err.name = 'Invariant Violation'; throw err; } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, elementType: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim, checkPropTypes: emptyFunctionWithReset, resetWarningCache: emptyFunction }; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /** * 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. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod propTypes.exports = factoryWithThrowingShims(); } var PropTypes = propTypes.exports; function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var PanelMenuSub = /*#__PURE__*/function (_Component) { _inherits(PanelMenuSub, _Component); var _super = _createSuper(PanelMenuSub); function PanelMenuSub(props) { var _this; _classCallCheck(this, PanelMenuSub); _this = _super.call(this, props); _this.state = { activeItem: _this.findActiveItem() }; return _this; } _createClass(PanelMenuSub, [{ key: "onItemClick", value: function onItemClick(event, item) { if (item.disabled) { event.preventDefault(); return; } if (!item.url) { event.preventDefault(); } if (item.command) { item.command({ originalEvent: event, item: item }); } var activeItem = this.state.activeItem; var active = this.isItemActive(item); if (active) { item.expanded = false; this.setState({ activeItem: this.props.multiple ? activeItem.filter(function (a_item) { return a_item !== item; }) : null }); } else { if (!this.props.multiple && activeItem) { activeItem.expanded = false; } item.expanded = true; this.setState({ activeItem: this.props.multiple ? [].concat(_toConsumableArray(activeItem || []), [item]) : item }); } } }, { key: "findActiveItem", value: function findActiveItem() { if (this.props.model) { if (this.props.multiple) { return this.props.model.filter(function (item) { return item.expanded; }); } else { var activeItem = null; this.props.model.forEach(function (item) { if (item.expanded) { if (!activeItem) activeItem = item;else item.expanded = false; } }); return activeItem; } } return null; } }, { key: "isItemActive", value: function isItemActive(item) { return this.state.activeItem && (this.props.multiple ? this.state.activeItem.indexOf(item) > -1 : this.state.activeItem === item); } }, { key: "renderSeparator", value: function renderSeparator(index) { return /*#__PURE__*/React.createElement("li", { key: 'separator_' + index, className: "p-menu-separator" }); } }, { key: "renderSubmenu", value: function renderSubmenu(item, active) { var submenuWrapperClassName = classNames('p-toggleable-content', { 'p-toggleable-content-collapsed': !active }); var submenuContentRef = /*#__PURE__*/React.createRef(); if (item.items) { return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: submenuContentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, in: active, unmountOnExit: true }, /*#__PURE__*/React.createElement("div", { ref: submenuContentRef, className: submenuWrapperClassName }, /*#__PURE__*/React.createElement(PanelMenuSub, { model: item.items, multiple: this.props.multiple }))); } return null; } }, { key: "renderMenuitem", value: function renderMenuitem(item, index) { var _this2 = this; var active = this.isItemActive(item); var className = classNames('p-menuitem', item.className); var linkClassName = classNames('p-menuitem-link', { 'p-disabled': item.disabled }); var iconClassName = classNames('p-menuitem-icon', item.icon); var submenuIconClassName = classNames('p-panelmenu-icon pi pi-fw', { 'pi-angle-right': !active, 'pi-angle-down': active }); var icon = item.icon && /*#__PURE__*/React.createElement("span", { className: iconClassName }); var label = item.label && /*#__PURE__*/React.createElement("span", { className: "p-menuitem-text" }, item.label); var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", { className: submenuIconClassName }); var submenu = this.renderSubmenu(item, active); var content = /*#__PURE__*/React.createElement("a", { href: item.url || '#', className: linkClassName, target: item.target, onClick: function onClick(event) { return _this2.onItemClick(event, item, index); }, role: "menuitem", "aria-disabled": item.disabled }, submenuIcon, icon, label); if (item.template) { var defaultContentOptions = { onClick: function onClick(event) { return _this2.onItemClick(event, item, index); }, className: linkClassName, labelClassName: 'p-menuitem-text', iconClassName: iconClassName, submenuIconClassName: submenuIconClassName, element: content, props: this.props, leaf: !item.items, active: active }; content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions); } return /*#__PURE__*/React.createElement("li", { key: item.label + '_' + index, className: className, style: item.style, role: "none" }, content, submenu); } }, { key: "renderItem", value: function renderItem(item, index) { if (item.separator) return this.renderSeparator(index);else return this.renderMenuitem(item, index); } }, { key: "renderMenu", value: function renderMenu() { var _this3 = this; if (this.props.model) { return this.props.model.map(function (item, index) { return _this3.renderItem(item, index); }); } return null; } }, { key: "render", value: function render() { var className = classNames('p-submenu-list', this.props.className); var menu = this.renderMenu(); return /*#__PURE__*/React.createElement("ul", { className: className, role: "tree" }, menu); } }]); return PanelMenuSub; }(Component); _defineProperty(PanelMenuSub, "defaultProps", { model: null, multiple: false }); _defineProperty(PanelMenuSub, "propTypes", { model: PropTypes.any, multiple: PropTypes.bool }); var PanelMenu = /*#__PURE__*/function (_Component2) { _inherits(PanelMenu, _Component2); var _super2 = _createSuper(PanelMenu); function PanelMenu(props) { var _this4; _classCallCheck(this, PanelMenu); _this4 = _super2.call(this, props); _this4.state = { id: props.id, activeItem: _this4.findActiveItem() }; return _this4; } _createClass(PanelMenu, [{ key: "onItemClick", value: function onItemClick(event, item) { if (item.disabled) { event.preventDefault(); return; } if (!item.url) { event.preventDefault(); } if (item.command) { item.command({ originalEvent: event, item: item }); } var activeItem = this.state.activeItem; var active = this.isItemActive(item); if (active) { item.expanded = false; this.setState({ activeItem: this.props.multiple ? activeItem.filter(function (a_item) { return a_item !== item; }) : null }); } else { if (!this.props.multiple && activeItem) { activeItem.expanded = false; } item.expanded = true; this.setState({ activeItem: this.props.multiple ? [].concat(_toConsumableArray(activeItem || []), [item]) : item }); } } }, { key: "findActiveItem", value: function findActiveItem() { if (this.props.model) { if (this.props.multiple) { return this.props.model.filter(function (item) { return item.expanded; }); } else { var activeItem = null; this.props.model.forEach(function (item) { if (item.expanded) { if (!activeItem) activeItem = item;else item.expanded = false; } }); return activeItem; } } return null; } }, { key: "isItemActive", value: function isItemActive(item) { return this.state.activeItem && (this.props.multiple ? this.state.activeItem.indexOf(item) > -1 : this.state.activeItem === item); } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } } }, { key: "renderPanel", value: function renderPanel(item, index) { var _this5 = this; var active = this.isItemActive(item); var className = classNames('p-panelmenu-panel', item.className); var headerClassName = classNames('p-component p-panelmenu-header', { 'p-highlight': active, 'p-disabled': item.disabled }); var submenuIconClassName = classNames('p-panelmenu-icon pi', { 'pi-chevron-right': !active, ' pi-chevron-down': active }); var iconClassName = classNames('p-menuitem-icon', item.icon); var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", { className: submenuIconClassName }); var itemIcon = item.icon && /*#__PURE__*/React.createElement("span", { className: iconClassName }); var label = item.label && /*#__PURE__*/React.createElement("span", { className: "p-menuitem-text" }, item.label); var contentWrapperClassName = classNames('p-toggleable-content', { 'p-toggleable-content-collapsed': !active }); var menuContentRef = /*#__PURE__*/React.createRef(); var content = /*#__PURE__*/React.createElement("a", { href: item.url || '#', className: "p-panelmenu-header-link", onClick: function onClick(e) { return _this5.onItemClick(e, item); }, "aria-expanded": active, id: this.state.id + '_header', "aria-controls": this.state.id + 'content', "aria-disabled": item.disabled }, submenuIcon, itemIcon, label); if (item.template) { var defaultContentOptions = { onClick: function onClick(event) { return _this5.onItemClick(event, item); }, className: 'p-panelmenu-header-link', labelClassName: 'p-menuitem-text', submenuIconClassName: submenuIconClassName, iconClassName: iconClassName, element: content, props: this.props, leaf: !item.items, active: active }; content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions); } return /*#__PURE__*/React.createElement("div", { key: item.label + '_' + index, className: className, style: item.style }, /*#__PURE__*/React.createElement("div", { className: headerClassName, style: item.style }, content), /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: menuContentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, in: active, unmountOnExit: true, options: this.props.transitionOptions }, /*#__PURE__*/React.createElement("div", { ref: menuContentRef, className: contentWrapperClassName, role: "region", id: this.state.id + '_content', "aria-labelledby": this.state.id + '_header' }, /*#__PURE__*/React.createElement("div", { className: "p-panelmenu-content" }, /*#__PURE__*/React.createElement(PanelMenuSub, { model: item.items, className: "p-panelmenu-root-submenu", multiple: this.props.multiple }))))); } }, { key: "renderPanels", value: function renderPanels() { var _this6 = this; if (this.props.model) { return this.props.model.map(function (item, index) { return _this6.renderPanel(item, index); }); } return null; } }, { key: "render", value: function render() { var className = classNames('p-panelmenu p-component', this.props.className); var panels = this.renderPanels(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style }, panels); } }]); return PanelMenu; }(Component); _defineProperty(PanelMenu, "defaultProps", { id: null, model: null, style: null, className: null, multiple: false, transitionOptions: null }); _defineProperty(PanelMenu, "propTypes", { id: PropTypes.string, model: PropTypes.array, style: PropTypes.object, className: PropTypes.string, multiple: PropTypes.bool, transitionOptions: PropTypes.object }); export { PanelMenu };
ajax/libs/primereact/7.1.0/row/row.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Row = /*#__PURE__*/function (_Component) { _inherits(Row, _Component); var _super = _createSuper(Row); function Row() { _classCallCheck(this, Row); return _super.apply(this, arguments); } _createClass(Row, [{ key: "render", value: function render() { return /*#__PURE__*/React.createElement("tr", null, this.props.children); } }]); return Row; }(Component); _defineProperty(Row, "defaultProps", { style: null, className: null }); export { Row };
ajax/libs/react-native-web/0.15.3/exports/createElement/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import createDOMProps from '../../modules/createDOMProps'; import React from 'react'; var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = createDOMProps(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return ( /*#__PURE__*/ React.createElement.apply(React, [Component, domProps].concat(children)) ); }; export default createElement;
ajax/libs/material-ui/4.9.2/esm/TextareaAutosize/TextareaAutosize.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import debounce from '../utils/debounce'; import useForkRef from '../utils/useForkRef'; function getStyleValue(computedStyle, property) { return parseInt(computedStyle[property], 10) || 0; } var useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect; var styles = { /* Styles applied to the shadow textarea element. */ shadow: { // Visibility needed to hide the extra text area on iPads visibility: 'hidden', // Remove from the content flow position: 'absolute', // Ignore the scrollbar width overflow: 'hidden', height: 0, top: 0, left: 0, // Create a new layer, increase the isolation of the computed values transform: 'translateZ(0)' } }; var TextareaAutosize = React.forwardRef(function TextareaAutosize(props, ref) { var onChange = props.onChange, rows = props.rows, rowsMax = props.rowsMax, _props$rowsMin = props.rowsMin, rowsMinProp = _props$rowsMin === void 0 ? 1 : _props$rowsMin, style = props.style, value = props.value, other = _objectWithoutProperties(props, ["onChange", "rows", "rowsMax", "rowsMin", "style", "value"]); var rowsMin = rows || rowsMinProp; var _React$useRef = React.useRef(value != null), isControlled = _React$useRef.current; var inputRef = React.useRef(null); var handleRef = useForkRef(ref, inputRef); var shadowRef = React.useRef(null); var _React$useState = React.useState({}), state = _React$useState[0], setState = _React$useState[1]; var syncHeight = React.useCallback(function () { var input = inputRef.current; var computedStyle = window.getComputedStyle(input); var inputShallow = shadowRef.current; inputShallow.style.width = computedStyle.width; inputShallow.value = input.value || props.placeholder || 'x'; var boxSizing = computedStyle['box-sizing']; var padding = getStyleValue(computedStyle, 'padding-bottom') + getStyleValue(computedStyle, 'padding-top'); var border = getStyleValue(computedStyle, 'border-bottom-width') + getStyleValue(computedStyle, 'border-top-width'); // The height of the inner content var innerHeight = inputShallow.scrollHeight - padding; // Measure height of a textarea with a single row inputShallow.value = 'x'; var singleRowHeight = inputShallow.scrollHeight - padding; // The height of the outer content var outerHeight = innerHeight; if (rowsMin) { outerHeight = Math.max(Number(rowsMin) * singleRowHeight, outerHeight); } if (rowsMax) { outerHeight = Math.min(Number(rowsMax) * singleRowHeight, outerHeight); } outerHeight = Math.max(outerHeight, singleRowHeight); // Take the box sizing into account for applying this value as a style. var outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0); var overflow = Math.abs(outerHeight - innerHeight) <= 1; setState(function (prevState) { // Need a large enough different to update the height. // This prevents infinite rendering loop. if (outerHeightStyle > 0 && Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1 || prevState.overflow !== overflow) { return { overflow: overflow, outerHeightStyle: outerHeightStyle }; } return prevState; }); }, [rowsMax, rowsMin, props.placeholder]); React.useEffect(function () { var handleResize = debounce(function () { syncHeight(); }); window.addEventListener('resize', handleResize); return function () { handleResize.clear(); window.removeEventListener('resize', handleResize); }; }, [syncHeight]); useEnhancedEffect(function () { syncHeight(); }); var handleChange = function handleChange(event) { if (!isControlled) { syncHeight(); } if (onChange) { onChange(event); } }; return React.createElement(React.Fragment, null, React.createElement("textarea", _extends({ value: value, onChange: handleChange, ref: handleRef // Apply the rows prop to get a "correct" first SSR paint , rows: rowsMin, style: _extends({ height: state.outerHeightStyle, // Need a large enough different to allow scrolling. // This prevents infinite rendering loop. overflow: state.overflow ? 'hidden' : null }, style) }, other)), React.createElement("textarea", { "aria-hidden": true, className: props.className, readOnly: true, ref: shadowRef, tabIndex: -1, style: _extends({}, styles.shadow, {}, style) })); }); process.env.NODE_ENV !== "production" ? TextareaAutosize.propTypes = { /** * @ignore */ className: PropTypes.string, /** * @ignore */ onChange: PropTypes.func, /** * @ignore */ placeholder: PropTypes.string, /** * Use `rowsMin` instead. The prop will be removed in v5. * * @deprecated */ rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Maximum number of rows to display. */ rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Minimum number of rows to display. */ rowsMin: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * @ignore */ style: PropTypes.object, /** * @ignore */ value: PropTypes.any } : void 0; export default TextareaAutosize;
ajax/libs/material-ui/4.10.1/esm/utils/createSvgIcon.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import SvgIcon from '../SvgIcon'; /** * Private module reserved for @material-ui/x packages. */ export default function createSvgIcon(path, displayName) { var Component = function Component(props, ref) { return /*#__PURE__*/React.createElement(SvgIcon, _extends({ ref: ref }, props), path); }; if (process.env.NODE_ENV !== 'production') { // Need to set `displayName` on the inner component for React.memo. // React prior to 16.14 ignores `displayName` on the wrapper. Component.displayName = "".concat(displayName, "Icon"); } Component.muiName = SvgIcon.muiName; return React.memo(React.forwardRef(Component)); }
ajax/libs/primereact/7.2.0/gmap/gmap.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var GMap = /*#__PURE__*/function (_Component) { _inherits(GMap, _Component); var _super = _createSuper(GMap); function GMap() { _classCallCheck(this, GMap); return _super.apply(this, arguments); } _createClass(GMap, [{ key: "initMap", value: function initMap() { this.map = new google.maps.Map(this.container, this.props.options); if (this.props.onMapReady) { this.props.onMapReady({ map: this.map }); } this.initOverlays(this.props.overlays); this.bindMapEvent('click', this.props.onMapClick); this.bindMapEvent('dragend', this.props.onMapDragEnd); this.bindMapEvent('zoom_changed', this.props.onZoomChanged); } }, { key: "initOverlays", value: function initOverlays(overlays) { if (overlays) { var _iterator = _createForOfIteratorHelper(overlays), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var overlay = _step.value; overlay.setMap(this.map); this.bindOverlayEvents(overlay); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } } }, { key: "bindOverlayEvents", value: function bindOverlayEvents(overlay) { var _this = this; overlay.addListener('click', function (event) { if (_this.props.onOverlayClick) { _this.props.onOverlayClick({ originalEvent: event, overlay: overlay, map: _this.map }); } }); if (overlay.getDraggable()) { this.bindDragEvents(overlay); } } }, { key: "bindDragEvents", value: function bindDragEvents(overlay) { this.bindDragEvent(overlay, 'dragstart', this.props.onOverlayDragStart); this.bindDragEvent(overlay, 'drag', this.props.onOverlayDrag); this.bindDragEvent(overlay, 'dragend', this.props.onOverlayDragEnd); } }, { key: "bindMapEvent", value: function bindMapEvent(eventName, callback) { this.map.addListener(eventName, function (event) { if (callback) { callback(event); } }); } }, { key: "bindDragEvent", value: function bindDragEvent(overlay, eventName, callback) { var _this2 = this; overlay.addListener(eventName, function (event) { if (callback) { callback({ originalEvent: event, overlay: overlay, map: _this2.map }); } }); } }, { key: "getMap", value: function getMap() { return this.map; } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState, snapshot) { if (prevProps.overlays !== this.props.overlays) { if (prevProps.overlays) { var _iterator2 = _createForOfIteratorHelper(prevProps.overlays), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var overlay = _step2.value; google.maps.event.clearInstanceListeners(overlay); overlay.setMap(null); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } this.initOverlays(this.props.overlays); } } }, { key: "componentDidMount", value: function componentDidMount() { this.initMap(); } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this3.container = el; }, style: this.props.style, className: this.props.className }); } }]); return GMap; }(Component); _defineProperty(GMap, "defaultProps", { options: null, overlays: null, style: null, className: null, onMapReady: null, onMapClick: null, onMapDragEnd: null, onZoomChanged: null, onOverlayDragStart: null, onOverlayDrag: null, onOverlayDragEnd: null, onOverlayClick: null }); export { GMap };
ajax/libs/primereact/7.2.0/virtualscroller/virtualscroller.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { ObjectUtils, classNames } from 'primereact/utils'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var VirtualScroller = /*#__PURE__*/function (_Component) { _inherits(VirtualScroller, _Component); var _super = _createSuper(VirtualScroller); function VirtualScroller(props) { var _this; _classCallCheck(this, VirtualScroller); _this = _super.call(this, props); var isBoth = _this.isBoth(); _this.state = { first: isBoth ? { rows: 0, cols: 0 } : 0, last: isBoth ? { rows: 0, cols: 0 } : 0, numItemsInViewport: isBoth ? { rows: 0, cols: 0 } : 0, numToleratedItems: props.numToleratedItems, loading: props.loading, loaderArr: [] }; _this.onScroll = _this.onScroll.bind(_assertThisInitialized(_this)); _this.lastScrollPos = isBoth ? { top: 0, left: 0 } : 0; return _this; } _createClass(VirtualScroller, [{ key: "scrollTo", value: function scrollTo(options) { this.el && this.el.scrollTo(options); } }, { key: "scrollToIndex", value: function scrollToIndex(index) { var _this2 = this; var behavior = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'auto'; var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var first = this.state.first; var _this$calculateNumIte = this.calculateNumItems(), numToleratedItems = _this$calculateNumIte.numToleratedItems; var itemSize = this.props.itemSize; var contentPos = this.getContentPosition(); var calculateFirst = function calculateFirst() { var _index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var _numT = arguments.length > 1 ? arguments[1] : undefined; return _index <= _numT ? 0 : _index; }; var calculateCoord = function calculateCoord(_first, _size, _cpos) { return _first * _size + _cpos; }; var scrollTo = function scrollTo() { var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; return _this2.scrollTo({ left: left, top: top, behavior: behavior }); }; if (isBoth) { var newFirst = { rows: calculateFirst(index[0], numToleratedItems[0]), cols: calculateFirst(index[1], numToleratedItems[1]) }; if (newFirst.rows !== first.rows || newFirst.cols !== first.cols) { scrollTo(calculateCoord(newFirst.cols, itemSize[1], contentPos.left), calculateCoord(newFirst.rows, itemSize[0], contentPos.top)); this.setState({ first: newFirst }); } } else { var _newFirst = calculateFirst(index, numToleratedItems); if (_newFirst !== first) { isHorizontal ? scrollTo(calculateCoord(_newFirst, itemSize, contentPos.left), 0) : scrollTo(0, calculateCoord(_newFirst, itemSize, contentPos.top)); this.setState({ first: _newFirst }); } } } }, { key: "scrollInView", value: function scrollInView(index, to) { var _this3 = this; var behavior = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'auto'; if (to) { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var _this$getRenderedRang = this.getRenderedRange(), first = _this$getRenderedRang.first, viewport = _this$getRenderedRang.viewport; var itemSize = this.props.itemSize; var scrollTo = function scrollTo() { var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; return _this3.scrollTo({ left: left, top: top, behavior: behavior }); }; var isToStart = to === 'to-start'; var isToEnd = to === 'to-end'; if (isToStart) { if (isBoth) { if (viewport.first.rows - first.rows > index[0]) { scrollTo(viewport.first.cols * itemSize, (viewport.first.rows - 1) * itemSize); } else if (viewport.first.cols - first.cols > index[1]) { scrollTo((viewport.first.cols - 1) * itemSize, viewport.first.rows * itemSize); } } else { if (viewport.first - first > index) { var pos = (viewport.first - 1) * itemSize; isHorizontal ? scrollTo(pos, 0) : scrollTo(0, pos); } } } else if (isToEnd) { if (isBoth) { if (viewport.last.rows - first.rows <= index[0] + 1) { scrollTo(viewport.first.cols * itemSize, (viewport.first.rows + 1) * itemSize); } else if (viewport.last.cols - first.cols <= index[1] + 1) { scrollTo((viewport.first.cols + 1) * itemSize, viewport.first.rows * itemSize); } } else { if (viewport.last - first <= index + 1) { var _pos2 = (viewport.first + 1) * itemSize; isHorizontal ? scrollTo(_pos2, 0) : scrollTo(0, _pos2); } } } } else { this.scrollToIndex(index, behavior); } } }, { key: "getRows", value: function getRows() { return this.state.loading ? this.props.loaderDisabled ? this.state.loaderArr : [] : this.loadedItems(); } }, { key: "getColumns", value: function getColumns() { if (this.props.columns) { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); if (isBoth || isHorizontal) { return this.state.loading && this.props.loaderDisabled ? isBoth ? this.state.loaderArr[0] : this.state.loaderArr : this.props.columns.slice(isBoth ? this.state.first.cols : this.state.first, isBoth ? this.state.last.cols : this.state.last); } } return this.props.columns; } }, { key: "getRenderedRange", value: function getRenderedRange() { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var _this$state = this.state, first = _this$state.first, last = _this$state.last, numItemsInViewport = _this$state.numItemsInViewport; var itemSize = this.props.itemSize; var calculateFirstInViewport = function calculateFirstInViewport(_pos, _size) { return Math.floor(_pos / (_size || _pos)); }; var firstInViewport = first; var lastInViewport = 0; if (this.el) { var scrollTop = this.el.scrollTop; var scrollLeft = this.el.scrollLeft; if (isBoth) { firstInViewport = { rows: calculateFirstInViewport(scrollTop, itemSize[0]), cols: calculateFirstInViewport(scrollLeft, itemSize[1]) }; lastInViewport = { rows: firstInViewport.rows + numItemsInViewport.rows, cols: firstInViewport.cols + numItemsInViewport.cols }; } else { var scrollPos = isHorizontal ? scrollLeft : scrollTop; firstInViewport = calculateFirstInViewport(scrollPos, itemSize); lastInViewport = firstInViewport + numItemsInViewport; } } return { first: first, last: last, viewport: { first: firstInViewport, last: lastInViewport } }; } }, { key: "isVertical", value: function isVertical() { return this.props.orientation === 'vertical'; } }, { key: "isHorizontal", value: function isHorizontal() { return this.props.orientation === 'horizontal'; } }, { key: "isBoth", value: function isBoth() { return this.props.orientation === 'both'; } }, { key: "calculateNumItems", value: function calculateNumItems() { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var itemSize = this.props.itemSize; var contentPos = this.getContentPosition(); var contentWidth = this.el ? this.el.offsetWidth - contentPos.left : 0; var contentHeight = this.el ? this.el.offsetHeight - contentPos.top : 0; var calculateNumItemsInViewport = function calculateNumItemsInViewport(_contentSize, _itemSize) { return Math.ceil(_contentSize / (_itemSize || _contentSize)); }; var calculateNumToleratedItems = function calculateNumToleratedItems(_numItems) { return Math.ceil(_numItems / 2); }; var numItemsInViewport = isBoth ? { rows: calculateNumItemsInViewport(contentHeight, itemSize[0]), cols: calculateNumItemsInViewport(contentWidth, itemSize[1]) } : calculateNumItemsInViewport(isHorizontal ? contentWidth : contentHeight, itemSize); var numToleratedItems = this.state.numToleratedItems || (isBoth ? [calculateNumToleratedItems(numItemsInViewport.rows), calculateNumToleratedItems(numItemsInViewport.cols)] : calculateNumToleratedItems(numItemsInViewport)); return { numItemsInViewport: numItemsInViewport, numToleratedItems: numToleratedItems }; } }, { key: "calculateOptions", value: function calculateOptions() { var _this4 = this; var isBoth = this.isBoth(); var first = this.state.first; var _this$calculateNumIte2 = this.calculateNumItems(), numItemsInViewport = _this$calculateNumIte2.numItemsInViewport, numToleratedItems = _this$calculateNumIte2.numToleratedItems; var calculateLast = function calculateLast(_first, _num, _numT, _isCols) { return _this4.getLast(_first + _num + (_first < _numT ? 2 : 3) * _numT, _isCols); }; var last = isBoth ? { rows: calculateLast(first.rows, numItemsInViewport.rows, numToleratedItems[0]), cols: calculateLast(first.cols, numItemsInViewport.cols, numToleratedItems[1], true) } : calculateLast(first, numItemsInViewport, numToleratedItems); var state = { numItemsInViewport: numItemsInViewport, last: last, numToleratedItems: numToleratedItems }; if (this.props.showLoader) { state['loaderArr'] = isBoth ? Array.from({ length: numItemsInViewport.rows }).map(function () { return Array.from({ length: numItemsInViewport.cols }); }) : Array.from({ length: numItemsInViewport }); } this.setState(state, function () { if (_this4.props.lazy) { _this4.props.onLazyLoad && _this4.props.onLazyLoad({ first: _this4.state.first, last: _this4.state.last }); } }); } }, { key: "getLast", value: function getLast() { var last = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var isCols = arguments.length > 1 ? arguments[1] : undefined; if (this.props.items) { return Math.min(isCols ? (this.props.columns || this.props.items[0]).length : this.props.items.length, last); } return 0; } }, { key: "getContentPosition", value: function getContentPosition() { if (this.content) { var style = getComputedStyle(this.content); var left = parseInt(style.paddingLeft, 10) + Math.max(parseInt(style.left, 10), 0); var right = parseInt(style.paddingRight, 10) + Math.max(parseInt(style.right, 10), 0); var top = parseInt(style.paddingTop, 10) + Math.max(parseInt(style.top, 10), 0); var bottom = parseInt(style.paddingBottom, 10) + Math.max(parseInt(style.bottom, 10), 0); return { left: left, right: right, top: top, bottom: bottom, x: left + right, y: top + bottom }; } return { left: 0, right: 0, top: 0, bottom: 0, x: 0, y: 0 }; } }, { key: "setSize", value: function setSize() { var _this5 = this; if (this.el) { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var parentElement = this.el.parentElement; var width = this.props.scrollWidth || "".concat(this.el.offsetWidth || parentElement.offsetWidth, "px"); var height = this.props.scrollHeight || "".concat(this.el.offsetHeight || parentElement.offsetHeight, "px"); var setProp = function setProp(_name, _value) { return _this5.el.style[_name] = _value; }; if (isBoth || isHorizontal) { setProp('height', height); setProp('width', width); } else { setProp('height', height); } } } }, { key: "setSpacerSize", value: function setSpacerSize() { var _this6 = this; var items = this.props.items; if (this.spacer && items) { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var itemSize = this.props.itemSize; var contentPos = this.getContentPosition(); var setProp = function setProp(_name, _value, _size) { var _cpos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; return _this6.spacer.style[_name] = (_value || []).length * _size + _cpos + 'px'; }; if (isBoth) { setProp('height', items, itemSize[0], contentPos.y); setProp('width', this.props.columns || items[1], itemSize[1], contentPos.x); } else { isHorizontal ? setProp('width', this.props.columns || items, itemSize, contentPos.x) : setProp('height', items, itemSize, contentPos.y); } } } }, { key: "setContentPosition", value: function setContentPosition(pos) { var _this7 = this; if (this.content) { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var first = pos ? pos.first : this.state.first; var itemSize = this.props.itemSize; var calculateTranslateVal = function calculateTranslateVal(_first, _size) { return _first * _size; }; var setTransform = function setTransform() { var _x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var _y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; _this7.sticky && (_this7.sticky.style.top = "-".concat(_y, "px")); _this7.content.style.transform = "translate3d(".concat(_x, "px, ").concat(_y, "px, 0)"); }; if (isBoth) { setTransform(calculateTranslateVal(first.cols, itemSize[1]), calculateTranslateVal(first.rows, itemSize[0])); } else { var translateVal = calculateTranslateVal(first, itemSize); isHorizontal ? setTransform(translateVal, 0) : setTransform(0, translateVal); } } } }, { key: "onScrollPositionChange", value: function onScrollPositionChange(event) { var _this8 = this; var target = event.target; var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var _this$state2 = this.state, first = _this$state2.first, last = _this$state2.last, numItemsInViewport = _this$state2.numItemsInViewport, numToleratedItems = _this$state2.numToleratedItems; var itemSize = this.props.itemSize; var contentPos = this.getContentPosition(); var calculateScrollPos = function calculateScrollPos(_pos, _cpos) { return _pos ? _pos > _cpos ? _pos - _cpos : _pos : 0; }; var calculateCurrentIndex = function calculateCurrentIndex(_pos, _size) { return Math.floor(_pos / (_size || _pos)); }; var calculateTriggerIndex = function calculateTriggerIndex(_currentIndex, _first, _last, _num, _numT, _isScrollDownOrRight) { return _currentIndex <= _numT ? _numT : _isScrollDownOrRight ? _last - _num - _numT : _first + _numT - 1; }; var calculateFirst = function calculateFirst(_currentIndex, _triggerIndex, _first, _last, _num, _numT, _isScrollDownOrRight) { if (_currentIndex <= _numT) return 0;else return Math.max(0, _isScrollDownOrRight ? _currentIndex < _triggerIndex ? _first : _currentIndex - _numT : _currentIndex > _triggerIndex ? _first : _currentIndex - 2 * _numT); }; var calculateLast = function calculateLast(_currentIndex, _first, _last, _num, _numT, _isCols) { var lastValue = _first + _num + 2 * _numT; if (_currentIndex >= _numT) { lastValue += _numT + 1; } return _this8.getLast(lastValue, _isCols); }; var scrollTop = calculateScrollPos(target.scrollTop, contentPos.top); var scrollLeft = calculateScrollPos(target.scrollLeft, contentPos.left); var newFirst = 0; var newLast = last; var isRangeChanged = false; if (isBoth) { var isScrollDown = this.lastScrollPos.top <= scrollTop; var isScrollRight = this.lastScrollPos.left <= scrollLeft; var currentIndex = { rows: calculateCurrentIndex(scrollTop, itemSize[0]), cols: calculateCurrentIndex(scrollLeft, itemSize[1]) }; var triggerIndex = { rows: calculateTriggerIndex(currentIndex.rows, first.rows, last.rows, numItemsInViewport.rows, numToleratedItems[0], isScrollDown), cols: calculateTriggerIndex(currentIndex.cols, first.cols, last.cols, numItemsInViewport.cols, numToleratedItems[1], isScrollRight) }; newFirst = { rows: calculateFirst(currentIndex.rows, triggerIndex.rows, first.rows, last.rows, numItemsInViewport.rows, numToleratedItems[0], isScrollDown), cols: calculateFirst(currentIndex.cols, triggerIndex.cols, first.cols, last.cols, numItemsInViewport.cols, numToleratedItems[1], isScrollRight) }; newLast = { rows: calculateLast(currentIndex.rows, newFirst.rows, last.rows, numItemsInViewport.rows, numToleratedItems[0]), cols: calculateLast(currentIndex.cols, newFirst.cols, last.cols, numItemsInViewport.cols, numToleratedItems[1], true) }; isRangeChanged = newFirst.rows !== first.rows && newLast.rows !== last.rows || newFirst.cols !== first.cols && newLast.cols !== last.cols; this.lastScrollPos = { top: scrollTop, left: scrollLeft }; } else { var scrollPos = isHorizontal ? scrollLeft : scrollTop; var isScrollDownOrRight = this.lastScrollPos <= scrollPos; var _currentIndex2 = calculateCurrentIndex(scrollPos, itemSize); var _triggerIndex2 = calculateTriggerIndex(_currentIndex2, first, last, numItemsInViewport, numToleratedItems, isScrollDownOrRight); newFirst = calculateFirst(_currentIndex2, _triggerIndex2, first, last, numItemsInViewport, numToleratedItems, isScrollDownOrRight); newLast = calculateLast(_currentIndex2, newFirst, last, numItemsInViewport, numToleratedItems); isRangeChanged = newFirst !== first && newLast !== last; this.lastScrollPos = scrollPos; } return { first: newFirst, last: newLast, isRangeChanged: isRangeChanged }; } }, { key: "onScrollChange", value: function onScrollChange(event) { var _this9 = this; var _this$onScrollPositio = this.onScrollPositionChange(event), first = _this$onScrollPositio.first, last = _this$onScrollPositio.last, isRangeChanged = _this$onScrollPositio.isRangeChanged; if (isRangeChanged) { var newState = { first: first, last: last }; this.setContentPosition(newState); this.setState(newState, function () { _this9.props.onScrollIndexChange && _this9.props.onScrollIndexChange(newState); if (_this9.props.lazy) { _this9.props.onLazyLoad && _this9.props.onLazyLoad(newState); } }); } } }, { key: "onScroll", value: function onScroll(event) { var _this10 = this; this.props.onScroll && this.props.onScroll(event); if (this.props.delay) { if (this.scrollTimeout) { clearTimeout(this.scrollTimeout); } if (!this.state.loading && this.props.showLoader) { var _this$onScrollPositio2 = this.onScrollPositionChange(event), changed = _this$onScrollPositio2.isRangeChanged; changed && this.setState({ loading: true }); } this.scrollTimeout = setTimeout(function () { _this10.onScrollChange(event); if (_this10.state.loading && _this10.props.showLoader && !_this10.props.lazy) { _this10.setState({ loading: false }); } }, this.props.delay); } else { this.onScrollChange(event); } } }, { key: "getOptions", value: function getOptions(renderedIndex) { var first = this.state.first; var count = (this.props.items || []).length; var index = this.isBoth() ? first.rows + renderedIndex : first + renderedIndex; return { index: index, count: count, first: index === 0, last: index === count - 1, even: index % 2 === 0, odd: index % 2 !== 0, props: this.props }; } }, { key: "loaderOptions", value: function loaderOptions(index, extOptions) { var count = this.state.loaderArr.length; return _objectSpread({ index: index, count: count, first: index === 0, last: index === count - 1, even: index % 2 === 0, odd: index % 2 !== 0, props: this.props }, extOptions); } }, { key: "loadedItems", value: function loadedItems() { var _this11 = this; var items = this.props.items; if (items && !this.state.loading) { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var _this$state3 = this.state, first = _this$state3.first, last = _this$state3.last; if (isBoth) return items.slice(first.rows, last.rows).map(function (item) { return _this11.props.columns ? item : item.slice(first.cols, last.cols); });else if (isHorizontal && this.props.columns) return items;else return items.slice(first, last); } return []; } }, { key: "isPropChanged", value: function isPropChanged(prevProps) { var _this12 = this; var props = ['itemSize', 'scrollHeight']; return props.some(function (p) { return !ObjectUtils.equals(prevProps[p], _this12.props[p]); }); } }, { key: "init", value: function init() { this.setSize(); this.calculateOptions(); this.setSpacerSize(); } }, { key: "componentDidMount", value: function componentDidMount() { this.init(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (!prevProps.items || prevProps.items.length !== (this.props.items || []).length || this.isPropChanged(prevProps)) { this.init(); } if (this.props.lazy && prevProps.loading !== this.props.loading && this.state.loading !== this.props.loading) { this.setState({ loading: this.props.loading }); } if (prevProps.orientation !== this.props.orientation) { this.lastScrollPos = this.isBoth() ? { top: 0, left: 0 } : 0; } } }, { key: "renderLoaderItem", value: function renderLoaderItem(index) { var extOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = this.loaderOptions(index, extOptions); var content = ObjectUtils.getJSXElement(this.props.loadingTemplate, options); return /*#__PURE__*/React.createElement(React.Fragment, { key: index }, content); } }, { key: "renderLoader", value: function renderLoader() { var _this13 = this; if (!this.props.loaderDisabled && this.props.showLoader && this.state.loading) { var className = classNames('p-virtualscroller-loader', { 'p-component-overlay': !this.props.loadingTemplate }); var content = /*#__PURE__*/React.createElement("i", { className: "p-virtualscroller-loading-icon pi pi-spinner pi-spin" }); if (this.props.loadingTemplate) { var isBoth = this.isBoth(); var numItemsInViewport = this.state.numItemsInViewport; content = this.state.loaderArr.map(function (_, index) { return _this13.renderLoaderItem(index, isBoth && { numCols: numItemsInViewport.cols }); }); } return /*#__PURE__*/React.createElement("div", { className: className }, content); } return null; } }, { key: "renderSpacer", value: function renderSpacer() { var _this14 = this; if (this.props.showSpacer) { return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this14.spacer = el; }, className: "p-virtualscroller-spacer" }); } return null; } }, { key: "renderItem", value: function renderItem(item, index) { var options = this.getOptions(index); var content = ObjectUtils.getJSXElement(this.props.itemTemplate, item, options); return /*#__PURE__*/React.createElement(React.Fragment, { key: options.index }, content); } }, { key: "renderItems", value: function renderItems(loadedItems) { var _this15 = this; return loadedItems.map(function (item, index) { return _this15.renderItem(item, index); }); } }, { key: "renderContent", value: function renderContent() { var _this16 = this; var loadedItems = this.loadedItems(); var items = this.renderItems(loadedItems); var className = classNames('p-virtualscroller-content', { 'p-virtualscroller-loading': this.state.loading }); var content = /*#__PURE__*/React.createElement("div", { className: className, ref: function ref(el) { return _this16.content = el; } }, items); if (this.props.contentTemplate) { var defaultOptions = { className: className, contentRef: function contentRef(el) { return _this16.content = el; }, spacerRef: function spacerRef(el) { return _this16.spacer = el; }, stickyRef: function stickyRef(el) { return _this16.sticky = el; }, items: loadedItems, getItemOptions: function getItemOptions(index) { return _this16.getOptions(index); }, children: items, element: content, props: this.props, loading: this.state.loading, getLoaderOptions: function getLoaderOptions(index, ext) { return _this16.loaderOptions(index, ext); }, loadingTemplate: this.props.loadingTemplate, itemSize: this.props.itemSize, rows: this.getRows(), columns: this.getColumns(), vertical: this.isVertical(), horizontal: this.isHorizontal(), both: this.isBoth() }; return ObjectUtils.getJSXElement(this.props.contentTemplate, defaultOptions); } return content; } }, { key: "render", value: function render() { var _this17 = this; if (this.props.disabled) { var content = ObjectUtils.getJSXElement(this.props.contentTemplate, { items: this.props.items, rows: this.props.items, columns: this.props.columns }); return /*#__PURE__*/React.createElement(React.Fragment, null, this.props.children, content); } else { var isBoth = this.isBoth(); var isHorizontal = this.isHorizontal(); var className = classNames('p-virtualscroller', { 'p-both-scroll': isBoth, 'p-horizontal-scroll': isHorizontal }, this.props.className); var loader = this.renderLoader(); var _content = this.renderContent(); var spacer = this.renderSpacer(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this17.el = el; }, className: className, tabIndex: 0, style: this.props.style, onScroll: this.onScroll }, _content, spacer, loader); } } }]); return VirtualScroller; }(Component); _defineProperty(VirtualScroller, "defaultProps", { id: null, style: null, className: null, items: null, itemSize: 0, scrollHeight: null, scrollWidth: null, orientation: 'vertical', numToleratedItems: null, delay: 0, lazy: false, disabled: false, loaderDisabled: false, columns: null, loading: false, showSpacer: true, showLoader: false, loadingTemplate: null, itemTemplate: null, contentTemplate: null, onScroll: null, onScrollIndexChange: null, onLazyLoad: null }); export { VirtualScroller };
ajax/libs/react-native-web/0.14.0/exports/RefreshControl/index.js
cdnjs/cdnjs
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import View from '../View'; import React from 'react'; function RefreshControl(props) { var colors = props.colors, enabled = props.enabled, onRefresh = props.onRefresh, progressBackgroundColor = props.progressBackgroundColor, progressViewOffset = props.progressViewOffset, refreshing = props.refreshing, size = props.size, tintColor = props.tintColor, title = props.title, titleColor = props.titleColor, rest = _objectWithoutPropertiesLoose(props, ["colors", "enabled", "onRefresh", "progressBackgroundColor", "progressViewOffset", "refreshing", "size", "tintColor", "title", "titleColor"]); return React.createElement(View, rest); } export default RefreshControl;
ajax/libs/material-ui/5.0.0-alpha.22/styles/ThemeProvider.js
cdnjs/cdnjs
import React from 'react'; import PropTypes from 'prop-types'; import { ThemeProvider as MuiThemeProvider } from '@material-ui/styles'; import { exactProp } from '@material-ui/utils'; import { ThemeContext as StyledEngineThemeContext } from '@material-ui/styled-engine'; import useTheme from './useTheme'; function InnerThemeProvider(props) { const theme = useTheme(); return /*#__PURE__*/React.createElement(StyledEngineThemeContext.Provider, { value: typeof theme === 'object' ? theme : {} }, props.children); } process.env.NODE_ENV !== "production" ? InnerThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node } : void 0; /** * This component makes the `theme` available down the React tree. * It should preferably be used at **the root of your component tree**. */ function ThemeProvider(props) { const { children, theme: localTheme } = props; return /*#__PURE__*/React.createElement(MuiThemeProvider, { theme: localTheme }, /*#__PURE__*/React.createElement(InnerThemeProvider, null, children)); } process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node, /** * A theme object. You can provide a function to extend the outer theme. */ theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0; } export default ThemeProvider;
ajax/libs/react-native-web/0.17.5/exports/YellowBox/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import React from 'react'; import UnimplementedView from '../../modules/UnimplementedView'; function YellowBox(props) { return /*#__PURE__*/React.createElement(UnimplementedView, props); } YellowBox.ignoreWarnings = function () {}; export default YellowBox;
ajax/libs/material-ui/5.0.0-alpha.17/styles/ThemeProvider.js
cdnjs/cdnjs
import React from 'react'; import PropTypes from 'prop-types'; import { ThemeProvider as MuiThemeProvider } from '@material-ui/styles'; import { exactProp } from '@material-ui/utils'; import { ThemeContext as StyledEngineThemeContext } from '@material-ui/styled-engine'; import useTheme from './useTheme'; function InnerThemeProvider(props) { const theme = useTheme(); return /*#__PURE__*/React.createElement(StyledEngineThemeContext.Provider, { value: typeof theme === 'object' ? theme : {} }, props.children); } process.env.NODE_ENV !== "production" ? InnerThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node } : void 0; /** * This component makes the `theme` available down the React tree. * It should preferably be used at **the root of your component tree**. */ function ThemeProvider(props) { const { children, theme: localTheme } = props; return /*#__PURE__*/React.createElement(MuiThemeProvider, { theme: localTheme }, /*#__PURE__*/React.createElement(InnerThemeProvider, null, children)); } process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = { /** * Your component tree. */ children: PropTypes.node, /** * A theme object. You can provide a function to extend the outer theme. */ theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0; } export default ThemeProvider;
ajax/libs/react-native-web/0.14.0/modules/UnimplementedView/index.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import View from '../../exports/View'; import React from 'react'; /** * Common implementation for a simple stubbed view. */ var UnimplementedView = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(UnimplementedView, _React$Component); function UnimplementedView() { return _React$Component.apply(this, arguments) || this; } var _proto = UnimplementedView.prototype; _proto.setNativeProps = function setNativeProps() {// Do nothing. }; _proto.render = function render() { return React.createElement(View, { style: [unimplementedViewStyles, this.props.style] }, this.props.children); }; return UnimplementedView; }(React.Component); var unimplementedViewStyles = process.env.NODE_ENV !== 'production' ? { alignSelf: 'flex-start', borderColor: 'red', borderWidth: 1 } : {}; export default UnimplementedView;
ajax/libs/boardgame-io/0.39.12/esm/react.js
cdnjs/cdnjs
import { t as _inherits, _ as _createClass, p as _defineProperty, o as _classCallCheck, u as _possibleConstructorReturn, v as _getPrototypeOf, y as _objectSpread2, J as _assertThisInitialized, D as _toConsumableArray } from './turn-order-a2314c0f.js'; import 'redux'; import 'immer'; import './reducer-4d135cbd.js'; import './Debug-1ad6801e.js'; import 'flatted'; import { M as MCTSBot } from './ai-ce6b7ece.js'; import './initialize-ec2b5846.js'; import { C as Client$1 } from './client-abd9e531.js'; import React from 'react'; import PropTypes from 'prop-types'; import Cookies from 'react-cookies'; import './base-c99f5be2.js'; import { S as SocketIO, L as Local } from './socketio-b6741dab.js'; import './master-5e6f33cb.js'; import 'socket.io-client'; /** * Client * * boardgame.io React client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} debug - Enables the Debug UI. * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET, * UNDO and REDO. */ function Client(opts) { var _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, loading = opts.loading, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer, debug = opts.debug; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { var Loading = function Loading() { return React.createElement("div", { className: "bgio-loading" }, "connecting..."); }; loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _temp = _class = /*#__PURE__*/ function (_React$Component) { _inherits(WrappedBoard, _React$Component); function WrappedBoard(props) { var _this; _classCallCheck(this, WrappedBoard); _this = _possibleConstructorReturn(this, _getPrototypeOf(WrappedBoard).call(this, props)); if (debug === undefined) { debug = props.debug; } _this.client = Client$1({ game: game, debug: debug, numPlayers: numPlayers, multiplayer: multiplayer, gameID: props.gameID, playerID: props.playerID, credentials: props.credentials, enhancer: enhancer }); return _this; } _createClass(WrappedBoard, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.client.subscribe(function () { return _this2.forceUpdate(); }); this.client.start(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.client.stop(); this.unsubscribe(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.gameID != prevProps.gameID) { this.client.updateGameID(this.props.gameID); } if (this.props.playerID != prevProps.playerID) { this.client.updatePlayerID(this.props.playerID); } if (this.props.credentials != prevProps.credentials) { this.client.updateCredentials(this.props.credentials); } } }, { key: "render", value: function render() { var state = this.client.getState(); if (state === null) { return React.createElement(loading); } var _board = null; if (board) { _board = React.createElement(board, _objectSpread2({}, state, {}, this.props, { isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, gameID: this.client.gameID, playerID: this.client.playerID, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, log: this.client.log, gameMetadata: this.client.gameMetadata })); } return React.createElement("div", { className: "bgio-client" }, _board); } }]); return WrappedBoard; }(React.Component), _defineProperty(_class, "propTypes", { // The ID of a game to connect to. // Only relevant in multiplayer. gameID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string, // Enable / disable the Debug UI. debug: PropTypes.any }), _defineProperty(_class, "defaultProps", { gameID: 'default', playerID: null, credentials: null, debug: true }), _temp; } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ var _LobbyConnectionImpl = /*#__PURE__*/ function () { function _LobbyConnectionImpl(_ref) { var server = _ref.server, gameComponents = _ref.gameComponents, playerName = _ref.playerName, playerCredentials = _ref.playerCredentials; _classCallCheck(this, _LobbyConnectionImpl); this.gameComponents = gameComponents; this.playerName = playerName || 'Visitor'; this.playerCredentials = playerCredentials; this.server = server; this.rooms = []; } _createClass(_LobbyConnectionImpl, [{ key: "_baseUrl", value: function _baseUrl() { return "".concat(this.server || '', "/games"); } }, { key: "refresh", value: async function refresh() { try { this.rooms.length = 0; var resp = await fetch(this._baseUrl()); if (resp.status !== 200) { throw new Error('HTTP status ' + resp.status); } var json = await resp.json(); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = json[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var gameName = _step.value; if (!this._getGameComponents(gameName)) continue; var gameResp = await fetch(this._baseUrl() + '/' + gameName); var gameJson = await gameResp.json(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = gameJson.rooms[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var inst = _step2.value; inst.gameName = gameName; } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } this.rooms = this.rooms.concat(gameJson.rooms); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } catch (error) { throw new Error('failed to retrieve list of games (' + error + ')'); } } }, { key: "_getGameInstance", value: function _getGameInstance(gameID) { var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = this.rooms[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var inst = _step3.value; if (inst['gameID'] === gameID) return inst; } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { _iterator3["return"](); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } } }, { key: "_getGameComponents", value: function _getGameComponents(gameName) { var _iteratorNormalCompletion4 = true; var _didIteratorError4 = false; var _iteratorError4 = undefined; try { for (var _iterator4 = this.gameComponents[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { var comp = _step4.value; if (comp.game.name === gameName) return comp; } } catch (err) { _didIteratorError4 = true; _iteratorError4 = err; } finally { try { if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) { _iterator4["return"](); } } finally { if (_didIteratorError4) { throw _iteratorError4; } } } } }, { key: "_findPlayer", value: function _findPlayer(playerName) { var _iteratorNormalCompletion5 = true; var _didIteratorError5 = false; var _iteratorError5 = undefined; try { for (var _iterator5 = this.rooms[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { var inst = _step5.value; if (inst.players.some(function (player) { return player.name === playerName; })) return inst; } } catch (err) { _didIteratorError5 = true; _iteratorError5 = err; } finally { try { if (!_iteratorNormalCompletion5 && _iterator5["return"] != null) { _iterator5["return"](); } } finally { if (_didIteratorError5) { throw _iteratorError5; } } } } }, { key: "join", value: async function join(gameName, gameID, playerID) { try { var inst = this._findPlayer(this.playerName); if (inst) { throw new Error('player has already joined ' + inst.gameID); } inst = this._getGameInstance(gameID); if (!inst) { throw new Error('game instance ' + gameID + ' not found'); } var resp = await fetch(this._baseUrl() + '/' + gameName + '/' + gameID + '/join', { method: 'POST', body: JSON.stringify({ playerID: playerID, playerName: this.playerName }), headers: { 'Content-Type': 'application/json' } }); if (resp.status !== 200) throw new Error('HTTP status ' + resp.status); var json = await resp.json(); inst.players[Number.parseInt(playerID)].name = this.playerName; this.playerCredentials = json.playerCredentials; } catch (error) { throw new Error('failed to join room ' + gameID + ' (' + error + ')'); } } }, { key: "leave", value: async function leave(gameName, gameID) { try { var inst = this._getGameInstance(gameID); if (!inst) throw new Error('game instance not found'); var _iteratorNormalCompletion6 = true; var _didIteratorError6 = false; var _iteratorError6 = undefined; try { for (var _iterator6 = inst.players[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { var player = _step6.value; if (player.name === this.playerName) { var resp = await fetch(this._baseUrl() + '/' + gameName + '/' + gameID + '/leave', { method: 'POST', body: JSON.stringify({ playerID: player.id, credentials: this.playerCredentials }), headers: { 'Content-Type': 'application/json' } }); if (resp.status !== 200) { throw new Error('HTTP status ' + resp.status); } delete player.name; delete this.playerCredentials; return; } } } catch (err) { _didIteratorError6 = true; _iteratorError6 = err; } finally { try { if (!_iteratorNormalCompletion6 && _iterator6["return"] != null) { _iterator6["return"](); } } finally { if (_didIteratorError6) { throw _iteratorError6; } } } throw new Error('player not found in room'); } catch (error) { throw new Error('failed to leave room ' + gameID + ' (' + error + ')'); } } }, { key: "disconnect", value: async function disconnect() { var inst = this._findPlayer(this.playerName); if (inst) { await this.leave(inst.gameName, inst.gameID); } this.rooms = []; this.playerName = 'Visitor'; } }, { key: "create", value: async function create(gameName, numPlayers) { try { var comp = this._getGameComponents(gameName); if (!comp) throw new Error('game not found'); if (numPlayers < comp.game.minPlayers || numPlayers > comp.game.maxPlayers) throw new Error('invalid number of players ' + numPlayers); var resp = await fetch(this._baseUrl() + '/' + gameName + '/create', { method: 'POST', body: JSON.stringify({ numPlayers: numPlayers }), headers: { 'Content-Type': 'application/json' } }); if (resp.status !== 200) throw new Error('HTTP status ' + resp.status); } catch (error) { throw new Error('failed to create room for ' + gameName + ' (' + error + ')'); } } }]); return _LobbyConnectionImpl; }(); /** * LobbyConnection * * Lobby model. * * @param {string} server - '<host>:<port>' of the server. * @param {Array} gameComponents - A map of Board and Game objects for the supported games. * @param {string} playerName - The name of the player. * @param {string} playerCredentials - The credentials currently used by the player, if any. * * Returns: * A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances. */ function LobbyConnection(opts) { return new _LobbyConnectionImpl(opts); } var LobbyLoginForm = /*#__PURE__*/ function (_React$Component) { _inherits(LobbyLoginForm, _React$Component); function LobbyLoginForm() { var _getPrototypeOf2; var _this; _classCallCheck(this, LobbyLoginForm); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(LobbyLoginForm)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "state", { playerName: _this.props.playerName, nameErrorMsg: '' }); _defineProperty(_assertThisInitialized(_this), "onClickEnter", function () { if (_this.state.playerName === '') return; _this.props.onEnter(_this.state.playerName); }); _defineProperty(_assertThisInitialized(_this), "onKeyPress", function (event) { if (event.key === 'Enter') { _this.onClickEnter(); } }); _defineProperty(_assertThisInitialized(_this), "onChangePlayerName", function (event) { var name = event.target.value.trim(); _this.setState({ playerName: name, nameErrorMsg: name.length > 0 ? '' : 'empty player name' }); }); return _this; } _createClass(LobbyLoginForm, [{ key: "render", value: function render() { return React.createElement("div", null, React.createElement("p", { className: "phase-title" }, "Choose a player name:"), React.createElement("input", { type: "text", value: this.state.playerName, onChange: this.onChangePlayerName, onKeyPress: this.onKeyPress }), React.createElement("span", { className: "buttons" }, React.createElement("button", { className: "buttons", onClick: this.onClickEnter }, "Enter")), React.createElement("br", null), React.createElement("span", { className: "error-msg" }, this.state.nameErrorMsg, React.createElement("br", null))); } }]); return LobbyLoginForm; }(React.Component); _defineProperty(LobbyLoginForm, "propTypes", { playerName: PropTypes.string, onEnter: PropTypes.func.isRequired }); _defineProperty(LobbyLoginForm, "defaultProps", { playerName: '' }); var LobbyRoomInstance = /*#__PURE__*/ function (_React$Component) { _inherits(LobbyRoomInstance, _React$Component); function LobbyRoomInstance() { var _getPrototypeOf2; var _this; _classCallCheck(this, LobbyRoomInstance); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(LobbyRoomInstance)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "_createSeat", function (player) { return player.name || '[free]'; }); _defineProperty(_assertThisInitialized(_this), "_createButtonJoin", function (inst, seatId) { return React.createElement("button", { key: 'button-join-' + inst.gameID, onClick: function onClick() { return _this.props.onClickJoin(inst.gameName, inst.gameID, '' + seatId); } }, "Join"); }); _defineProperty(_assertThisInitialized(_this), "_createButtonLeave", function (inst) { return React.createElement("button", { key: 'button-leave-' + inst.gameID, onClick: function onClick() { return _this.props.onClickLeave(inst.gameName, inst.gameID); } }, "Leave"); }); _defineProperty(_assertThisInitialized(_this), "_createButtonPlay", function (inst, seatId) { return React.createElement("button", { key: 'button-play-' + inst.gameID, onClick: function onClick() { return _this.props.onClickPlay(inst.gameName, { gameID: inst.gameID, playerID: '' + seatId, numPlayers: inst.players.length }); } }, "Play"); }); _defineProperty(_assertThisInitialized(_this), "_createButtonSpectate", function (inst) { return React.createElement("button", { key: 'button-spectate-' + inst.gameID, onClick: function onClick() { return _this.props.onClickPlay(inst.gameName, { gameID: inst.gameID, numPlayers: inst.players.length }); } }, "Spectate"); }); _defineProperty(_assertThisInitialized(_this), "_createInstanceButtons", function (inst) { var playerSeat = inst.players.find(function (player) { return player.name === _this.props.playerName; }); var freeSeat = inst.players.find(function (player) { return !player.name; }); if (playerSeat && freeSeat) { // already seated: waiting for game to start return _this._createButtonLeave(inst); } if (freeSeat) { // at least 1 seat is available return _this._createButtonJoin(inst, freeSeat.id); } // room is full if (playerSeat) { return React.createElement("div", null, [_this._createButtonPlay(inst, playerSeat.id), _this._createButtonLeave(inst)]); } // allow spectating return _this._createButtonSpectate(inst); }); return _this; } _createClass(LobbyRoomInstance, [{ key: "render", value: function render() { var room = this.props.room; var status = 'OPEN'; if (!room.players.find(function (player) { return !player.name; })) { status = 'RUNNING'; } return React.createElement("tr", { key: 'line-' + room.gameID }, React.createElement("td", { key: 'cell-name-' + room.gameID }, room.gameName), React.createElement("td", { key: 'cell-status-' + room.gameID }, status), React.createElement("td", { key: 'cell-seats-' + room.gameID }, room.players.map(this._createSeat).join(', ')), React.createElement("td", { key: 'cell-buttons-' + room.gameID }, this._createInstanceButtons(room))); } }]); return LobbyRoomInstance; }(React.Component); _defineProperty(LobbyRoomInstance, "propTypes", { room: PropTypes.shape({ gameName: PropTypes.string.isRequired, gameID: PropTypes.string.isRequired, players: PropTypes.array.isRequired }), playerName: PropTypes.string.isRequired, onClickJoin: PropTypes.func.isRequired, onClickLeave: PropTypes.func.isRequired, onClickPlay: PropTypes.func.isRequired }); var LobbyCreateRoomForm = /*#__PURE__*/ function (_React$Component) { _inherits(LobbyCreateRoomForm, _React$Component); function LobbyCreateRoomForm(props) { var _this; _classCallCheck(this, LobbyCreateRoomForm); _this = _possibleConstructorReturn(this, _getPrototypeOf(LobbyCreateRoomForm).call(this, props)); /* fix min and max number of players */ _defineProperty(_assertThisInitialized(_this), "state", { selectedGame: 0, numPlayers: 2 }); _defineProperty(_assertThisInitialized(_this), "_createGameNameOption", function (game, idx) { return React.createElement("option", { key: 'name-option-' + idx, value: idx }, game.game.name); }); _defineProperty(_assertThisInitialized(_this), "_createNumPlayersOption", function (idx) { return React.createElement("option", { key: 'num-option-' + idx, value: idx }, idx); }); _defineProperty(_assertThisInitialized(_this), "_createNumPlayersRange", function (game) { return _toConsumableArray(new Array(game.maxPlayers + 1).keys()).slice(game.minPlayers); }); _defineProperty(_assertThisInitialized(_this), "onChangeNumPlayers", function (event) { _this.setState({ numPlayers: Number.parseInt(event.target.value) }); }); _defineProperty(_assertThisInitialized(_this), "onChangeSelectedGame", function (event) { var idx = Number.parseInt(event.target.value); _this.setState({ selectedGame: idx, numPlayers: _this.props.games[idx].game.minPlayers }); }); _defineProperty(_assertThisInitialized(_this), "onClickCreate", function () { _this.props.createGame(_this.props.games[_this.state.selectedGame].game.name, _this.state.numPlayers); }); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = props.games[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var game = _step.value; var game_details = game.game; if (!game_details.minPlayers) { game_details.minPlayers = 1; } if (!game_details.maxPlayers) { game_details.maxPlayers = 4; } console.assert(game_details.maxPlayers >= game_details.minPlayers); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } _this.state = { selectedGame: 0, numPlayers: props.games[0].game.minPlayers }; return _this; } _createClass(LobbyCreateRoomForm, [{ key: "render", value: function render() { var _this2 = this; return React.createElement("div", null, React.createElement("select", { value: this.state.selectedGame, onChange: function onChange(evt) { return _this2.onChangeSelectedGame(evt); } }, this.props.games.map(this._createGameNameOption)), React.createElement("span", null, "Players:"), React.createElement("select", { value: this.state.numPlayers, onChange: this.onChangeNumPlayers }, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map(this._createNumPlayersOption)), React.createElement("span", { className: "buttons" }, React.createElement("button", { onClick: this.onClickCreate }, "Create"))); } }]); return LobbyCreateRoomForm; }(React.Component); _defineProperty(LobbyCreateRoomForm, "propTypes", { games: PropTypes.array.isRequired, createGame: PropTypes.func.isRequired }); var LobbyPhases = { ENTER: 'enter', PLAY: 'play', LIST: 'list' }; /** * Lobby * * React lobby component. * * @param {Array} gameComponents - An array of Board and Game objects for the supported games. * @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000'). * If not set, defaults to the server that served the page. * @param {string} gameServer - Address of the game server (for example 'localhost:8001'). * If not set, defaults to the server that served the page. * @param {function} clientFactory - Function that is used to create the game clients. * @param {number} refreshInterval - Interval between server updates (default: 2000ms). * @param {bool} debug - Enable debug information (default: false). * * Returns: * A React component that provides a UI to create, list, join, leave, play or spectate game instances. */ var Lobby = /*#__PURE__*/ function (_React$Component) { _inherits(Lobby, _React$Component); function Lobby(_props) { var _this; _classCallCheck(this, Lobby); _this = _possibleConstructorReturn(this, _getPrototypeOf(Lobby).call(this, _props)); _defineProperty(_assertThisInitialized(_this), "state", { phase: LobbyPhases.ENTER, playerName: 'Visitor', runningGame: null, errorMsg: '', credentialStore: {} }); _defineProperty(_assertThisInitialized(_this), "_createConnection", function (props) { var name = _this.state.playerName; _this.connection = LobbyConnection({ server: props.lobbyServer, gameComponents: props.gameComponents, playerName: name, playerCredentials: _this.state.credentialStore[name] }); }); _defineProperty(_assertThisInitialized(_this), "_updateCredentials", function (playerName, credentials) { _this.setState(function (prevState) { // clone store or componentDidUpdate will not be triggered var store = Object.assign({}, prevState.credentialStore); store[[playerName]] = credentials; return { credentialStore: store }; }); }); _defineProperty(_assertThisInitialized(_this), "_updateConnection", async function () { await _this.connection.refresh(); _this.forceUpdate(); }); _defineProperty(_assertThisInitialized(_this), "_enterLobby", function (playerName) { _this.setState({ playerName: playerName, phase: LobbyPhases.LIST }); }); _defineProperty(_assertThisInitialized(_this), "_exitLobby", async function () { await _this.connection.disconnect(); _this.setState({ phase: LobbyPhases.ENTER, errorMsg: '' }); }); _defineProperty(_assertThisInitialized(_this), "_createRoom", async function (gameName, numPlayers) { try { await _this.connection.create(gameName, numPlayers); await _this.connection.refresh(); // rerender _this.setState({}); } catch (error) { _this.setState({ errorMsg: error.message }); } }); _defineProperty(_assertThisInitialized(_this), "_joinRoom", async function (gameName, gameID, playerID) { try { await _this.connection.join(gameName, gameID, playerID); await _this.connection.refresh(); _this._updateCredentials(_this.connection.playerName, _this.connection.playerCredentials); } catch (error) { _this.setState({ errorMsg: error.message }); } }); _defineProperty(_assertThisInitialized(_this), "_leaveRoom", async function (gameName, gameID) { try { await _this.connection.leave(gameName, gameID); await _this.connection.refresh(); _this._updateCredentials(_this.connection.playerName, _this.connection.playerCredentials); } catch (error) { _this.setState({ errorMsg: error.message }); } }); _defineProperty(_assertThisInitialized(_this), "_startGame", function (gameName, gameOpts) { var gameCode = _this.connection._getGameComponents(gameName); if (!gameCode) { _this.setState({ errorMsg: 'game ' + gameName + ' not supported' }); return; } var multiplayer = undefined; if (gameOpts.numPlayers > 1) { if (_this.props.gameServer) { multiplayer = SocketIO({ server: _this.props.gameServer }); } else { multiplayer = SocketIO(); } } if (gameOpts.numPlayers == 1) { var maxPlayers = gameCode.game.maxPlayers; var bots = {}; for (var i = 1; i < maxPlayers; i++) { bots[i + ''] = MCTSBot; } multiplayer = Local({ bots: bots }); } var app = _this.props.clientFactory({ game: gameCode.game, board: gameCode.board, debug: _this.props.debug, multiplayer: multiplayer }); var game = { app: app, gameID: gameOpts.gameID, playerID: gameOpts.numPlayers > 1 ? gameOpts.playerID : '0', credentials: _this.connection.playerCredentials }; _this.setState({ phase: LobbyPhases.PLAY, runningGame: game }); }); _defineProperty(_assertThisInitialized(_this), "_exitRoom", function () { _this.setState({ phase: LobbyPhases.LIST, runningGame: null }); }); _defineProperty(_assertThisInitialized(_this), "_getPhaseVisibility", function (phase) { return _this.state.phase !== phase ? 'hidden' : 'phase'; }); _defineProperty(_assertThisInitialized(_this), "renderRooms", function (rooms, playerName) { return rooms.map(function (room) { var gameID = room.gameID, gameName = room.gameName, players = room.players; return React.createElement(LobbyRoomInstance, { key: 'instance-' + gameID, room: { gameID: gameID, gameName: gameName, players: Object.values(players) }, playerName: playerName, onClickJoin: _this._joinRoom, onClickLeave: _this._leaveRoom, onClickPlay: _this._startGame }); }); }); _this._createConnection(_this.props); setInterval(_this._updateConnection, _this.props.refreshInterval); return _this; } _createClass(Lobby, [{ key: "componentDidMount", value: function componentDidMount() { var cookie = Cookies.load('lobbyState') || {}; if (cookie.phase && cookie.phase === LobbyPhases.PLAY) { cookie.phase = LobbyPhases.LIST; } this.setState({ phase: cookie.phase || LobbyPhases.ENTER, playerName: cookie.playerName || 'Visitor', credentialStore: cookie.credentialStore || {} }); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { var name = this.state.playerName; var creds = this.state.credentialStore[name]; if (prevState.phase !== this.state.phase || prevState.credentialStore[name] !== creds || prevState.playerName !== name) { this._createConnection(this.props); this._updateConnection(); var cookie = { phase: this.state.phase, playerName: name, credentialStore: this.state.credentialStore }; Cookies.save('lobbyState', cookie, { path: '/' }); } } }, { key: "render", value: function render() { var _this$props = this.props, gameComponents = _this$props.gameComponents, renderer = _this$props.renderer; var _this$state = this.state, errorMsg = _this$state.errorMsg, playerName = _this$state.playerName, phase = _this$state.phase, runningGame = _this$state.runningGame; if (renderer) { return renderer({ errorMsg: errorMsg, gameComponents: gameComponents, rooms: this.connection.rooms, phase: phase, playerName: playerName, runningGame: runningGame, handleEnterLobby: this._enterLobby, handleExitLobby: this._exitLobby, handleCreateRoom: this._createRoom, handleJoinRoom: this._joinRoom, handleLeaveRoom: this._leaveRoom, handleExitRoom: this._exitRoom, handleRefreshRooms: this._updateConnection, handleStartGame: this._startGame }); } return React.createElement("div", { id: "lobby-view", style: { padding: 50 } }, React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.ENTER) }, React.createElement(LobbyLoginForm, { key: playerName, playerName: playerName, onEnter: this._enterLobby })), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.LIST) }, React.createElement("p", null, "Welcome, ", playerName), React.createElement("div", { className: "phase-title", id: "game-creation" }, React.createElement("span", null, "Create a room:"), React.createElement(LobbyCreateRoomForm, { games: gameComponents, createGame: this._createRoom })), React.createElement("p", { className: "phase-title" }, "Join a room:"), React.createElement("div", { id: "instances" }, React.createElement("table", null, React.createElement("tbody", null, this.renderRooms(this.connection.rooms, playerName))), React.createElement("span", { className: "error-msg" }, errorMsg, React.createElement("br", null))), React.createElement("p", { className: "phase-title" }, "Rooms that become empty are automatically deleted.")), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.PLAY) }, runningGame && React.createElement(runningGame.app, { gameID: runningGame.gameID, playerID: runningGame.playerID, credentials: runningGame.credentials }), React.createElement("div", { className: "buttons", id: "game-exit" }, React.createElement("button", { onClick: this._exitRoom }, "Exit game"))), React.createElement("div", { className: "buttons", id: "lobby-exit" }, React.createElement("button", { onClick: this._exitLobby }, "Exit lobby"))); } }]); return Lobby; }(React.Component); _defineProperty(Lobby, "propTypes", { gameComponents: PropTypes.array.isRequired, lobbyServer: PropTypes.string, gameServer: PropTypes.string, debug: PropTypes.bool, clientFactory: PropTypes.func, refreshInterval: PropTypes.number }); _defineProperty(Lobby, "defaultProps", { debug: false, clientFactory: Client, refreshInterval: 2000 }); export { Client, Lobby };
ajax/libs/material-ui/4.9.2/esm/utils/focusVisible.js
cdnjs/cdnjs
// based on https://github.com/WICG/focus-visible/blob/v4.1.5/src/focus-visible.js import React from 'react'; import ReactDOM from 'react-dom'; var hadKeyboardEvent = true; var hadFocusVisibleRecently = false; var hadFocusVisibleRecentlyTimeout = null; var inputTypesWhitelist = { text: true, search: true, url: true, tel: true, email: true, password: true, number: true, date: true, month: true, week: true, time: true, datetime: true, 'datetime-local': true }; /** * Computes whether the given element should automatically trigger the * `focus-visible` class being added, i.e. whether it should always match * `:focus-visible` when focused. * @param {Element} node * @return {boolean} */ function focusTriggersKeyboardModality(node) { var type = node.type, tagName = node.tagName; if (tagName === 'INPUT' && inputTypesWhitelist[type] && !node.readOnly) { return true; } if (tagName === 'TEXTAREA' && !node.readOnly) { return true; } if (node.isContentEditable) { return true; } return false; } /** * Keep track of our keyboard modality state with `hadKeyboardEvent`. * If the most recent user interaction was via the keyboard; * and the key press did not include a meta, alt/option, or control key; * then the modality is keyboard. Otherwise, the modality is not keyboard. * @param {KeyboardEvent} event */ function handleKeyDown(event) { if (event.metaKey || event.altKey || event.ctrlKey) { return; } hadKeyboardEvent = true; } /** * If at any point a user clicks with a pointing device, ensure that we change * the modality away from keyboard. * This avoids the situation where a user presses a key on an already focused * element, and then clicks on a different element, focusing it with a * pointing device, while we still think we're in keyboard modality. */ function handlePointerDown() { hadKeyboardEvent = false; } function handleVisibilityChange() { if (this.visibilityState === 'hidden') { // If the tab becomes active again, the browser will handle calling focus // on the element (Safari actually calls it twice). // If this tab change caused a blur on an element with focus-visible, // re-apply the class when the user switches back to the tab. if (hadFocusVisibleRecently) { hadKeyboardEvent = true; } } } function prepare(doc) { doc.addEventListener('keydown', handleKeyDown, true); doc.addEventListener('mousedown', handlePointerDown, true); doc.addEventListener('pointerdown', handlePointerDown, true); doc.addEventListener('touchstart', handlePointerDown, true); doc.addEventListener('visibilitychange', handleVisibilityChange, true); } export function teardown(doc) { doc.removeEventListener('keydown', handleKeyDown, true); doc.removeEventListener('mousedown', handlePointerDown, true); doc.removeEventListener('pointerdown', handlePointerDown, true); doc.removeEventListener('touchstart', handlePointerDown, true); doc.removeEventListener('visibilitychange', handleVisibilityChange, true); } function isFocusVisible(event) { var target = event.target; try { return target.matches(':focus-visible'); } catch (error) {} // browsers not implementing :focus-visible will throw a SyntaxError // we use our own heuristic for those browsers // rethrow might be better if it's not the expected error but do we really // want to crash if focus-visible malfunctioned? // no need for validFocusTarget check. the user does that by attaching it to // focusable events only return hadKeyboardEvent || focusTriggersKeyboardModality(target); } /** * Should be called if a blur event is fired on a focus-visible element */ function handleBlurVisible() { // To detect a tab/window switch, we look for a blur event followed // rapidly by a visibility change. // If we don't see a visibility change within 100ms, it's probably a // regular focus change. hadFocusVisibleRecently = true; window.clearTimeout(hadFocusVisibleRecentlyTimeout); hadFocusVisibleRecentlyTimeout = window.setTimeout(function () { hadFocusVisibleRecently = false; }, 100); } export function useIsFocusVisible() { var ref = React.useCallback(function (instance) { var node = ReactDOM.findDOMNode(instance); if (node != null) { prepare(node.ownerDocument); } }, []); return { isFocusVisible: isFocusVisible, onBlurVisible: handleBlurVisible, ref: ref }; }
ajax/libs/primereact/6.5.1/badge/badge.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Badge = /*#__PURE__*/function (_Component) { _inherits(Badge, _Component); var _super = _createSuper(Badge); function Badge() { _classCallCheck(this, Badge); return _super.apply(this, arguments); } _createClass(Badge, [{ key: "render", value: function render() { var badgeClassName = classNames('p-badge p-component', { 'p-badge-no-gutter': this.props.value && String(this.props.value).length === 1, 'p-badge-dot': !this.props.value, 'p-badge-lg': this.props.size === 'large', 'p-badge-xl': this.props.size === 'xlarge', 'p-badge-info': this.props.severity === 'info', 'p-badge-success': this.props.severity === 'success', 'p-badge-warning': this.props.severity === 'warning', 'p-badge-danger': this.props.severity === 'danger' }, this.props.className); return /*#__PURE__*/React.createElement("span", { className: badgeClassName, style: this.props.style }, this.props.value); } }]); return Badge; }(Component); _defineProperty(Badge, "defaultProps", { value: null, severity: null, size: null, style: null, className: null }); export { Badge };